idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
151,600
|
protected ClusterMutex getClusterMutexInternal ( final String mutexName ) { final TransactionOperations transactionOperations = this . getTransactionOperations ( ) ; return transactionOperations . execute ( new TransactionCallback < ClusterMutex > ( ) { @ Override public ClusterMutex doInTransaction ( TransactionStatus status ) { final CacheKey key = CacheKey . build ( CLUSTER_MUTEX_SOURCE , mutexName ) ; ClusterMutex clusterMutex = entityManagerCache . get ( BasePortalJpaDao . PERSISTENCE_UNIT_NAME , key ) ; if ( clusterMutex != null ) { return clusterMutex ; } final NaturalIdQuery < ClusterMutex > query = createNaturalIdQuery ( ClusterMutex . class ) ; query . using ( ClusterMutex_ . name , mutexName ) ; clusterMutex = query . load ( ) ; entityManagerCache . put ( BasePortalJpaDao . PERSISTENCE_UNIT_NAME , key , clusterMutex ) ; return clusterMutex ; } } ) ; }
|
Retrieves a ClusterMutex in a new TX
| 233
| 11
|
151,601
|
protected void createClusterMutex ( final String mutexName ) { this . executeIgnoreRollback ( new TransactionCallbackWithoutResult ( ) { @ Override protected void doInTransactionWithoutResult ( TransactionStatus status ) { final EntityManager entityManager = getEntityManager ( ) ; final ClusterMutex clusterMutex = new ClusterMutex ( mutexName ) ; entityManager . persist ( clusterMutex ) ; try { entityManager . flush ( ) ; logger . trace ( "Created {}" , clusterMutex ) ; } catch ( PersistenceException e ) { if ( e . getCause ( ) instanceof ConstraintViolationException ) { // ignore, another thread beat us to creation logger . debug ( "Failed to create mutex, it was likely created concurrently by another thread: " + clusterMutex , e ) ; return ; } // re-throw exception with unhandled cause throw e ; } } } ) ; }
|
Creates a new ClusterMutex with the specified name . Returns the created mutex or null if the mutex already exists .
| 197
| 26
|
151,602
|
protected void validateLockedMutex ( ClusterMutex clusterMutex ) { if ( ! clusterMutex . isLocked ( ) ) { throw new IllegalMonitorStateException ( "Mutex is not currently locked, it cannot be updated: " + clusterMutex ) ; } final String serverName = this . portalInfoProvider . getUniqueServerName ( ) ; if ( ! serverName . equals ( clusterMutex . getServerId ( ) ) ) { throw new IllegalMonitorStateException ( "Mutex is currently locked by another server: " + clusterMutex + " local serverName: " + serverName ) ; } }
|
Validates that the specified mutex is locked by this server throws IllegalMonitorStateException if either test fails
| 132
| 21
|
151,603
|
protected void unlockAbandonedLock ( final String mutexName ) { this . executeIgnoreRollback ( new TransactionCallbackWithoutResult ( ) { @ Override protected void doInTransactionWithoutResult ( TransactionStatus status ) { final EntityManager entityManager = getEntityManager ( ) ; final ClusterMutex clusterMutex = getClusterMutex ( mutexName ) ; if ( ! isLockAbandoned ( clusterMutex ) ) { // No longer abandoned return ; } logger . warn ( "Unlocking abandoned " + clusterMutex ) ; clusterMutex . unlock ( ) ; entityManager . persist ( clusterMutex ) ; try { entityManager . flush ( ) ; } catch ( OptimisticLockException e ) { logger . trace ( "Abandoned mutex {} was cleared by another thread or server" , mutexName ) ; } } } ) ; }
|
Unlocks an abandoned mutex
| 183
| 6
|
151,604
|
protected < T > T executeIgnoreRollback ( TransactionCallback < T > action , T rollbackValue ) { try { // Try to create the mutex in a new TX return this . newTransactionTemplate . execute ( action ) ; } catch ( TransactionSystemException e ) { if ( e . getCause ( ) instanceof RollbackException ) { // Ignore rollbacks return rollbackValue ; } // re-throw exception with unhandled cause throw e ; } }
|
Utility for using TransactionTemplate when we know that a rollback might happen and just want to ignore it
| 97
| 21
|
151,605
|
public boolean hasAnyFavorites ( IUserLayout layout ) { Validate . notNull ( layout , "Cannot determine whether a null layout contains favorites." ) ; // (premature) performance optimization: short circuit returns true if nonzero favorite // portlets return ( ! getFavoritePortletLayoutNodes ( layout ) . isEmpty ( ) || ! getFavoriteCollections ( layout ) . isEmpty ( ) ) ; }
|
True if the layout contains any favorited collections or favorited individual portlets false otherwise .
| 89
| 18
|
151,606
|
@ Override public void perform ( ) throws PortalException { // push the change into the PLF if ( nodeId . startsWith ( Constants . FRAGMENT_ID_USER_PREFIX ) ) { // we are dealing with an incorporated node, so get a plf ghost // node, set its attribute, then add a directive indicating the // attribute that should be pushed into the ilf during merge Element plfNode = HandlerUtils . getPLFNode ( ilfNode , person , true , // create node if not found false ) ; // don't create children plfNode . setAttribute ( name , value ) ; /* * add directive to hold override value. This is not necessary for * folder names since they are overridden at render time with their * locale specific version and persisted via a different mechanism. */ EditManager . addEditDirective ( plfNode , name , person ) ; } else { // node owned by user so change attribute in child directly Document plf = RDBMDistributedLayoutStore . getPLF ( person ) ; Element plfNode = plf . getElementById ( nodeId ) ; if ( plfNode != null ) // should always be non-null { plfNode . setAttribute ( name , value ) ; } } /* * push the change into the ILF if not the name attribute. For names * the rendering will inject the localized name via a special processor. * So it doesn't matter what is in the ILF's folder name attribute. */ if ( ! name . equals ( Constants . ATT_NAME ) ) // should always be non-null { ilfNode . setAttribute ( name , value ) ; } }
|
Apply the attribute change .
| 353
| 5
|
151,607
|
protected Map < String , String > getUserInfo ( String remoteUser , HttpServletRequest httpServletRequest , IPortletWindow portletWindow ) throws PortletContainerException { // Get the list of user attributes the portal knows about the user final IPersonAttributes personAttributes = this . personAttributeDao . getPerson ( remoteUser ) ; if ( personAttributes == null ) { return Collections . emptyMap ( ) ; } final List < ? extends UserAttribute > expectedUserAttributes = this . getExpectedUserAttributes ( httpServletRequest , portletWindow ) ; final Map < String , String > portletUserAttributes = this . generateUserInfo ( personAttributes , expectedUserAttributes , httpServletRequest ) ; return portletUserAttributes ; }
|
Commons logic to get a subset of the user s attributes for the specified portlet window .
| 158
| 19
|
151,608
|
protected Map < String , String > generateUserInfo ( final IPersonAttributes personAttributes , final List < ? extends UserAttribute > expectedUserAttributes , HttpServletRequest httpServletRequest ) { final Map < String , String > portletUserAttributes = new HashMap < String , String > ( expectedUserAttributes . size ( ) ) ; // Copy expected attributes to the USER_INFO Map final Map < String , List < Object > > attributes = personAttributes . getAttributes ( ) ; for ( final UserAttribute userAttributeDD : expectedUserAttributes ) { final String attributeName = userAttributeDD . getName ( ) ; // TODO a personAttributes.hasAttribute(String) API is needed here, if hasAttribute and // null then put the key with no value in the returned map if ( attributes . containsKey ( attributeName ) ) { final Object valueObj = personAttributes . getAttributeValue ( attributeName ) ; final String value = valueObj == null ? null : String . valueOf ( valueObj ) ; portletUserAttributes . put ( attributeName , value ) ; } } return portletUserAttributes ; }
|
Using the Map of portal user attributes and a List of expected attributes generate the USER_INFO map for the portlet
| 234
| 24
|
151,609
|
@ RequestMapping public void service ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { response . setHeader ( "Pragma" , "no-cache" ) ; response . setHeader ( "Cache-Control" , "no-cache" ) ; response . setDateHeader ( "Expires" , 0 ) ; // create the redirect URL, adding fname and args parameters if necessary String redirectTarget = null ; final String refUrl = request . getParameter ( REFERER_URL_PARAM ) ; final URL redirectLocation = parseLocalRefUrl ( request , refUrl ) ; if ( redirectLocation != null ) { redirectTarget = redirectLocation . toString ( ) ; } if ( redirectTarget == null ) { /* Grab the target functional name, if any, off the login request. * Also any arguments for the target. We will pass them along after authentication. */ String targetFname = request . getParameter ( "uP_fname" ) ; if ( targetFname == null ) { final IPortalUrlBuilder defaultUrl = this . portalUrlProvider . getDefaultUrl ( request ) ; redirectTarget = defaultUrl . getUrlString ( ) ; } else { try { final IPortalUrlBuilder urlBuilder = this . portalUrlProvider . getPortalUrlBuilderByPortletFName ( request , targetFname , UrlType . RENDER ) ; Enumeration < String > e = request . getParameterNames ( ) ; while ( e . hasMoreElements ( ) ) { String paramName = e . nextElement ( ) ; if ( ! paramName . equals ( "uP_fname" ) ) { urlBuilder . addParameter ( paramName , request . getParameterValues ( paramName ) ) ; } } redirectTarget = urlBuilder . getUrlString ( ) ; } catch ( IllegalArgumentException e ) { final IPortalUrlBuilder defaultUrl = this . portalUrlProvider . getDefaultUrl ( request ) ; redirectTarget = defaultUrl . getUrlString ( ) ; } } } IPerson person = null ; final Object authError = request . getSession ( false ) . getAttribute ( LoginController . AUTH_ERROR_KEY ) ; if ( authError == null || ! ( ( Boolean ) authError ) ) { person = this . personManager . getPerson ( request ) ; } if ( person == null || ! person . getSecurityContext ( ) . isAuthenticated ( ) ) { if ( request . getMethod ( ) . equals ( "POST" ) ) request . getSession ( false ) . setAttribute ( AUTH_ATTEMPTED_KEY , "true" ) ; // Preserve the attempted username so it can be redisplayed to the user String attemptedUserName = request . getParameter ( "userName" ) ; if ( attemptedUserName != null ) request . getSession ( false ) . setAttribute ( ATTEMPTED_USERNAME_KEY , request . getParameter ( "userName" ) ) ; } final String encodedRedirectURL = response . encodeRedirectURL ( redirectTarget ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Redirecting to " + redirectTarget ) ; } response . sendRedirect ( encodedRedirectURL ) ; }
|
Process the incoming HttpServletRequest . Note that this processing occurs after PortalPreAuthenticatedProcessingFilter has run and performed pre - processing .
| 697
| 30
|
151,610
|
protected void selectFormDefaultPortlet ( final F report ) { final Set < AggregatedPortletMapping > portlets = this . getPortlets ( ) ; if ( ! portlets . isEmpty ( ) ) { report . getPortlets ( ) . add ( portlets . iterator ( ) . next ( ) . getFname ( ) ) ; } }
|
Select the first portlet name by default for the form
| 77
| 11
|
151,611
|
private void getMetaData ( final Connection conn ) { try { final DatabaseMetaData dmd = conn . getMetaData ( ) ; this . databaseProductName = dmd . getDatabaseProductName ( ) ; this . databaseProductVersion = dmd . getDatabaseProductVersion ( ) ; this . driverName = dmd . getDriverName ( ) ; this . driverVersion = dmd . getDriverVersion ( ) ; this . userName = dmd . getUserName ( ) ; this . dbUrl = dmd . getURL ( ) ; this . dbmdSupportsOuterJoins = dmd . supportsOuterJoins ( ) ; } catch ( SQLException sqle ) { LOG . error ( "Error getting database meta data." , sqle ) ; } }
|
Gets meta data about the connection .
| 166
| 8
|
151,612
|
@ RequestMapping ( headers = { "org.apereo.portal.url.UrlType=ACTION" } , method = RequestMethod . POST ) public void actionRequest ( HttpServletRequest request , HttpServletResponse response ) throws IOException { final IPortalRequestInfo portalRequestInfo = this . urlSyntaxProvider . getPortalRequestInfo ( request ) ; final IPortletRequestInfo portletRequestInfo = portalRequestInfo . getTargetedPortletRequestInfo ( ) ; final IPortalUrlBuilder actionRedirectUrl ; if ( portletRequestInfo != null ) { final IPortletWindowId targetWindowId = portletRequestInfo . getPortletWindowId ( ) ; actionRedirectUrl = this . portalUrlProvider . getPortalUrlBuilderByPortletWindow ( request , targetWindowId , UrlType . RENDER ) ; } else { final String targetedLayoutNodeId = portalRequestInfo . getTargetedLayoutNodeId ( ) ; if ( targetedLayoutNodeId != null ) { actionRedirectUrl = this . portalUrlProvider . getPortalUrlBuilderByLayoutNode ( request , targetedLayoutNodeId , UrlType . RENDER ) ; } else { actionRedirectUrl = this . portalUrlProvider . getDefaultUrl ( request ) ; } } // Stuff the action-redirect URL builder into the request so other code can use it during // request processing this . portalUrlProvider . convertToPortalActionUrlBuilder ( request , actionRedirectUrl ) ; if ( portletRequestInfo != null ) { final IPortletWindowId targetWindowId = portletRequestInfo . getPortletWindowId ( ) ; try { this . portletExecutionManager . doPortletAction ( targetWindowId , request , response ) ; } catch ( RuntimeException e ) { this . logger . error ( "Exception thrown while executing portlet action for: " + portletRequestInfo , e ) ; // TODO this should be a constant right? actionRedirectUrl . setParameter ( "portletActionError" , targetWindowId . toString ( ) ) ; } } sendRedirect ( actionRedirectUrl , response ) ; }
|
HTTP POST required for security .
| 463
| 6
|
151,613
|
public List < LocaleBean > getLocales ( Locale currentLocale ) { List < LocaleBean > locales = new ArrayList <> ( ) ; // get the array of locales available from the portal List < Locale > portalLocales = localeManagerFactory . getPortalLocales ( ) ; for ( Locale locale : portalLocales ) { if ( currentLocale != null ) { // if a current locale is available, display language names // using the current locale locales . add ( new LocaleBean ( locale , currentLocale ) ) ; } else { locales . add ( new LocaleBean ( locale ) ) ; } } return locales ; }
|
Return a list of LocaleBeans matching the currently available locales for the portal .
| 149
| 18
|
151,614
|
public Locale getCurrentUserLocale ( PortletRequest request ) { final HttpServletRequest originalPortalRequest = this . portalRequestUtils . getPortletHttpRequest ( request ) ; IUserInstance ui = userInstanceManager . getUserInstance ( originalPortalRequest ) ; IUserPreferencesManager upm = ui . getPreferencesManager ( ) ; final IUserProfile userProfile = upm . getUserProfile ( ) ; LocaleManager localeManager = userProfile . getLocaleManager ( ) ; // first check the session locales List < Locale > sessionLocales = localeManager . getSessionLocales ( ) ; if ( sessionLocales != null && sessionLocales . size ( ) > 0 ) { return sessionLocales . get ( 0 ) ; } // if no session locales were found, check the user locales List < Locale > userLocales = localeManager . getUserLocales ( ) ; if ( userLocales != null && userLocales . size ( ) > 0 ) { return userLocales . get ( 0 ) ; } // if no selected locale was found either in the session or user layout, // just return null return null ; }
|
Return the current user s locale .
| 254
| 7
|
151,615
|
public void updateUserLocale ( HttpServletRequest request , String localeString ) { IUserInstance ui = userInstanceManager . getUserInstance ( request ) ; IUserPreferencesManager upm = ui . getPreferencesManager ( ) ; final IUserProfile userProfile = upm . getUserProfile ( ) ; LocaleManager localeManager = userProfile . getLocaleManager ( ) ; if ( localeString != null ) { // build a new List<Locale> from the specified locale Locale userLocale = localeManagerFactory . parseLocale ( localeString ) ; List < Locale > locales = Collections . singletonList ( userLocale ) ; // set this locale in the session localeManager . setSessionLocales ( locales ) ; // if the current user is logged in, also update the persisted // user locale final IPerson person = ui . getPerson ( ) ; if ( ! person . isGuest ( ) ) { try { localeManager . setUserLocales ( Collections . singletonList ( userLocale ) ) ; localeStore . updateUserLocales ( person , new Locale [ ] { userLocale } ) ; // remove person layout framgent from session since it contains some of the data // in previous // translation and won't be cleared until next logout-login (applies when using // RDBMDistributedLayoutStore as user layout store). person . setAttribute ( Constants . PLF , null ) ; upm . getUserLayoutManager ( ) . loadUserLayout ( true ) ; } catch ( Exception e ) { throw new PortalException ( e ) ; } } } }
|
Update the current user s locale to match the selected locale . This implementation will update the session locale and if the user is not a guest will also update the locale in the user s persisted preferences .
| 346
| 39
|
151,616
|
public TenantOperationResponse importWithResources ( final ITenant tenant , final Set < Resource > resources ) { /* * First load dom4j Documents and sort the entity files into the proper order */ final Map < PortalDataKey , Set < BucketTuple > > importQueue ; try { importQueue = prepareImportQueue ( tenant , resources ) ; } catch ( Exception e ) { final TenantOperationResponse error = new TenantOperationResponse ( this , TenantOperationResponse . Result . ABORT ) ; error . addMessage ( createLocalizedMessage ( FAILED_TO_LOAD_TENANT_TEMPLATE , new String [ ] { tenant . getName ( ) } ) ) ; return error ; } log . trace ( "Ready to import data entity templates for new tenant '{}'; importQueue={}" , tenant . getName ( ) , importQueue ) ; // We're going to report on every item imported; TODO it would be better // if we could display human-friendly entity type name + sysid (fname, etc.) final StringBuilder importReport = new StringBuilder ( ) ; /* * Now import the identified entities each bucket in turn */ try { importQueue ( tenant , importQueue , importReport ) ; } catch ( Exception e ) { final TenantOperationResponse error = new TenantOperationResponse ( this , TenantOperationResponse . Result . ABORT ) ; error . addMessage ( finalizeImportReport ( importReport ) ) ; error . addMessage ( createLocalizedMessage ( FAILED_TO_IMPORT_TENANT_TEMPLATE_DATA , new String [ ] { tenant . getName ( ) } ) ) ; return error ; } TenantOperationResponse rslt = new TenantOperationResponse ( this , TenantOperationResponse . Result . SUCCESS ) ; rslt . addMessage ( finalizeImportReport ( importReport ) ) ; rslt . addMessage ( createLocalizedMessage ( TENANT_ENTITIES_IMPORTED , new String [ ] { tenant . getName ( ) } ) ) ; return rslt ; }
|
High - level implementation method that brokers the queuing importing and reporting that is common to Create and Update .
| 442
| 21
|
151,617
|
private Map < PortalDataKey , Set < BucketTuple > > prepareImportQueue ( final ITenant tenant , final Set < Resource > templates ) throws Exception { final Map < PortalDataKey , Set < BucketTuple > > rslt = new HashMap <> ( ) ; Resource rsc = null ; try { for ( Resource r : templates ) { rsc = r ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Loading template resource file for tenant " + "'" + tenant . getFname ( ) + "': " + rsc . getFilename ( ) ) ; } final Document doc = reader . read ( rsc . getInputStream ( ) ) ; PortalDataKey atLeastOneMatchingDataKey = null ; for ( PortalDataKey pdk : dataKeyImportOrder ) { boolean matches = evaluatePortalDataKeyMatch ( doc , pdk ) ; if ( matches ) { // Found the right bucket... log . debug ( "Found PortalDataKey '{}' for data document {}" , pdk , r . getURI ( ) ) ; atLeastOneMatchingDataKey = pdk ; Set < BucketTuple > bucket = rslt . get ( atLeastOneMatchingDataKey ) ; if ( bucket == null ) { // First of these we've seen; create the bucket; bucket = new HashSet <> ( ) ; rslt . put ( atLeastOneMatchingDataKey , bucket ) ; } BucketTuple tuple = new BucketTuple ( rsc , doc ) ; bucket . add ( tuple ) ; /* * At this point, we would normally add a break; * statement, but group_membership.xml files need to * match more than one PortalDataKey. */ } } if ( atLeastOneMatchingDataKey == null ) { // We can't proceed throw new RuntimeException ( "No PortalDataKey found for QName: " + doc . getRootElement ( ) . getQName ( ) ) ; } } } catch ( Exception e ) { log . error ( "Failed to process the specified template: {}" , ( rsc != null ? rsc . getFilename ( ) : "null" ) , e ) ; throw e ; } return rslt ; }
|
Loads dom4j Documents and sorts the entity files into the proper order for Import .
| 482
| 18
|
151,618
|
private void importQueue ( final ITenant tenant , final Map < PortalDataKey , Set < BucketTuple > > queue , final StringBuilder importReport ) throws Exception { final StandardEvaluationContext ctx = new StandardEvaluationContext ( ) ; ctx . setRootObject ( new RootObjectImpl ( tenant ) ) ; IDataTemplatingStrategy templating = new SpELDataTemplatingStrategy ( portalSpELService , ctx ) ; Document doc = null ; try { for ( PortalDataKey pdk : dataKeyImportOrder ) { Set < BucketTuple > bucket = queue . get ( pdk ) ; if ( bucket != null ) { log . debug ( "Importing the specified PortalDataKey tenant '{}': {}" , tenant . getName ( ) , pdk . getName ( ) ) ; for ( BucketTuple tuple : bucket ) { doc = tuple . getDocument ( ) ; Source data = templating . processTemplates ( doc , tuple . getResource ( ) . getURL ( ) . toString ( ) ) ; dataHandlerService . importData ( data , pdk ) ; importReport . append ( createImportReportLineItem ( pdk , tuple ) ) ; } } } } catch ( Exception e ) { log . error ( "Failed to process the specified template document:\n{}" , ( doc != null ? doc . asXML ( ) : "null" ) , e ) ; throw e ; } }
|
Imports the specified entities in the proper order .
| 315
| 10
|
151,619
|
public void updateCurrentUsername ( String newUsername ) { final String originalThreadName = originalThreadNameLocal . get ( ) ; if ( originalThreadName != null && newUsername != null ) { final Thread currentThread = Thread . currentThread ( ) ; final String threadName = getThreadName ( originalThreadName , newUsername ) ; currentThread . setName ( threadName ) ; } }
|
Update the thread name to use the specified username . Useful for authentication requests where the username changes mid - request
| 85
| 21
|
151,620
|
public Set < Entity > search ( String entityType , String searchTerm ) { if ( StringUtils . isBlank ( entityType ) && StringUtils . isBlank ( searchTerm ) ) { return null ; } Set < Entity > results = new HashSet < Entity > ( ) ; EntityEnum entityEnum = EntityEnum . getEntityEnum ( entityType ) ; EntityIdentifier [ ] identifiers ; Class < ? > identifierType ; // if the entity type is a group, use the group service's findGroup method // to locate it if ( entityEnum . isGroup ( ) ) { identifiers = GroupService . searchForGroups ( searchTerm , GroupService . SearchMethod . CONTAINS_CI , entityEnum . getClazz ( ) ) ; identifierType = IEntityGroup . class ; } // otherwise use the getGroupMember method else { identifiers = GroupService . searchForEntities ( searchTerm , GroupService . SearchMethod . CONTAINS_CI , entityEnum . getClazz ( ) ) ; identifierType = entityEnum . getClazz ( ) ; } for ( EntityIdentifier entityIdentifier : identifiers ) { if ( entityIdentifier . getType ( ) . equals ( identifierType ) ) { IGroupMember groupMember = GroupService . getGroupMember ( entityIdentifier ) ; Entity entity = getEntity ( groupMember ) ; results . add ( entity ) ; } } return results ; }
|
External search thus case insensitive .
| 306
| 6
|
151,621
|
private IAuthorizationPrincipal getAuthorizationPrincipal ( Authentication authentication ) { final Object authPrincipal = authentication . getPrincipal ( ) ; logger . trace ( "getAuthorizationPrincipal -- authPrincipal=[{}]" , authPrincipal ) ; String username ; if ( authPrincipal instanceof UserDetails ) { // User is authenticated UserDetails userDetails = ( UserDetails ) authPrincipal ; logger . trace ( "getAuthorizationPrincipal -- AUTHENTICATED, userDetails=[{}]" , userDetails ) ; username = userDetails . getUsername ( ) ; } else { // Which guest user are we? final HttpServletRequest req = portalRequestUtils . getCurrentPortalRequest ( ) ; final IPerson person = personManager . getPerson ( req ) ; logger . trace ( "getAuthorizationPrincipal -- UNAUTHENTICATED, person=[{}]" , person ) ; username = person . getUserName ( ) ; } return authorizationServiceFacade . newPrincipal ( username , IPerson . class ) ; }
|
Prepare a uPortal IAuthorizationPrincipal based in the Spring principal
| 225
| 16
|
151,622
|
public final void setDuration ( int duration ) { if ( isComplete ( ) ) { this . getLogger ( ) . warn ( "{} is already closed, the new duration of {} will be ignored on: {}" , this . getClass ( ) . getSimpleName ( ) , duration , this ) ; return ; } this . duration = duration ; }
|
Set the duration of the interval
| 75
| 6
|
151,623
|
protected IEntityGroup createUportalGroupFromGrouperGroup ( WsGroup wsGroup ) { IEntityGroup iEntityGroup = new EntityGroupImpl ( wsGroup . getName ( ) , IPerson . class ) ; // need to set the group name and description to the actual // display name and description iEntityGroup . setName ( wsGroup . getDisplayName ( ) ) ; iEntityGroup . setDescription ( wsGroup . getDescription ( ) ) ; return iEntityGroup ; }
|
Construct an IEntityGroup from a Grouper WsGroup .
| 108
| 14
|
151,624
|
protected WsGroup findGroupFromKey ( String key ) { WsGroup wsGroup = null ; if ( key != null ) { GcFindGroups gcFindGroups = new GcFindGroups ( ) ; gcFindGroups . addGroupName ( key ) ; WsFindGroupsResults results = gcFindGroups . execute ( ) ; // if no results were returned, return null if ( results != null && results . getGroupResults ( ) != null && results . getGroupResults ( ) . length > 0 ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "found group from key " + key + ": " + results . getGroupResults ( ) [ 0 ] ) ; } wsGroup = results . getGroupResults ( ) [ 0 ] ; } } return wsGroup ; }
|
Find the Grouper group matching the specified key .
| 184
| 11
|
151,625
|
protected static String getStemPrefix ( ) { String uportalStem = GrouperClientUtils . propertiesValue ( STEM_PREFIX , false ) ; // make sure it ends in colon if ( ! StringUtils . isBlank ( uportalStem ) ) { if ( uportalStem . endsWith ( ":" ) ) { uportalStem = uportalStem . substring ( 0 , uportalStem . length ( ) - 1 ) ; } } return uportalStem ; }
|
Get the prefix for the stem containing uPortal groups . If this value is non - empty all groups will be required to be prefixed with the specified stem name .
| 112
| 34
|
151,626
|
@ Override public void perform ( ) throws PortalException { // push the change into the PLF if ( nodeId . startsWith ( Constants . FRAGMENT_ID_USER_PREFIX ) ) { // we are dealing with an incorporated node ParameterEditManager . removeParmEditDirective ( nodeId , name , person ) ; } else { // node owned by user so add parameter child directly Document plf = RDBMDistributedLayoutStore . getPLF ( person ) ; Element plfNode = plf . getElementById ( nodeId ) ; removeParameterChild ( plfNode , name ) ; } // push the change into the ILF removeParameterChild ( ilfNode , name ) ; }
|
Remove the parameter from a channel in both the ILF and PLF using the appropriate mechanisms for incorporated nodes versus owned nodes .
| 153
| 25
|
151,627
|
public static PortletCategoryBean create ( String id , String name , String description , Set < PortletCategoryBean > subcategories , Set < PortletDefinitionBean > portlets ) { return new PortletCategoryBean ( id , name , description , subcategories , portlets ) ; }
|
Creates a new bean based on the provided inputs .
| 65
| 11
|
151,628
|
@ PreAuthorize ( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))" ) @ RequestMapping ( value = "/permissions/owners.json" , method = RequestMethod . GET ) public ModelAndView getOwners ( ) { // get a list of all currently defined permission owners List < IPermissionOwner > owners = permissionOwnerDao . getAllPermissionOwners ( ) ; ModelAndView mv = new ModelAndView ( ) ; mv . addObject ( "owners" , owners ) ; mv . setViewName ( "json" ) ; return mv ; }
|
Provide a JSON view of all known permission owners registered with uPortal .
| 168
| 16
|
151,629
|
@ PreAuthorize ( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))" ) @ RequestMapping ( value = "/permissions/owners/{owner}.json" , method = RequestMethod . GET ) public ModelAndView getOwners ( @ PathVariable ( "owner" ) String ownerParam , HttpServletResponse response ) { IPermissionOwner owner ; if ( StringUtils . isNumeric ( ownerParam ) ) { long id = Long . valueOf ( ownerParam ) ; owner = permissionOwnerDao . getPermissionOwner ( id ) ; } else { owner = permissionOwnerDao . getPermissionOwner ( ownerParam ) ; } // if the IPermissionOwner was found, add it to the JSON model if ( owner != null ) { ModelAndView mv = new ModelAndView ( ) ; mv . addObject ( "owner" , owner ) ; mv . setViewName ( "json" ) ; return mv ; } // otherwise return a 404 not found error code else { response . setStatus ( HttpServletResponse . SC_NOT_FOUND ) ; return null ; } }
|
Provide a detailed view of the specified IPermissionOwner . This view should contain a list of the owner s defined activities .
| 282
| 26
|
151,630
|
@ PreAuthorize ( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))" ) @ RequestMapping ( value = "/permissions/activities.json" , method = RequestMethod . GET ) public ModelAndView getActivities ( @ RequestParam ( value = "q" , required = false ) String query ) { if ( StringUtils . isNotBlank ( query ) ) { query = query . toLowerCase ( ) ; } List < IPermissionActivity > activities = new ArrayList <> ( ) ; Collection < IPermissionOwner > owners = permissionOwnerDao . getAllPermissionOwners ( ) ; for ( IPermissionOwner owner : owners ) { for ( IPermissionActivity activity : owner . getActivities ( ) ) { if ( StringUtils . isBlank ( query ) || activity . getName ( ) . toLowerCase ( ) . contains ( query ) ) { activities . add ( activity ) ; } } } Collections . sort ( activities ) ; ModelAndView mv = new ModelAndView ( ) ; mv . addObject ( "activities" , activities ) ; mv . setViewName ( "json" ) ; return mv ; }
|
Provide a list of all registered IPermissionActivities . If an optional search string is provided the returned list will be restricted to activities matching the query .
| 296
| 32
|
151,631
|
@ PreAuthorize ( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))" ) @ RequestMapping ( value = "/permissions/{activity}/targets.json" , method = RequestMethod . GET ) public ModelAndView getTargets ( @ PathVariable ( "activity" ) Long activityId , @ RequestParam ( "q" ) String query ) { IPermissionActivity activity = permissionOwnerDao . getPermissionActivity ( activityId ) ; Collection < IPermissionTarget > targets = Collections . emptyList ( ) ; if ( activity != null ) { IPermissionTargetProvider provider = targetProviderRegistry . getTargetProvider ( activity . getTargetProviderKey ( ) ) ; SortedSet < IPermissionTarget > matchingTargets = new TreeSet <> ( ) ; // add matching results for this identifier provider to the set targets = provider . searchTargets ( query ) ; for ( IPermissionTarget target : targets ) { if ( ( StringUtils . isNotBlank ( target . getName ( ) ) && target . getName ( ) . toLowerCase ( ) . contains ( query ) ) || target . getKey ( ) . toLowerCase ( ) . contains ( query ) ) { matchingTargets . addAll ( targets ) ; } } } ModelAndView mv = new ModelAndView ( ) ; mv . addObject ( "targets" , targets ) ; mv . setViewName ( "json" ) ; return mv ; }
|
Return a list of targets defined for a particular IPermissionActivity matching the specified search query .
| 363
| 19
|
151,632
|
@ PreAuthorize ( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))" ) @ RequestMapping ( "/v5-5/permissions/assignments/users/{username}" ) public ModelAndView getAssignmentsForUser ( @ PathVariable ( "username" ) String username , @ RequestParam ( value = "includeInherited" , required = false , defaultValue = "false" ) boolean includeInherited ) { final JsonEntityBean entity = groupListHelper . getEntity ( EntityEnum . PERSON . toString ( ) , username , false ) ; final List < JsonPermission > permissions = getPermissionsForEntity ( entity , includeInherited ) ; final ModelAndView mv = new ModelAndView ( ) ; mv . addObject ( "assignments" , permissions ) ; mv . setViewName ( "json" ) ; return mv ; }
|
Provides the collection of permission assignments that apply to the specified user optionally including inherited assignments .
| 237
| 18
|
151,633
|
private void setReportFormTabs ( final TabRenderReportForm report ) { if ( ! report . getTabs ( ) . isEmpty ( ) ) { // Tabs are already set, do nothing return ; } final Set < AggregatedTabMapping > tabs = this . getTabs ( ) ; if ( ! tabs . isEmpty ( ) ) { report . getTabs ( ) . add ( tabs . iterator ( ) . next ( ) . getId ( ) ) ; } }
|
Set the tab names to have first selected by default
| 104
| 10
|
151,634
|
@ javax . annotation . Resource ( name = "dataFileIncludes" ) public void setDataFileIncludes ( Set < String > dataFileIncludes ) { this . dataFileIncludes = dataFileIncludes ; }
|
Ant path matching patterns that files must match to be included
| 44
| 11
|
151,635
|
private void importDataArchive ( final Resource resource , final ArchiveInputStream resourceStream , BatchImportOptions options ) { final File tempDir = Files . createTempDir ( ) ; try { ArchiveEntry archiveEntry ; while ( ( archiveEntry = resourceStream . getNextEntry ( ) ) != null ) { final File entryFile = new File ( tempDir , archiveEntry . getName ( ) ) ; if ( ! archiveEntry . isDirectory ( ) ) { entryFile . getParentFile ( ) . mkdirs ( ) ; IOUtils . copy ( new CloseShieldInputStream ( resourceStream ) , new FileOutputStream ( entryFile ) ) ; } } importDataDirectory ( tempDir , null , options ) ; } catch ( IOException e ) { throw new RuntimeException ( "Failed to extract data from '" + resource + "' to '" + tempDir + "' for batch import." , e ) ; } finally { FileUtils . deleteQuietly ( tempDir ) ; } }
|
Extracts the archive resource and then runs the batch - import process on it .
| 212
| 17
|
151,636
|
private List < FutureHolder < ? > > waitForFutures ( final Queue < ? extends FutureHolder < ? > > futures , final PrintWriter reportWriter , final File reportDirectory , final boolean wait ) throws InterruptedException { final List < FutureHolder < ? > > failedFutures = new LinkedList <> ( ) ; for ( Iterator < ? extends FutureHolder < ? > > futuresItr = futures . iterator ( ) ; futuresItr . hasNext ( ) ; ) { final FutureHolder < ? > futureHolder = futuresItr . next ( ) ; // If waiting, or if not waiting but the future is already done do the get final Future < ? > future = futureHolder . getFuture ( ) ; if ( wait || ( ! wait && future . isDone ( ) ) ) { futuresItr . remove ( ) ; try { // Don't bother doing a get() on canceled futures if ( ! future . isCancelled ( ) ) { if ( this . maxWait > 0 ) { future . get ( this . maxWait , this . maxWaitTimeUnit ) ; } else { future . get ( ) ; } reportWriter . printf ( REPORT_FORMAT , "SUCCESS" , futureHolder . getDescription ( ) , futureHolder . getExecutionTimeMillis ( ) ) ; } } catch ( CancellationException e ) { // Ignore cancellation exceptions } catch ( ExecutionException e ) { logger . error ( "Failed: " + futureHolder ) ; futureHolder . setError ( e ) ; failedFutures . add ( futureHolder ) ; reportWriter . printf ( REPORT_FORMAT , "FAIL" , futureHolder . getDescription ( ) , futureHolder . getExecutionTimeMillis ( ) ) ; try { final String dataReportName = SafeFilenameUtils . makeSafeFilename ( futureHolder . getDataType ( ) + "_" + futureHolder . getDataName ( ) + ".txt" ) ; final File dataReportFile = new File ( reportDirectory , dataReportName ) ; final PrintWriter dataReportWriter = new PrintWriter ( new BufferedWriter ( new FileWriter ( dataReportFile ) ) ) ; try { dataReportWriter . println ( "FAIL: " + futureHolder . getDataType ( ) + " - " + futureHolder . getDataName ( ) ) ; dataReportWriter . println ( "--------------------------------------------------------------------------------" ) ; e . getCause ( ) . printStackTrace ( dataReportWriter ) ; } finally { IOUtils . closeQuietly ( dataReportWriter ) ; } } catch ( Exception re ) { logger . warn ( "Failed to write error report for failed " + futureHolder + ", logging root failure here" , e . getCause ( ) ) ; } } catch ( TimeoutException e ) { logger . warn ( "Failed: " + futureHolder ) ; futureHolder . setError ( e ) ; failedFutures . add ( futureHolder ) ; future . cancel ( true ) ; reportWriter . printf ( REPORT_FORMAT , "TIMEOUT" , futureHolder . getDescription ( ) , futureHolder . getExecutionTimeMillis ( ) ) ; } } } return failedFutures ; }
|
Used by batch import and export to wait for queued tasks to complete . Handles fail - fast behavior if any of the tasks threw and exception by canceling all queued futures and logging a summary of the failures . All completed futures are removed from the queue .
| 706
| 53
|
151,637
|
@ Override public String setParameterValue ( String parameterName , String parameterValue ) { // don't try to store a null value if ( parameterValue == null ) return null ; return ( String ) parameters . put ( parameterName , parameterValue ) ; }
|
Set a channel parameter value .
| 53
| 6
|
151,638
|
static void applyAndUpdateParmEditSet ( Document plf , Document ilf , IntegrationResult result ) { Element pSet = null ; try { pSet = getParmEditSet ( plf , null , false ) ; } catch ( Exception e ) { LOG . error ( "Exception occurred while getting user's DLM " + "paramter-edit-set." , e ) ; } if ( pSet == null ) return ; NodeList edits = pSet . getChildNodes ( ) ; for ( int i = edits . getLength ( ) - 1 ; i >= 0 ; i -- ) { if ( applyEdit ( ( Element ) edits . item ( i ) , ilf ) == false ) { pSet . removeChild ( edits . item ( i ) ) ; result . setChangedPLF ( true ) ; } else { result . setChangedILF ( true ) ; } } if ( pSet . getChildNodes ( ) . getLength ( ) == 0 ) { plf . getDocumentElement ( ) . removeChild ( pSet ) ; result . setChangedPLF ( true ) ; } }
|
Get the parm edit set if any from the plf and process each edit command removing any that fail from the set so that the set is self cleaning .
| 237
| 32
|
151,639
|
private static boolean applyEdit ( Element edit , Document ilf ) { String nodeID = edit . getAttribute ( Constants . ATT_TARGET ) ; Element channel = ilf . getElementById ( nodeID ) ; if ( channel == null ) return false ; // now get the name of the parameter to be edited and find that element String parmName = edit . getAttribute ( Constants . ATT_NAME ) ; String parmValue = edit . getAttribute ( Constants . ATT_USER_VALUE ) ; NodeList ilfParms = channel . getChildNodes ( ) ; Element targetParm = null ; for ( int i = 0 ; i < ilfParms . getLength ( ) ; i ++ ) { Element ilfParm = ( Element ) ilfParms . item ( i ) ; if ( ilfParm . getAttribute ( Constants . ATT_NAME ) . equals ( parmName ) ) { targetParm = ilfParm ; break ; } } if ( targetParm == null ) // parameter not found so we are free to set { Element parameter = ilf . createElement ( "parameter" ) ; parameter . setAttribute ( "name" , parmName ) ; parameter . setAttribute ( "value" , parmValue ) ; parameter . setAttribute ( "override" , "yes" ) ; channel . appendChild ( parameter ) ; return true ; } /* TODO Add support for fragments to set dlm:editAllowed attribute for * channel parameters. (2005.11.04 mboyd) * * In the commented code below, the check for editAllowed will never be * seen on a parameter element in the * current database schema approach used by DLM. This is because * parameters are second class citizens of the layout structure. They * are not found in the up_layout_struct table but only in the * up_layout_param table. DLM functionality like dlm:editAllowed, * dlm:moveAllowed, dlm:deleteAllowed, and dlm:addChildAllowed were * implemented without schema changes by adding these as parameters to * structural elements and upon loading any parameter that begins with * 'dlm:' is placed as an attribute on the containing structural * element. So any channel parameter entry with dlm:editAllowed has that * value placed as an attribute on the containing channel not on the * parameter that was meant to have it. * * The only solution would be to add special dlm:parm children below * channels that would get the editAllowed value and then when creating * the DOM don't create those as child elements but use them to set the * attribute on the corresponding parameter by having the name of the * dlm:parm element be the name of the parameter to which it is to be * related. * * The result of this lack of functionality is that fragments can't * mark any channel parameters as dlm:editAllowed='false' thereby * further restricting which channel parameters can be edited beyond * what the channel definition specifies during publishing. */ // Attr editAllowed = targetParm.getAttributeNode( Constants.ATT_EDIT_ALLOWED ); // if ( editAllowed != null && editAllowed.getNodeValue().equals("false")) // return false; // target parm found. See if channel definition will still allow changes. Attr override = targetParm . getAttributeNode ( Constants . ATT_OVERRIDE ) ; if ( override != null && ! override . getNodeValue ( ) . equals ( Constants . CAN_OVERRIDE ) ) return false ; // now see if the change is still needed if ( targetParm . getAttribute ( Constants . ATT_VALUE ) . equals ( parmValue ) ) return false ; // user's edit same as fragment or chan def targetParm . setAttribute ( "value" , parmValue ) ; return true ; }
|
Attempt to apply a single channel parameter edit command and return true if it succeeds or false otherwise . If the edit is disallowed or the target element no longer exists in the document the edit command fails and returns false .
| 842
| 43
|
151,640
|
private static Element getParmEditSet ( Document plf , IPerson person , boolean create ) throws PortalException { Node root = plf . getDocumentElement ( ) ; Node child = root . getFirstChild ( ) ; while ( child != null ) { if ( child . getNodeName ( ) . equals ( Constants . ELM_PARM_SET ) ) return ( Element ) child ; child = child . getNextSibling ( ) ; } if ( create == false ) return null ; String ID = null ; try { ID = getDLS ( ) . getNextStructDirectiveId ( person ) ; } catch ( Exception e ) { throw new PortalException ( "Exception encountered while " + "generating new parameter edit set node " + "Id for userId=" + person . getID ( ) , e ) ; } Element parmSet = plf . createElement ( Constants . ELM_PARM_SET ) ; parmSet . setAttribute ( Constants . ATT_TYPE , Constants . ELM_PARM_SET ) ; parmSet . setAttribute ( Constants . ATT_ID , ID ) ; parmSet . setIdAttribute ( Constants . ATT_ID , true ) ; root . appendChild ( parmSet ) ; return parmSet ; }
|
Get the parameter edits set if any stored in the root of the document or create it if passed - in create flag is true .
| 276
| 26
|
151,641
|
public static synchronized void addParmEditDirective ( String targetId , String name , String value , IPerson person ) throws PortalException { Document plf = ( Document ) person . getAttribute ( Constants . PLF ) ; Element parmSet = getParmEditSet ( plf , person , true ) ; NodeList edits = parmSet . getChildNodes ( ) ; Element existingEdit = null ; for ( int i = 0 ; i < edits . getLength ( ) ; i ++ ) { Element edit = ( Element ) edits . item ( i ) ; if ( edit . getAttribute ( Constants . ATT_TARGET ) . equals ( targetId ) && edit . getAttribute ( Constants . ATT_NAME ) . equals ( name ) ) { existingEdit = edit ; break ; } } if ( existingEdit == null ) // existing one not found, create a new one { addParmEditDirective ( targetId , name , value , person , plf , parmSet ) ; return ; } existingEdit . setAttribute ( Constants . ATT_USER_VALUE , value ) ; }
|
Create and append a parameter edit directive to parameter edits set for applying a user specified value to a named parameter of the incorporated channel represented by the passed - in target id . If one already exists for that node and that name then the value of the existing edit is changed to the passed - in value .
| 235
| 60
|
151,642
|
private static void addParmEditDirective ( String targetID , String name , String value , IPerson person , Document plf , Element parmSet ) throws PortalException { String ID = null ; try { ID = getDLS ( ) . getNextStructDirectiveId ( person ) ; } catch ( Exception e ) { throw new PortalException ( "Exception encountered while " + "generating new parameter edit node " + "Id for userId=" + person . getID ( ) , e ) ; } Element parm = plf . createElement ( Constants . ELM_PARM_EDIT ) ; parm . setAttribute ( Constants . ATT_TYPE , Constants . ELM_PARM_EDIT ) ; parm . setAttribute ( Constants . ATT_ID , ID ) ; parm . setIdAttribute ( Constants . ATT_ID , true ) ; parm . setAttributeNS ( Constants . NS_URI , Constants . ATT_TARGET , targetID ) ; parm . setAttribute ( Constants . ATT_NAME , name ) ; parm . setAttribute ( Constants . ATT_USER_VALUE , value ) ; parmSet . appendChild ( parm ) ; }
|
This method does the actual work of adding a newly created parameter edit and adding it to the parameter edits set .
| 259
| 22
|
151,643
|
public static void removeParmEditDirective ( String targetId , String name , IPerson person ) throws PortalException { Document plf = ( Document ) person . getAttribute ( Constants . PLF ) ; Element parmSet = getParmEditSet ( plf , person , false ) ; if ( parmSet == null ) return ; // no set so no edit to remove NodeList edits = parmSet . getChildNodes ( ) ; for ( int i = 0 ; i < edits . getLength ( ) ; i ++ ) { Element edit = ( Element ) edits . item ( i ) ; if ( edit . getAttribute ( Constants . ATT_TARGET ) . equals ( targetId ) && edit . getAttribute ( Constants . ATT_NAME ) . equals ( name ) ) { parmSet . removeChild ( edit ) ; break ; } } if ( parmSet . getChildNodes ( ) . getLength ( ) == 0 ) // no more edits, remove { Node parent = parmSet . getParentNode ( ) ; parent . removeChild ( parmSet ) ; } }
|
Remove a parameter edit directive from the parameter edits set for applying user specified values to a named parameter of an incorporated channel represented by the passed - in target id . If one doesn t exists for that node and that name then this call returns without any effects .
| 236
| 51
|
151,644
|
public static final < T > T dropTableIfExists ( JdbcOperations jdbcOperations , final String table , final Function < JdbcOperations , T > preDropCallback ) { LOGGER . info ( "Dropping table: " + table ) ; final boolean tableExists = doesTableExist ( jdbcOperations , table ) ; if ( tableExists ) { final T ret = preDropCallback . apply ( jdbcOperations ) ; jdbcOperations . execute ( "DROP TABLE " + table ) ; return ret ; } return null ; }
|
Check if the named table exists if it does drop it calling the preDropCallback first
| 128
| 17
|
151,645
|
public static boolean doesTableExist ( JdbcOperations jdbcOperations , final String table ) { final boolean tableExists = jdbcOperations . execute ( new ConnectionCallback < Boolean > ( ) { @ Override public Boolean doInConnection ( Connection con ) throws SQLException , DataAccessException { final DatabaseMetaData metaData = con . getMetaData ( ) ; final ResultSet tables = metaData . getTables ( null , null , null , new String [ ] { "TABLE" } ) ; while ( tables . next ( ) ) { final String dbTableName = tables . getString ( "TABLE_NAME" ) ; if ( table . equalsIgnoreCase ( dbTableName ) ) { return true ; } } return false ; } } ) ; return tableExists ; }
|
Check if the specified table exists
| 173
| 6
|
151,646
|
@ Override public int getPortalUID ( IPerson person , boolean createPortalData ) throws AuthorizationException { int uid ; String username = ( String ) person . getAttribute ( IPerson . USERNAME ) ; // only synchronize a non-guest request. if ( PersonFactory . getGuestUsernames ( ) . contains ( username ) ) { uid = __getPortalUID ( person , createPortalData ) ; } else { synchronized ( getLock ( person ) ) { uid = __getPortalUID ( person , createPortalData ) ; } } return uid ; }
|
Get the portal user ID for this person object .
| 130
| 10
|
151,647
|
private PortalUser getPortalUser ( final String userName ) { return jdbcOperations . execute ( ( ConnectionCallback < PortalUser > ) con -> { PortalUser portalUser = null ; PreparedStatement pstmt = null ; try { String query = "SELECT USER_ID FROM UP_USER WHERE USER_NAME=?" ; pstmt = con . prepareStatement ( query ) ; pstmt . setString ( 1 , userName ) ; ResultSet rs = null ; try { if ( log . isDebugEnabled ( ) ) log . debug ( "RDBMUserIdentityStore::getPortalUID(userName=" + userName + "): " + query ) ; rs = pstmt . executeQuery ( ) ; if ( rs . next ( ) ) { portalUser = new PortalUser ( ) ; portalUser . setUserId ( rs . getInt ( "USER_ID" ) ) ; portalUser . setUserName ( userName ) ; } } finally { try { if ( rs != null ) { rs . close ( ) ; } } catch ( Exception e ) { } } } finally { try { if ( pstmt != null ) { pstmt . close ( ) ; } } catch ( Exception e ) { } } return portalUser ; } ) ; }
|
Gets the PortalUser data store object for the specified user name .
| 277
| 14
|
151,648
|
@ RequestMapping ( params = "action=export" ) public ModelAndView getExportView ( PortletRequest request ) { Map < String , Object > model = new HashMap < String , Object > ( ) ; // add a list of all permitted export types final Iterable < IPortalDataType > exportPortalDataTypes = this . portalDataHandlerService . getExportPortalDataTypes ( ) ; final List < IPortalDataType > types = getAllowedTypes ( request , IPermission . EXPORT_ACTIVITY , exportPortalDataTypes ) ; model . put ( "supportedTypes" , types ) ; return new ModelAndView ( "/jsp/ImportExportPortlet/export" , model ) ; }
|
Display the entity export form view .
| 155
| 7
|
151,649
|
@ RequestMapping ( params = "action=delete" ) public ModelAndView getDeleteView ( PortletRequest request ) { Map < String , Object > model = new HashMap < String , Object > ( ) ; // add a list of all permitted deletion types final Iterable < IPortalDataType > deletePortalDataTypes = this . portalDataHandlerService . getDeletePortalDataTypes ( ) ; final List < IPortalDataType > types = getAllowedTypes ( request , IPermission . DELETE_ACTIVITY , deletePortalDataTypes ) ; model . put ( "supportedTypes" , types ) ; return new ModelAndView ( "/jsp/ImportExportPortlet/delete" , model ) ; }
|
Display the entity deletion form view .
| 156
| 7
|
151,650
|
public void validateEditDetails ( GroupForm group , MessageContext context ) { // ensure the group name is set if ( StringUtils . isBlank ( group . getName ( ) ) ) { context . addMessage ( new MessageBuilder ( ) . error ( ) . source ( "name" ) . code ( "please.enter.name" ) . build ( ) ) ; } }
|
Validate the detail editing group view
| 81
| 7
|
151,651
|
public String getTypeAndIdHash ( ) { assert ( entityType != null ) ; assert ( id != null ) ; String idStr = id . replaceAll ( "\\W" , "__" ) ; return entityType . toString ( ) . toLowerCase ( ) + "_" + idStr ; }
|
Compute a hash based on type and ID to uniquely identify this bean . This method helps avoid the unlikely case where a group and person in the same principal list have the same ID .
| 66
| 37
|
151,652
|
private void filterAnalyticsGroups ( IGroupMember groupMember , JsonNode config , Map < String , Boolean > isMemberCache ) { if ( config == null ) { return ; } final JsonNode dimensionGroups = config . get ( "dimensionGroups" ) ; if ( dimensionGroups == null ) { return ; } for ( final Iterator < JsonNode > groupItr = dimensionGroups . elements ( ) ; groupItr . hasNext ( ) ; ) { final JsonNode group = groupItr . next ( ) ; final JsonNode valueNode = group . get ( "value" ) ; if ( valueNode == null ) { continue ; } final String groupName = valueNode . asText ( ) ; Boolean isMember = isMemberCache . get ( groupName ) ; if ( isMember == null ) { isMember = isMember ( groupMember , groupName ) ; isMemberCache . put ( groupName , isMember ) ; } if ( ! isMember ) { groupItr . remove ( ) ; } } }
|
Remove groups from the AnalyticsConfig that the current user is not a member of
| 225
| 15
|
151,653
|
private boolean isMember ( IGroupMember groupMember , String groupName ) { try { IEntityGroup group = GroupService . findGroup ( groupName ) ; if ( group != null ) { return groupMember . isDeepMemberOf ( group ) ; } final EntityIdentifier [ ] results = GroupService . searchForGroups ( groupName , GroupService . SearchMethod . DISCRETE , IPerson . class ) ; if ( results == null || results . length == 0 ) { this . logger . warn ( "No portal group found for '{}' no users will be placed in that group for analytics" , groupName ) ; return false ; } if ( results . length > 1 ) { this . logger . warn ( "{} groups were found for groupName '{}'. The first result will be used." , results . length , groupName ) ; } group = ( IEntityGroup ) GroupService . getGroupMember ( results [ 0 ] ) ; return groupMember . isDeepMemberOf ( group ) ; } catch ( Exception e ) { this . logger . warn ( "Failed to determine if {} is a member of {}, returning false" , groupMember , groupName , e ) ; return false ; } }
|
Check if the user is a member of the specified group name
| 257
| 12
|
151,654
|
@ PostConstruct public void warnOnApathyKeyInMappings ( ) { if ( null != profileKeyForNoSelection && immutableMappings . containsKey ( profileKeyForNoSelection ) ) { logger . warn ( "Configured to treat profile key {} as apathy, " + "yet also configured to map that key to profile fname {}. Apathy wins. " + "This is likely just fine, but it might be a misconfiguration." , profileKeyForNoSelection , immutableMappings . get ( profileKeyForNoSelection ) ) ; } }
|
Log a warning when configured such that a profile key both means apathy and means a particular profile fname .
| 122
| 22
|
151,655
|
protected void chunkString ( final List < CharacterEvent > characterEvents , final CharSequence buffer , int patternIndex ) { // Iterate over the chunking patterns for ( ; patternIndex < this . chunkingPatterns . length ; patternIndex ++ ) { final Pattern pattern = this . chunkingPatterns [ patternIndex ] ; final Matcher matcher = pattern . matcher ( buffer ) ; if ( matcher . find ( ) ) { final CharacterEventSource eventSource = this . chunkingPatternEventSources . get ( pattern ) ; int prevMatchEnd = 0 ; do { // Add all of the text up to the match as a new chunk, use subSequence to avoid // extra string alloc this . chunkString ( characterEvents , buffer . subSequence ( prevMatchEnd , matcher . start ( ) ) , patternIndex + 1 ) ; // Get the generated CharacterEvents for the match final MatchResult matchResult = matcher . toMatchResult ( ) ; eventSource . generateCharacterEvents ( this . request , matchResult , characterEvents ) ; prevMatchEnd = matcher . end ( ) ; } while ( matcher . find ( ) ) ; // Add any remaining text from the original CharacterDataEvent if ( prevMatchEnd < buffer . length ( ) ) { this . chunkString ( characterEvents , buffer . subSequence ( prevMatchEnd , buffer . length ( ) ) , patternIndex + 1 ) ; } return ; } } // Buffer didn't match anything, just append the string data // de-duplication of the event string data final String eventString = buffer . toString ( ) ; characterEvents . add ( CharacterDataEventImpl . create ( eventString ) ) ; }
|
Breaks up the String into a List of CharacterEvents based on the configured Map of Patterns to CharacterEventSources
| 355
| 22
|
151,656
|
@ Override public IPerson getPerson ( HttpServletRequest request ) throws PortalSecurityException { /* * This method overrides the implementation of getPerson() in BasePersonManager, but we only * want the RemoteUser behavior here if we're using RemoteUser AuthN. */ if ( ! remoteUserSecurityContextFactory . isEnabled ( ) ) { return super . getPerson ( request ) ; } // Return the person object if it exists in the user's session final HttpSession session = request . getSession ( false ) ; IPerson person = null ; if ( session != null ) { person = ( IPerson ) session . getAttribute ( PERSON_SESSION_KEY ) ; if ( person != null ) { return person ; } } try { // Create a new instance of a person person = createPersonForRequest ( request ) ; // If the user has authenticated with the server which has implemented web // authentication, // the REMOTE_USER environment variable will be set. String remoteUser = request . getRemoteUser ( ) ; // We don't want to ignore the security contexts which are already configured in // security.properties, so we // retrieve the existing security contexts. If one of the existing security contexts is // a RemoteUserSecurityContext, // we set the REMOTE_USER field of the existing RemoteUserSecurityContext context. // // If a RemoteUserSecurityContext does not already exist, we create one and populate the // REMOTE_USER field. ISecurityContext context ; Enumeration subContexts = null ; boolean remoteUserSecurityContextExists = false ; // Retrieve existing security contexts. context = person . getSecurityContext ( ) ; if ( context != null ) subContexts = context . getSubContexts ( ) ; if ( subContexts != null ) { while ( subContexts . hasMoreElements ( ) ) { ISecurityContext ctx = ( ISecurityContext ) subContexts . nextElement ( ) ; // Check to see if a RemoteUserSecurityContext already exists, and set the // REMOTE_USER if ( ctx instanceof RemoteUserSecurityContext ) { RemoteUserSecurityContext remoteuserctx = ( RemoteUserSecurityContext ) ctx ; remoteuserctx . setRemoteUser ( remoteUser ) ; remoteUserSecurityContextExists = true ; } } } // If a RemoteUserSecurityContext doesn't already exist, create one. // This preserves the default behavior of this class. if ( ! remoteUserSecurityContextExists ) { RemoteUserSecurityContext remoteuserctx = new RemoteUserSecurityContext ( remoteUser ) ; person . setSecurityContext ( remoteuserctx ) ; } } catch ( Exception e ) { // Log the exception logger . error ( "Exception creating person for request: {}" , request , e ) ; } if ( session != null ) { // Add this person object to the user's session session . setAttribute ( PERSON_SESSION_KEY , person ) ; } // Return the new person object return ( person ) ; }
|
Retrieve an IPerson object for the incoming request
| 623
| 10
|
151,657
|
public static String makeSafeFilename ( String filename ) { // Replace invalid characters for ( final Map . Entry < Pattern , String > pair : REPLACEMENT_PAIRS . entrySet ( ) ) { final Pattern pattern = pair . getKey ( ) ; final Matcher matcher = pattern . matcher ( filename ) ; filename = matcher . replaceAll ( pair . getValue ( ) ) ; } // Make sure the name doesn't violate a Windows reserved word... for ( Pattern pattern : WINDOWS_INVALID_PATTERNS ) { if ( pattern . matcher ( filename ) . matches ( ) ) { filename = "uP-" + filename ; break ; } } return filename ; }
|
Makes safe filename
| 148
| 4
|
151,658
|
@ SuppressWarnings ( "unchecked" ) protected < D extends CachedPortletResultHolder < T > , T extends Serializable > CacheState < D , T > getPortletCacheState ( HttpServletRequest request , IPortletWindow portletWindow , PublicPortletCacheKey publicCacheKey , Ehcache publicOutputCache , Ehcache privateOutputCache ) { final CacheState < D , T > cacheState = new CacheState < D , T > ( ) ; cacheState . setPublicPortletCacheKey ( publicCacheKey ) ; final IPortletWindowId portletWindowId = portletWindow . getPortletWindowId ( ) ; // Check for publicly cached data D cachedPortletData = ( D ) this . getCachedPortletData ( publicCacheKey , publicOutputCache , portletWindow ) ; if ( cachedPortletData != null ) { cacheState . setCachedPortletData ( cachedPortletData ) ; return cacheState ; } // Generate private cache key final HttpSession session = request . getSession ( ) ; final String sessionId = session . getId ( ) ; final IPortletEntityId entityId = portletWindow . getPortletEntityId ( ) ; final PrivatePortletCacheKey privateCacheKey = new PrivatePortletCacheKey ( sessionId , portletWindowId , entityId , publicCacheKey ) ; cacheState . setPrivatePortletCacheKey ( privateCacheKey ) ; // Check for privately cached data cachedPortletData = ( D ) this . getCachedPortletData ( privateCacheKey , privateOutputCache , portletWindow ) ; if ( cachedPortletData != null ) { cacheState . setCachedPortletData ( cachedPortletData ) ; return cacheState ; } return cacheState ; }
|
Get the cached portlet data looking in both the public and then private caches returning the first found
| 382
| 19
|
151,659
|
@ PreAuthorize ( "hasPermission('ALL', 'java.lang.String', new org.apereo.portal.spring.security.evaluator.AuthorizableActivity('UP_PERMISSIONS', 'VIEW_PERMISSIONS'))" ) @ RequestMapping ( value = "/permissions/principals.json" , method = RequestMethod . GET ) public ModelAndView getPrincipals ( @ RequestParam ( value = "q" ) String query , HttpServletRequest request , HttpServletResponse response ) throws Exception { /* * Add groups and people matching the search query to the JSON model */ ModelAndView mv = new ModelAndView ( ) ; List < JsonEntityBean > groups = new ArrayList < JsonEntityBean > ( ) ; groups . addAll ( listHelper . search ( EntityEnum . GROUP . toString ( ) , query ) ) ; Collections . sort ( groups ) ; mv . addObject ( "groups" , groups ) ; List < JsonEntityBean > people = new ArrayList < JsonEntityBean > ( ) ; people . addAll ( listHelper . search ( EntityEnum . PERSON . toString ( ) , query ) ) ; Collections . sort ( people ) ; mv . addObject ( "people" , people ) ; mv . setViewName ( "json" ) ; return mv ; }
|
Return a JSON view of the uPortal principals matching the supplied query string .
| 305
| 16
|
151,660
|
static Element appendChild ( Element plfChild , Element parent , boolean copyChildren ) { Document document = parent . getOwnerDocument ( ) ; Element copy = ( Element ) document . importNode ( plfChild , false ) ; parent . appendChild ( copy ) ; // set the identifier for the doc if warrented String id = copy . getAttribute ( Constants . ATT_ID ) ; if ( id != null && ! id . equals ( "" ) ) copy . setIdAttribute ( Constants . ATT_ID , true ) ; if ( copyChildren ) { NodeList children = plfChild . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { if ( children . item ( i ) instanceof Element ) appendChild ( ( Element ) children . item ( i ) , copy , true ) ; } } return copy ; }
|
This method copies a plf node and any of its children into the passed in compViewParent .
| 189
| 20
|
151,661
|
private boolean isLocked ( Class entityType , String entityKey ) throws LockingException { return isLocked ( entityType , entityKey , null ) ; }
|
Answers if the entity represented by the entityType and entityKey already has a lock of some type .
| 34
| 21
|
151,662
|
@ Override public void renew ( IEntityLock lock , int duration ) throws LockingException { if ( isValid ( lock ) ) { Date newExpiration = getNewExpiration ( duration ) ; getLockStore ( ) . update ( lock , newExpiration ) ; ( ( EntityLockImpl ) lock ) . setExpirationTime ( newExpiration ) ; } else { throw new LockingException ( "Could not renew " + lock + " : lock is invalid." ) ; } }
|
Extends the expiration time of the lock by some service - defined increment .
| 103
| 15
|
151,663
|
public PortletDefinitionForm createPortletDefinitionForm ( IPerson person , String portletId ) { IPortletDefinition def = portletDefinitionRegistry . getPortletDefinition ( portletId ) ; // create the new form final PortletDefinitionForm form ; if ( def != null ) { // if this is a pre-existing portlet, set the category and permissions form = new PortletDefinitionForm ( def ) ; form . setId ( def . getPortletDefinitionId ( ) . getStringId ( ) ) ; // create a JsonEntityBean for each current category and add it // to our form bean's category list Set < PortletCategory > categories = portletCategoryRegistry . getParentCategories ( def ) ; for ( PortletCategory cat : categories ) { form . addCategory ( new JsonEntityBean ( cat ) ) ; } addPrincipalPermissionsToForm ( def , form ) ; } else { form = createNewPortletDefinitionForm ( ) ; } /* TODO: Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */ // User must have SOME FORM of lifecycle permission over AT LEAST ONE // category in which this portlet resides; lifecycle permissions are // hierarchical, so we'll test with the weakest. if ( ! hasLifecyclePermission ( person , PortletLifecycleState . CREATED , form . getCategories ( ) ) ) { logger . warn ( "User '" + person . getUserName ( ) + "' attempted to edit the following portlet without MANAGE permission: " + def ) ; throw new SecurityException ( "Not Authorized" ) ; } return form ; }
|
Construct a new PortletDefinitionForm for the given IPortletDefinition id . If a PortletDefinition matching this ID already exists the form will be pre - populated with the PortletDefinition s current configuration . If the PortletDefinition does not yet exist a new default form will be created .
| 360
| 59
|
151,664
|
public void removePortletRegistration ( IPerson person , PortletDefinitionForm form ) { /* TODO: Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */ // Arguably a check here is redundant since -- in the current // portlet-manager webflow -- you can't get to this point in the // conversation with out first obtaining a PortletDefinitionForm; but // it makes sense to check permissions here as well since the route(s) // to reach this method could evolve in the future. // Let's enforce the policy that you may only delete a portlet thet's // currently in a lifecycle state you have permission to MANAGE. // (They're hierarchical.) if ( ! hasLifecyclePermission ( person , form . getLifecycleState ( ) , form . getCategories ( ) ) ) { logger . warn ( "User '" + person . getUserName ( ) + "' attempted to remove portlet '" + form . getFname ( ) + "' without the proper MANAGE permission" ) ; throw new SecurityException ( "Not Authorized" ) ; } IPortletDefinition def = portletDefinitionRegistry . getPortletDefinition ( form . getId ( ) ) ; /* * It's very important to remove portlets via the portletPublishingService * because that API cleans up details like category memberships and permissions. */ portletPublishingService . removePortletDefinition ( def , person ) ; }
|
Delete the portlet with the given portlet ID .
| 315
| 11
|
151,665
|
public boolean shouldDisplayLayoutLink ( IPerson person , PortletDefinitionForm form , String portletId ) { if ( ! form . isNew ( ) ) { return false ; } // only include the "do layout" link for published portlets. if ( form . getLifecycleState ( ) != PortletLifecycleState . PUBLISHED ) { return false ; } // check that the user can edit at least 1 fragment. Map < String , String > layouts = fragmentAdminHelper . getAuthorizedDlmFragments ( person . getUserName ( ) ) ; if ( layouts == null || layouts . isEmpty ( ) ) { return false ; } // check that the user has subscribe priv. IAuthorizationPrincipal authPrincipal = authorizationService . newPrincipal ( person . getUserName ( ) , EntityEnum . PERSON . getClazz ( ) ) ; return authPrincipal . canSubscribe ( portletId ) ; }
|
Check if the link to the Fragment admin portlet should display in the status message .
| 201
| 18
|
151,666
|
public String getFragmentAdminURL ( HttpServletRequest request ) { IPortalUrlBuilder builder = urlProvider . getPortalUrlBuilderByPortletFName ( request , PORTLET_FNAME_FRAGMENT_ADMIN_PORTLET , UrlType . RENDER ) ; IPortletUrlBuilder portletUrlBuilder = builder . getTargetedPortletUrlBuilder ( ) ; portletUrlBuilder . setPortletMode ( PortletMode . VIEW ) ; portletUrlBuilder . setWindowState ( WindowState . MAXIMIZED ) ; return builder . getUrlString ( ) ; }
|
Get the link to the fragment admin portlet .
| 131
| 10
|
151,667
|
public Set < String > getArbitraryPortletPreferenceNames ( PortletDefinitionForm form ) { // set default values for all portlet parameters PortletPublishingDefinition cpd = this . portletPublishingDefinitionDao . getChannelPublishingDefinition ( form . getTypeId ( ) ) ; Set < String > currentPrefs = new HashSet <> ( ) ; currentPrefs . addAll ( form . getPortletPreferences ( ) . keySet ( ) ) ; for ( Step step : cpd . getSteps ( ) ) { if ( step . getPreferences ( ) != null ) { for ( Preference pref : step . getPreferences ( ) ) { currentPrefs . remove ( pref . getName ( ) ) ; } } } return currentPrefs ; }
|
Get a list of the key names of the currently - set arbitrary portlet preferences .
| 169
| 17
|
151,668
|
public List < PortletApplicationDefinition > getPortletApplications ( ) { final PortletRegistryService portletRegistryService = portalDriverContainerServices . getPortletRegistryService ( ) ; final List < PortletApplicationDefinition > contexts = new ArrayList <> ( ) ; for ( final Iterator < String > iter = portletRegistryService . getRegisteredPortletApplicationNames ( ) ; iter . hasNext ( ) ; ) { final String applicationName = iter . next ( ) ; final PortletApplicationDefinition applicationDefninition ; try { applicationDefninition = portletRegistryService . getPortletApplication ( applicationName ) ; } catch ( PortletContainerException e ) { throw new RuntimeException ( "Failed to load PortletApplicationDefinition for '" + applicationName + "'" ) ; } final List < ? extends PortletDefinition > portlets = applicationDefninition . getPortlets ( ) ; portlets . sort ( new ComparableExtractingComparator < PortletDefinition , String > ( String . CASE_INSENSITIVE_ORDER ) { @ Override protected String getComparable ( PortletDefinition o ) { final List < ? extends DisplayName > displayNames = o . getDisplayNames ( ) ; if ( displayNames != null && displayNames . size ( ) > 0 ) { return displayNames . get ( 0 ) . getDisplayName ( ) ; } return o . getPortletName ( ) ; } } ) ; contexts . add ( applicationDefninition ) ; } contexts . sort ( new ComparableExtractingComparator < PortletApplicationDefinition , String > ( String . CASE_INSENSITIVE_ORDER ) { @ Override protected String getComparable ( PortletApplicationDefinition o ) { final String portletContextName = o . getName ( ) ; if ( portletContextName != null ) { return portletContextName ; } final String applicationName = o . getContextPath ( ) ; if ( "/" . equals ( applicationName ) ) { return "ROOT" ; } if ( applicationName . startsWith ( "/" ) ) { return applicationName . substring ( 1 ) ; } return applicationName ; } } ) ; return contexts ; }
|
Retreive the list of portlet application contexts currently available in this portlet container .
| 470
| 18
|
151,669
|
private void copyAssertionAttributesToUserAttributes ( Assertion assertion ) { if ( ! copyAssertionAttributesToUserAttributes ) { return ; } // skip this if there are no attributes or if the attribute set is empty. if ( assertion . getPrincipal ( ) . getAttributes ( ) == null || assertion . getPrincipal ( ) . getAttributes ( ) . isEmpty ( ) ) { return ; } Map < String , List < Object > > attributes = new HashMap <> ( ) ; // loop over the set of person attributes from CAS... for ( Map . Entry < String , Object > attrEntry : assertion . getPrincipal ( ) . getAttributes ( ) . entrySet ( ) ) { log . debug ( "Adding attribute '{}' from Assertion with value '{}'; runtime type of value is {}" , attrEntry . getKey ( ) , attrEntry . getValue ( ) , attrEntry . getValue ( ) . getClass ( ) . getName ( ) ) ; // Check for credential if ( decryptCredentialToPassword && key != null && cipher != null && attrEntry . getKey ( ) . equals ( CREDENTIAL_KEY ) ) { try { final String encPwd = ( String ) ( attrEntry . getValue ( ) instanceof List ? ( ( List ) attrEntry . getValue ( ) ) . get ( 0 ) : attrEntry . getValue ( ) ) ; byte [ ] cred64 = DatatypeConverter . parseBase64Binary ( encPwd ) ; cipher . init ( Cipher . DECRYPT_MODE , key ) ; final byte [ ] cipherData = cipher . doFinal ( cred64 ) ; final Object pwd = new String ( cipherData , UTF_8 ) ; attributes . put ( PASSWORD_KEY , Collections . singletonList ( pwd ) ) ; } catch ( Exception e ) { log . warn ( "Cannot decipher credential" , e ) ; } } // convert each attribute to a list, if necessary... List < Object > valueList ; if ( attrEntry . getValue ( ) instanceof List ) { valueList = ( List < Object > ) attrEntry . getValue ( ) ; } else { valueList = Collections . singletonList ( attrEntry . getValue ( ) ) ; } // add the attribute... attributes . put ( attrEntry . getKey ( ) , valueList ) ; } // get the attribute descriptor from Spring... IAdditionalDescriptors additionalDescriptors = ( IAdditionalDescriptors ) applicationContext . getBean ( SESSION_ADDITIONAL_DESCRIPTORS_BEAN ) ; // add the new properties... additionalDescriptors . addAttributes ( attributes ) ; }
|
If enabled convert CAS assertion person attributes into uPortal user attributes .
| 590
| 14
|
151,670
|
@ Override public IBasicEntity get ( Class < ? extends IBasicEntity > type , String key ) throws CachingException { return EntityCachingServiceLocator . getEntityCachingService ( ) . get ( type , key ) ; }
|
Returns the cached entity identified by type and key .
| 51
| 10
|
151,671
|
public IBasicEntity get ( EntityIdentifier entityID ) throws CachingException { return EntityCachingServiceLocator . getEntityCachingService ( ) . get ( entityID . getType ( ) , entityID . getKey ( ) ) ; }
|
Returns the cached entity referred to by entityID .
| 53
| 10
|
151,672
|
@ Override public void remove ( Class < ? extends IBasicEntity > type , String key ) throws CachingException { EntityCachingServiceLocator . getEntityCachingService ( ) . remove ( type , key ) ; }
|
Removes the entity identified by type and key from the cache and notifies peer caches .
| 48
| 18
|
151,673
|
@ RequestMapping ( "VIEW" ) public String renderError ( RenderRequest request , RenderResponse response , ModelMap model ) throws Exception { HttpServletRequest httpRequest = this . portalRequestUtils . getPortletHttpRequest ( request ) ; IPortletWindowId currentFailedPortletWindowId = ( IPortletWindowId ) request . getAttribute ( REQUEST_ATTRIBUTE__CURRENT_FAILED_PORTLET_WINDOW_ID ) ; model . addAttribute ( "portletWindowId" , currentFailedPortletWindowId ) ; Exception cause = ( Exception ) request . getAttribute ( REQUEST_ATTRIBUTE__CURRENT_EXCEPTION_CAUSE ) ; model . addAttribute ( "exception" , cause ) ; final String rootCauseMessage = ExceptionUtils . getRootCauseMessage ( cause ) ; model . addAttribute ( "rootCauseMessage" , rootCauseMessage ) ; // Maintenance Mode? if ( cause != null && cause instanceof MaintenanceModeException ) { return "/jsp/PortletError/maintenance" ; } IUserInstance userInstance = this . userInstanceManager . getUserInstance ( httpRequest ) ; if ( hasAdminPrivileges ( userInstance ) ) { IPortletWindow window = this . portletWindowRegistry . getPortletWindow ( httpRequest , currentFailedPortletWindowId ) ; window . setRenderParameters ( new ParameterMap ( ) ) ; IPortalUrlBuilder adminRetryUrl = this . portalUrlProvider . getPortalUrlBuilderByPortletWindow ( httpRequest , currentFailedPortletWindowId , UrlType . RENDER ) ; model . addAttribute ( "adminRetryUrl" , adminRetryUrl . getUrlString ( ) ) ; final IPortletWindow portletWindow = portletWindowRegistry . getPortletWindow ( httpRequest , currentFailedPortletWindowId ) ; final IPortletEntity parentPortletEntity = portletWindow . getPortletEntity ( ) ; final IPortletDefinition parentPortletDefinition = parentPortletEntity . getPortletDefinition ( ) ; model . addAttribute ( "channelDefinition" , parentPortletDefinition ) ; StringWriter stackTraceWriter = new StringWriter ( ) ; cause . printStackTrace ( new PrintWriter ( stackTraceWriter ) ) ; model . addAttribute ( "stackTrace" , stackTraceWriter . toString ( ) ) ; return "/jsp/PortletError/detailed" ; } // no admin privileges, return generic view return "/jsp/PortletError/generic" ; }
|
Render the error portlet view .
| 558
| 7
|
151,674
|
private String getAttributeValue ( Attributes attrs , int attribute ) throws NamingException { NamingEnumeration values = null ; String aValue = "" ; if ( ! isAttribute ( attribute ) ) return aValue ; Attribute attrib = attrs . get ( attributes [ attribute ] ) ; if ( attrib != null ) { for ( values = attrib . getAll ( ) ; values . hasMoreElements ( ) ; ) { aValue = ( String ) values . nextElement ( ) ; break ; // take only the first attribute value } } return aValue ; }
|
Return a single value of an attribute from possibly multiple values grossly ignoring anything else . If there are no values then return an empty string .
| 122
| 27
|
151,675
|
@ Override public UserProfile addUserProfile ( final IPerson person , final IUserProfile profile ) { final int userId = person . getID ( ) ; final int layoutId = getLayoutId ( person , profile ) ; // generate an id for this profile return jdbcOperations . execute ( ( ConnectionCallback < UserProfile > ) con -> { String sQuery ; PreparedStatement pstmt = con . prepareStatement ( "INSERT INTO UP_USER_PROFILE " + "(USER_ID, PROFILE_ID, PROFILE_FNAME, PROFILE_NAME, STRUCTURE_SS_ID, THEME_SS_ID," + "DESCRIPTION, LAYOUT_ID) VALUES (?,?,?,?,?,?,?,?)" ) ; int profileId = getNextKey ( ) ; pstmt . setInt ( 1 , userId ) ; pstmt . setInt ( 2 , profileId ) ; pstmt . setString ( 3 , profile . getProfileFname ( ) ) ; pstmt . setString ( 4 , profile . getProfileName ( ) ) ; pstmt . setInt ( 5 , profile . getStructureStylesheetId ( ) ) ; pstmt . setInt ( 6 , profile . getThemeStylesheetId ( ) ) ; pstmt . setString ( 7 , profile . getProfileDescription ( ) ) ; pstmt . setInt ( 8 , layoutId ) ; sQuery = "INSERT INTO UP_USER_PROFILE (USER_ID, PROFILE_ID, PROFILE_FNAME, PROFILE_NAME, STRUCTURE_SS_ID, THEME_SS_ID, DESCRIPTION, LAYOUT_ID) VALUES (" + userId + ",'" + profileId + ",'" + profile . getProfileFname ( ) + "','" + profile . getProfileName ( ) + "'," + profile . getStructureStylesheetId ( ) + "," + profile . getThemeStylesheetId ( ) + ",'" + profile . getProfileDescription ( ) + "', " + profile . getLayoutId ( ) + ")" ; logger . debug ( "addUserProfile(): {}" , sQuery ) ; try { pstmt . executeUpdate ( ) ; UserProfile newProfile = new UserProfile ( ) ; newProfile . setProfileId ( profileId ) ; newProfile . setLayoutId ( layoutId ) ; newProfile . setLocaleManager ( profile . getLocaleManager ( ) ) ; newProfile . setProfileDescription ( profile . getProfileDescription ( ) ) ; newProfile . setProfileFname ( profile . getProfileFname ( ) ) ; newProfile . setProfileName ( profile . getProfileName ( ) ) ; newProfile . setStructureStylesheetId ( profile . getStructureStylesheetId ( ) ) ; newProfile . setSystemProfile ( false ) ; newProfile . setThemeStylesheetId ( profile . getThemeStylesheetId ( ) ) ; return newProfile ; } finally { pstmt . close ( ) ; } } ) ; }
|
Add a user profile
| 664
| 4
|
151,676
|
private void createLayout ( HashMap layoutStructure , Document doc , Element root , int structId ) { while ( structId != 0 ) { LayoutStructure ls = ( LayoutStructure ) layoutStructure . get ( structId ) ; // replaced with call to method in containing class to allow overriding // by subclasses of RDBMUserLayoutStore. // Element structure = ls.getStructureDocument(doc); Element structure = getStructure ( doc , ls ) ; root . appendChild ( structure ) ; String id = structure . getAttribute ( "ID" ) ; if ( id != null && ! id . equals ( "" ) ) { structure . setIdAttribute ( "ID" , true ) ; } createLayout ( layoutStructure , doc , structure , ls . getChildId ( ) ) ; structId = ls . getNextId ( ) ; } }
|
Create a layout
| 182
| 3
|
151,677
|
protected String getNextStructId ( final IPerson person , final String prefix ) { final int userId = person . getID ( ) ; return nextStructTransactionOperations . execute ( status -> jdbcOperations . execute ( new ConnectionCallback < String > ( ) { @ Override public String doInConnection ( Connection con ) throws SQLException , DataAccessException { try ( Statement stmt = con . createStatement ( ) ) { String sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId ; logger . debug ( "getNextStructId(): {}" , sQuery ) ; int currentStructId ; try ( ResultSet rs = stmt . executeQuery ( sQuery ) ) { if ( rs . next ( ) ) { currentStructId = rs . getInt ( 1 ) ; } else { throw new SQLException ( "no rows returned for query [" + sQuery + "]" ) ; } } int nextStructId = currentStructId + 1 ; String sUpdate = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + userId + " AND NEXT_STRUCT_ID=" + currentStructId ; logger . debug ( "getNextStructId(): {}" , sUpdate ) ; stmt . executeUpdate ( sUpdate ) ; return prefix + nextStructId ; } } } ) ) ; }
|
Return the next available structure id for a user
| 302
| 9
|
151,678
|
private int getLayoutID ( final int userId , final int profileId ) { return jdbcOperations . execute ( ( ConnectionCallback < Integer > ) con -> { String query = "SELECT LAYOUT_ID " + "FROM UP_USER_PROFILE " + "WHERE USER_ID=? AND PROFILE_ID=?" ; int layoutId = 0 ; PreparedStatement pstmt = con . prepareStatement ( query ) ; logger . debug ( "getLayoutID(userId={}, profileId={} ): {}" , userId , profileId , query ) ; pstmt . setInt ( 1 , userId ) ; pstmt . setInt ( 2 , profileId ) ; try { ResultSet rs = pstmt . executeQuery ( ) ; if ( rs . next ( ) ) { layoutId = rs . getInt ( 1 ) ; if ( rs . wasNull ( ) ) { layoutId = 0 ; } } } finally { pstmt . close ( ) ; } return layoutId ; } ) ; }
|
Returns the current layout ID for the user and profile . If the profile doesn t exist or the layout_id field is null 0 is returned .
| 224
| 29
|
151,679
|
public static String getResourceAsURLString ( Class < ? > requestingClass , String resource ) throws ResourceMissingException { return getResourceAsURL ( requestingClass , resource ) . toString ( ) ; }
|
Returns the requested resource as a URL string .
| 42
| 9
|
151,680
|
public static InputStream getResourceAsStream ( Class < ? > requestingClass , String resource ) throws ResourceMissingException , IOException { return getResourceAsURL ( requestingClass , resource ) . openStream ( ) ; }
|
Returns the requested resource as a stream .
| 45
| 8
|
151,681
|
public static InputSource getResourceAsSAXInputSource ( Class < ? > requestingClass , String resource ) throws ResourceMissingException , IOException { URL url = getResourceAsURL ( requestingClass , resource ) ; InputSource source = new InputSource ( url . openStream ( ) ) ; source . setPublicId ( url . toExternalForm ( ) ) ; return source ; }
|
Returns the requested resource as a SAX input source .
| 79
| 11
|
151,682
|
public static Document getResourceAsDocument ( Class < ? > requestingClass , String resource , boolean validate ) throws ResourceMissingException , IOException , ParserConfigurationException , SAXException { Document document = null ; InputStream inputStream = null ; try { DocumentBuilderFactory factoryToUse = null ; if ( validate ) { factoryToUse = ResourceLoader . validatingDocumentBuilderFactory ; } else { factoryToUse = ResourceLoader . nonValidatingDocumentBuilderFactory ; } inputStream = getResourceAsStream ( requestingClass , resource ) ; DocumentBuilder db = factoryToUse . newDocumentBuilder ( ) ; db . setEntityResolver ( new DTDResolver ( ) ) ; db . setErrorHandler ( new SAXErrorHandler ( "ResourceLoader.getResourceAsDocument(" + resource + ")" ) ) ; document = db . parse ( inputStream ) ; } finally { if ( inputStream != null ) inputStream . close ( ) ; } return document ; }
|
Get the contents of a URL as an XML Document
| 202
| 10
|
151,683
|
public static Document getResourceAsDocument ( Class < ? > requestingClass , String resource ) throws ResourceMissingException , IOException , ParserConfigurationException , SAXException { // Default is non-validating... return getResourceAsDocument ( requestingClass , resource , false ) ; }
|
Get the contents of a URL as an XML Document first trying to read the Document with validation turned on and falling back to reading it with validation turned off .
| 58
| 31
|
151,684
|
public static Properties getResourceAsProperties ( Class < ? > requestingClass , String resource ) throws ResourceMissingException , IOException { InputStream inputStream = null ; Properties props = null ; try { inputStream = getResourceAsStream ( requestingClass , resource ) ; props = new Properties ( ) ; props . load ( inputStream ) ; } finally { if ( inputStream != null ) inputStream . close ( ) ; } return props ; }
|
Get the contents of a URL as a java . util . Properties object
| 92
| 14
|
151,685
|
public static String getResourceAsString ( Class < ? > requestingClass , String resource ) throws ResourceMissingException , IOException { String line = null ; BufferedReader in = null ; StringBuffer sbText = null ; try { in = new BufferedReader ( new InputStreamReader ( getResourceAsStream ( requestingClass , resource ) , UTF_8 ) ) ; sbText = new StringBuffer ( 1024 ) ; while ( ( line = in . readLine ( ) ) != null ) sbText . append ( line ) . append ( "\n" ) ; } finally { if ( in != null ) in . close ( ) ; } return sbText . toString ( ) ; }
|
Get the contents of a URL as a String
| 146
| 9
|
151,686
|
public void setContextParameters ( Map < String , String > principals , Map < String , String > credentials , String ctxName , ISecurityContext securityContext ) { if ( log . isDebugEnabled ( ) ) { final StringBuilder msg = new StringBuilder ( ) ; msg . append ( "Preparing to authenticate; setting parameters for context name '" ) . append ( ctxName ) . append ( "', context class '" ) . append ( securityContext . getClass ( ) . getName ( ) ) . append ( "'" ) ; // Display principalTokens... msg . append ( "\n\t Available Principal Tokens" ) ; for ( final Object o : principals . entrySet ( ) ) { final Map . Entry < ? , ? > y = ( Map . Entry < ? , ? > ) o ; msg . append ( "\n\t\t" ) . append ( y . getKey ( ) ) . append ( "=" ) . append ( y . getValue ( ) ) ; } // Keep credentialTokens secret, but indicate whether they were provided... msg . append ( "\n\t Available Credential Tokens" ) ; for ( final Object o : credentials . entrySet ( ) ) { final Map . Entry < ? , ? > y = ( Map . Entry < ? , ? > ) o ; final String val = ( String ) y . getValue ( ) ; String valWasSpecified = null ; if ( val != null ) { valWasSpecified = val . trim ( ) . length ( ) == 0 ? "empty" : "provided" ; } msg . append ( "\n\t\t" ) . append ( y . getKey ( ) ) . append ( " was " ) . append ( valWasSpecified ) ; } log . debug ( msg . toString ( ) ) ; } String username = principals . get ( ctxName ) ; String credential = credentials . get ( ctxName ) ; // If username or credential are null, this indicates that the token was not // set in security.properties. We will then use the value for root. username = username != null ? username : ( String ) principals . get ( BASE_CONTEXT_NAME ) ; credential = credential != null ? credential : ( String ) credentials . get ( BASE_CONTEXT_NAME ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Authentication::setContextParameters() username: " + username ) ; } // Retrieve and populate an instance of the principal object final IPrincipal principalInstance = securityContext . getPrincipalInstance ( ) ; if ( username != null && ! username . equals ( "" ) ) { principalInstance . setUID ( username ) ; } // Retrieve and populate an instance of the credentials object final IOpaqueCredentials credentialsInstance = securityContext . getOpaqueCredentialsInstance ( ) ; if ( credentialsInstance != null ) { credentialsInstance . setCredentials ( credential ) ; } }
|
Get the principal and credential for a specific context and store them in the context .
| 627
| 16
|
151,687
|
protected void publishRenderEvent ( IPortletWindow portletWindow , HttpServletRequest httpServletRequest , RenderPart renderPart , long executionTime , boolean cached ) { final IPortletWindowId portletWindowId = portletWindow . getPortletWindowId ( ) ; // Determine if the portlet was targeted final IPortalRequestInfo portalRequestInfo = this . urlSyntaxProvider . getPortalRequestInfo ( httpServletRequest ) ; final boolean targeted = portletWindowId . equals ( portalRequestInfo . getTargetedPortletWindowId ( ) ) ; renderPart . publishRenderExecutionEvent ( this . portalEventFactory , this , httpServletRequest , portletWindowId , executionTime , targeted , cached ) ; }
|
Publish the portlet render event
| 159
| 7
|
151,688
|
protected void publishResourceEvent ( IPortletWindow portletWindow , HttpServletRequest httpServletRequest , long executionTime , boolean usedBrowserCache , boolean usedPortalCache ) { final IPortletWindowId portletWindowId = portletWindow . getPortletWindowId ( ) ; this . portalEventFactory . publishPortletResourceExecutionEvent ( httpServletRequest , this , portletWindowId , executionTime , usedBrowserCache , usedPortalCache ) ; }
|
Publish the portlet resource event
| 103
| 7
|
151,689
|
protected void enforceConfigPermission ( final HttpServletRequest httpServletRequest , final IPortletWindow portletWindow ) { Validate . notNull ( httpServletRequest , "Servlet request must not be null to determine remote user." ) ; Validate . notNull ( portletWindow , "Portlet window must not be null to determine its mode." ) ; final PortletMode portletMode = portletWindow . getPortletMode ( ) ; if ( portletMode != null ) { if ( IPortletRenderer . CONFIG . equals ( portletMode ) ) { final IPerson person = this . personManager . getPerson ( httpServletRequest ) ; final EntityIdentifier ei = person . getEntityIdentifier ( ) ; final AuthorizationServiceFacade authorizationServiceFacade = AuthorizationServiceFacade . instance ( ) ; final IAuthorizationPrincipal ap = authorizationServiceFacade . newPrincipal ( ei . getKey ( ) , ei . getType ( ) ) ; final IPortletEntity portletEntity = portletWindow . getPortletEntity ( ) ; final IPortletDefinition portletDefinition = portletEntity . getPortletDefinition ( ) ; if ( ! ap . canConfigure ( portletDefinition . getPortletDefinitionId ( ) . getStringId ( ) ) ) { logger . error ( "User {} attempted to use portlet {} in {} but lacks permission to use that mode. " + "THIS MAY BE AN ATTEMPT TO EXPLOIT A HISTORICAL SECURITY FLAW. " + "You should probably figure out who this user is and why they are trying to access " + "unauthorized portlet modes." , person . getUserName ( ) , portletDefinition . getFName ( ) , portletMode ) ; throw new AuthorizationException ( person . getUserName ( ) + " does not have permission to render '" + portletDefinition . getFName ( ) + "' in " + portletMode + " PortletMode." ) ; } } } }
|
Enforces config mode access control . If requesting user does not have CONFIG permission and the PortletWindow specifies config mode throws AuthorizationException . Otherwise does nothing .
| 437
| 31
|
151,690
|
@ Override public Object [ ] getAttributeValues ( String key ) { if ( userAttributes == null ) { return null ; } final List < Object > values = userAttributes . get ( key ) ; if ( values != null ) { return values . toArray ( ) ; } return null ; }
|
Returns multiple attributes for a key . If only one value exists it will be returned in an array of size one .
| 62
| 23
|
151,691
|
@ Override public void setAttribute ( String key , Object value ) { if ( value == null ) { setAttribute ( key , null ) ; } else { setAttribute ( key , Collections . singletonList ( value ) ) ; } }
|
Sets the specified attribute to a value .
| 50
| 9
|
151,692
|
@ Override public boolean isGuest ( ) { String userName = ( String ) getAttribute ( IPerson . USERNAME ) ; boolean isGuestUsername = PersonFactory . getGuestUsernames ( ) . contains ( userName ) ; boolean isAuthenticated = m_securityContext != null && m_securityContext . isAuthenticated ( ) ; return isGuestUsername && ! isAuthenticated ; }
|
Determines whether or not this person is a guest user .
| 86
| 13
|
151,693
|
public IEntityStore newInstance ( ) throws GroupsException { try { return new RDBMEntityStore ( ) ; } catch ( Exception ex ) { log . error ( "ReferenceEntityStoreFactory.newInstance(): " + ex ) ; throw new GroupsException ( ex ) ; } }
|
Return an instance of the entity store implementation .
| 60
| 9
|
151,694
|
protected Deque < XMLEvent > getAdditionalEvents ( XMLEvent event ) { final XMLEvent additionalEvent = this . getAdditionalEvent ( event ) ; if ( additionalEvent == null ) { return null ; } final Deque < XMLEvent > additionalEvents = new LinkedList < XMLEvent > ( ) ; additionalEvents . push ( additionalEvent ) ; return additionalEvents ; }
|
The Deque with the additional events WILL BE MODIFIED by the calling code .
| 88
| 16
|
151,695
|
protected String getStyleSheetName ( final HttpServletRequest request , PreferencesScope scope ) { final String stylesheetNameFromRequest ; if ( scope . equals ( PreferencesScope . STRUCTURE ) ) { stylesheetNameFromRequest = ( String ) request . getAttribute ( STYLESHEET_STRUCTURE_OVERRIDE_REQUEST_ATTRIBUTE ) ; } else { stylesheetNameFromRequest = ( String ) request . getAttribute ( STYLESHEET_THEME_OVERRIDE_REQUEST_ATTRIBUTE_NAME ) ; } return stylesheetNameFromRequest ; }
|
Returns the stylesheet name if overridden in the request object .
| 131
| 13
|
151,696
|
@ RequestMapping public void doLogout ( HttpServletRequest request , HttpServletResponse response ) throws IOException { String redirect = this . selectRedirectionUrl ( request ) ; final HttpSession session = request . getSession ( false ) ; if ( session != null ) { // Record that an authenticated user is requesting to log out try { final IPerson person = personManager . getPerson ( request ) ; if ( person != null && person . getSecurityContext ( ) . isAuthenticated ( ) ) { this . portalEventFactory . publishLogoutEvent ( request , this , person ) ; } } catch ( final Exception e ) { logger . error ( "Exception recording logout " + "associated with request " + request , e ) ; } final String originalUid = this . identitySwapperManager . getOriginalUsername ( session ) ; // Logging out from a swapped user, just redirect to the Login servlet if ( originalUid != null ) { redirect = request . getContextPath ( ) + "/Login" ; } else { // Clear out the existing session for the user try { session . invalidate ( ) ; } catch ( final IllegalStateException ise ) { // IllegalStateException indicates session was already invalidated. // This is fine. LogoutController is looking to guarantee the logged out // session is invalid; // it need not insist that it be the one to perform the invalidating. if ( logger . isTraceEnabled ( ) ) { logger . trace ( "LogoutController encountered IllegalStateException invalidating a presumably already-invalidated session." , ise ) ; } } } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Redirecting to " + redirect + " to send the user back to the guest page." ) ; } final String encodedRedirectURL = response . encodeRedirectURL ( redirect ) ; response . sendRedirect ( encodedRedirectURL ) ; }
|
Process the incoming request and response .
| 412
| 7
|
151,697
|
protected static void loadProps ( ) { PropertiesManager . props = new Properties ( ) ; try { String pfile = System . getProperty ( PORTAL_PROPERTIES_FILE_SYSTEM_VARIABLE ) ; if ( pfile == null ) { pfile = PORTAL_PROPERTIES_FILE_NAME ; } PropertiesManager . props . load ( PropertiesManager . class . getResourceAsStream ( pfile ) ) ; } catch ( Throwable t ) { log . error ( "Unable to read portal.properties file." , t ) ; } }
|
Load up the portal properties . Right now the portal properties is a simple . properties file with name value pairs . It may evolve to become an XML file later on .
| 125
| 33
|
151,698
|
public static String getProperty ( String name ) throws MissingPropertyException { if ( log . isTraceEnabled ( ) ) { log . trace ( "entering getProperty(" + name + ")" ) ; } if ( PropertiesManager . props == null ) loadProps ( ) ; String val = getPropertyUntrimmed ( name ) ; val = val . trim ( ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "returning from getProperty(" + name + ") with return value [" + val + "]" ) ; } return val ; }
|
Returns the value of a property for a given name . Any whitespace is trimmed off the beginning and end of the property value . Note that this method will never return null . If the requested property cannot be found this method throws an UndeclaredPortalException .
| 123
| 54
|
151,699
|
public static String getPropertyUntrimmed ( String name ) throws MissingPropertyException { if ( PropertiesManager . props == null ) loadProps ( ) ; if ( props == null ) { boolean alreadyReported = registerMissingProperty ( name ) ; throw new MissingPropertyException ( name , alreadyReported ) ; } String val = props . getProperty ( name ) ; if ( val == null ) { boolean alreadyReported = registerMissingProperty ( name ) ; throw new MissingPropertyException ( name , alreadyReported ) ; } return val ; }
|
Returns the value of a property for a given name including whitespace trailing the property value but not including whitespace leading the property value . An UndeclaredPortalException is thrown if the property cannot be found . This method will never return null .
| 113
| 51
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.