idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
34,900
private static boolean applyDelete ( Element delete , Document ilf ) { String nodeID = delete . getAttribute ( Constants . ATT_NAME ) ; Element e = ilf . getElementById ( nodeID ) ; if ( e == null ) return false ; String deleteAllowed = e . getAttribute ( Constants . ATT_DELETE_ALLOWED ) ; if ( deleteAllowed . equals ( "false" ) ) return false ; Element p = ( Element ) e . getParentNode ( ) ; e . setIdAttribute ( Constants . ATT_ID , false ) ; p . removeChild ( e ) ; return true ; }
Attempt to apply a single delete command and return true if it succeeds or false otherwise . If the delete is disallowed or the target element no longer exists in the document the delete command fails and returns false .
34,901
private static Element getDeleteSet ( 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_DELETE_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 delete set node " + "Id for userId=" + person . getID ( ) , e ) ; } Element delSet = plf . createElement ( Constants . ELM_DELETE_SET ) ; delSet . setAttribute ( Constants . ATT_TYPE , Constants . ELM_DELETE_SET ) ; delSet . setAttribute ( Constants . ATT_ID , ID ) ; root . appendChild ( delSet ) ; return delSet ; }
Get the delete set if any stored in the root of the document or create it is passed in create flag is true .
34,902
private static void addDeleteDirective ( Element compViewNode , String elementID , IPerson person , Document plf , Element delSet ) throws PortalException { String ID = null ; try { ID = getDLS ( ) . getNextStructDirectiveId ( person ) ; } catch ( Exception e ) { throw new PortalException ( "Exception encountered while " + "generating new delete node " + "Id for userId=" + person . getID ( ) , e ) ; } Element delete = plf . createElement ( Constants . ELM_DELETE ) ; delete . setAttribute ( Constants . ATT_TYPE , Constants . ELM_DELETE ) ; delete . setAttribute ( Constants . ATT_ID , ID ) ; delete . setAttributeNS ( Constants . NS_URI , Constants . ATT_NAME , elementID ) ; delSet . appendChild ( delete ) ; Element child = ( Element ) compViewNode . getFirstChild ( ) ; while ( child != null ) { String childID = child . getAttribute ( "ID" ) ; if ( childID . startsWith ( Constants . FRAGMENT_ID_USER_PREFIX ) ) addDeleteDirective ( child , childID , person , plf , delSet ) ; child = ( Element ) child . getNextSibling ( ) ; } }
This method does the actual work of adding a delete directive and then recursively calling itself for any incoporated children that need to be deleted as well .
34,903
public void perform ( ) throws PortalException { if ( nodeId . startsWith ( Constants . FRAGMENT_ID_USER_PREFIX ) ) { EditManager . removeEditDirective ( nodeId , name , person ) ; } if ( ! name . equals ( Constants . ATT_NAME ) ) { ilfNode . setAttribute ( name , fragmentValue ) ; } }
Reset a parameter to not override the value specified by a fragment . This is done by removing the parm edit in the PLF and setting the value in the ILF to the passed - in fragment value .
34,904
public EntityIdentifier [ ] searchForEntities ( String query , SearchMethod method ) throws GroupsException { boolean allowPartial = true ; switch ( method ) { case DISCRETE : allowPartial = false ; break ; case STARTS_WITH : query = query + "%" ; break ; case ENDS_WITH : query = "%" + query ; break ; case CONTAINS : query = "%" + query + "%" ; break ; default : throw new GroupsException ( "Unknown search type" ) ; } final List < IPortletDefinition > definitions = this . portletDefinitionRegistry . searchForPortlets ( query , allowPartial ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Found " + definitions . size ( ) + " matching definitions for query " + query ) ; } final EntityIdentifier [ ] identifiers = new EntityIdentifier [ definitions . size ( ) ] ; for ( final ListIterator < IPortletDefinition > defIter = definitions . listIterator ( ) ; defIter . hasNext ( ) ; ) { final IPortletDefinition definition = defIter . next ( ) ; identifiers [ defIter . previousIndex ( ) ] = new EntityIdentifier ( definition . getPortletDefinitionId ( ) . getStringId ( ) , this . getType ( ) ) ; } return identifiers ; }
Internal search so shouldn t be called as case insensitive .
34,905
public void setProviders ( Map < String , IPermissionTargetProvider > providers ) { this . providers . clear ( ) ; for ( Map . Entry < String , IPermissionTargetProvider > provider : providers . entrySet ( ) ) { this . providers . put ( provider . getKey ( ) , provider . getValue ( ) ) ; } }
Construct a new target provider registry and initialize it with the supplied map of key - > provider pairs .
34,906
public String parseString ( String expressionString , PortletRequest request ) { return getValue ( expressionString , request , String . class ) ; }
Primary method used assuming all defaults .
34,907
protected EvaluationContext getEvaluationContext ( PortletRequest request ) { Map < String , String > userInfo = ( Map < String , String > ) request . getAttribute ( PortletRequest . USER_INFO ) ; final SpELEnvironmentRoot root = new SpELEnvironmentRoot ( new PortletWebRequest ( request ) , userInfo ) ; final StandardEvaluationContext context = new StandardEvaluationContext ( root ) ; context . setBeanResolver ( this . beanResolver ) ; return context ; }
Return a SpEL evaluation context for the supplied portlet request .
34,908
private Version getSimpleVersion ( String product ) { final Tuple coreNumbers ; try { final TypedQuery < Tuple > coreNumbersQuery = this . createQuery ( this . findCoreVersionNumbers ) ; coreNumbersQuery . setParameter ( this . productParameter , product ) ; coreNumbers = DataAccessUtils . singleResult ( coreNumbersQuery . getResultList ( ) ) ; } catch ( SQLGrammarException e ) { logger . warn ( "UP_VERSION table doesn't exist, returning null for version of " + product ) ; return null ; } if ( coreNumbers == null ) { return null ; } final Integer major = coreNumbers . get ( VersionImpl_ . major . getName ( ) , VersionImpl_ . major . getBindableJavaType ( ) ) ; final Integer minor = coreNumbers . get ( VersionImpl_ . minor . getName ( ) , VersionImpl_ . minor . getBindableJavaType ( ) ) ; final Integer patch = coreNumbers . get ( VersionImpl_ . patch . getName ( ) , VersionImpl_ . patch . getBindableJavaType ( ) ) ; Integer local ; try { final TypedQuery < Integer > localNumberQuery = this . createQuery ( this . findLocalVersionNumber ) ; localNumberQuery . setParameter ( this . productParameter , product ) ; local = DataAccessUtils . singleResult ( localNumberQuery . getResultList ( ) ) ; } catch ( PersistenceException e ) { local = null ; } return new VersionImpl ( product , major , minor , patch , local ) ; }
Load a Version object with direct field queries . Used to deal with DB upgrades where not all of the fields have been loaded
34,909
private String calculateDynamicSkinUrlPathToUse ( PortletRequest request , String lessfileBaseName ) throws IOException { final DynamicSkinInstanceData data = new DefaultDynamicSkinInstanceDataImpl ( request ) ; if ( ! service . skinCssFileExists ( data ) ) { service . generateSkinCssFile ( data ) ; } return service . getSkinCssPath ( data ) ; }
Calculate the default skin URL path or the path to a skin CSS file that is specific to the set of portlet preference values currently defined .
34,910
protected long getLastModified ( Resource resource ) { try { return resource . lastModified ( ) ; } catch ( IOException e ) { this . logger . warn ( "Could not determine lastModified for " + resource + ". This resource will never be reloaded due to lastModified changing." , e ) ; } return 0 ; }
Determine the last modified time stamp for the resource
34,911
public IUserInstance getUserInstance ( HttpServletRequest request ) throws PortalException { try { request = this . portalRequestUtils . getOriginalPortalRequest ( request ) ; } catch ( IllegalArgumentException iae ) { } IUserInstance userInstance = ( IUserInstance ) request . getAttribute ( KEY ) ; if ( userInstance != null ) { return userInstance ; } final IPerson person ; try { person = this . personManager . getPerson ( request ) ; } catch ( Exception e ) { logger . error ( "Exception while retrieving IPerson!" , e ) ; throw new PortalSecurityException ( "Could not retrieve IPerson" , e ) ; } if ( person == null ) { throw new PortalSecurityException ( "PersonManager returned null person for this request. With no user, there's no UserInstance. Is PersonManager misconfigured? RDBMS access misconfigured?" ) ; } final HttpSession session = request . getSession ( ) ; if ( session == null ) { throw new IllegalStateException ( "HttpServletRequest.getSession() returned a null session for request: " + request ) ; } UserInstanceHolder userInstanceHolder = getUserInstanceHolder ( session ) ; if ( userInstanceHolder != null ) { userInstance = userInstanceHolder . getUserInstance ( ) ; if ( userInstance != null ) { return userInstance ; } } final LocaleManager localeManager = this . getLocaleManager ( request , person ) ; final String userAgent = this . getUserAgent ( request ) ; final IUserProfile userProfile = this . getUserProfile ( request , person , localeManager , userAgent ) ; IUserLayoutManager userLayoutManager = userLayoutManagerFactory . getUserLayoutManager ( person , userProfile ) ; final UserPreferencesManager userPreferencesManager = new UserPreferencesManager ( person , userProfile , userLayoutManager ) ; userInstance = new UserInstance ( person , userPreferencesManager , localeManager ) ; if ( userInstanceHolder == null ) { userInstanceHolder = new UserInstanceHolder ( ) ; } userInstanceHolder . setUserInstance ( userInstance ) ; session . setAttribute ( KEY , userInstanceHolder ) ; request . setAttribute ( KEY , userInstance ) ; return userInstance ; }
Returns the UserInstance object that is associated with the given request .
34,912
private boolean containsElmentWithId ( Node node , String id ) { String nodeName = node . getNodeName ( ) ; if ( "channel" . equals ( nodeName ) || "folder" . equals ( nodeName ) ) { Element e = ( Element ) node ; if ( id . equals ( e . getAttribute ( "ID" ) ) ) { return true ; } if ( "folder" . equals ( nodeName ) ) { for ( Node child = e . getFirstChild ( ) ; child != null ; child = child . getNextSibling ( ) ) { if ( containsElmentWithId ( child , id ) ) { return true ; } } } } return false ; }
Recursevly find out whether node contains a folder or channel with given identifier .
34,913
public static String currentRequestContextPath ( ) { final RequestAttributes requestAttributes = RequestContextHolder . getRequestAttributes ( ) ; if ( null == requestAttributes ) { throw new IllegalStateException ( "Request attributes are not bound. " + "Not operating in context of a Spring-processed Request?" ) ; } if ( requestAttributes instanceof ServletRequestAttributes ) { final ServletRequestAttributes servletRequestAttributes = ( ServletRequestAttributes ) requestAttributes ; final HttpServletRequest request = servletRequestAttributes . getRequest ( ) ; return request . getContextPath ( ) ; } else if ( requestAttributes instanceof PortletRequestAttributes ) { final PortletRequestAttributes portletRequestAttributes = ( PortletRequestAttributes ) requestAttributes ; final PortletRequest request = portletRequestAttributes . getRequest ( ) ; return request . getContextPath ( ) ; } else { throw new IllegalStateException ( "Request attributes are an unrecognized implementation." ) ; } }
Get the request context path from the current request . Copes with both HttpServletRequest and PortletRequest and so usable when handling Spring - processed Servlet or Portlet requests . Requires that Spring have bound the request as in the case of dispatcher servlet or portlet or when the binding filter or listener is active . This should be the case for all requests in the uPortal framework and framework portlets .
34,914
protected List < ? extends UserAttribute > getExpectedUserAttributes ( HttpServletRequest request , final IPortletWindow portletWindow ) { final IPortletEntity portletEntity = portletWindow . getPortletEntity ( ) ; final IPortletDefinition portletDefinition = portletEntity . getPortletDefinition ( ) ; final PortletApplicationDefinition portletApplicationDescriptor = this . portletDefinitionRegistry . getParentPortletApplicationDescriptor ( portletDefinition . getPortletDefinitionId ( ) ) ; return portletApplicationDescriptor . getUserAttributes ( ) ; }
Get the list of user attributes the portlet expects .
34,915
public static IAuthorizationPrincipal principalFromUser ( final IPerson user ) { Validate . notNull ( user , "Cannot determine an authorization principal for null user." ) ; final EntityIdentifier userEntityIdentifier = user . getEntityIdentifier ( ) ; Validate . notNull ( user , "The user object is defective: lacks entity identifier." ) ; final String userEntityKey = userEntityIdentifier . getKey ( ) ; Validate . notNull ( userEntityKey , "The user object is defective: lacks entity key." ) ; final Class userEntityType = userEntityIdentifier . getType ( ) ; Validate . notNull ( userEntityType , "The user object is defective: lacks entity type." ) ; final IAuthorizationPrincipal principal = AuthorizationServiceFacade . instance ( ) . newPrincipal ( userEntityKey , userEntityType ) ; return principal ; }
Convenience method for converting an IPerson to an IAuthorizationPrincipal .
34,916
private String primGetName ( String key ) { String name = key ; final IPersonAttributes personAttributes = this . paDao . getPerson ( name ) ; if ( personAttributes != null ) { Object displayName = personAttributes . getAttributeValue ( "displayName" ) ; String displayNameStr = "" ; if ( displayName != null ) { displayNameStr = String . valueOf ( displayName ) ; if ( StringUtils . isNotEmpty ( displayNameStr ) ) { name = displayNameStr ; } } } return name ; }
Actually lookup a user name using the underlying IPersonAttributeDao .
34,917
private Set < IPermission > removeInactivePermissions ( final IPermission [ ] perms ) { Date now = new Date ( ) ; Set < IPermission > rslt = new HashSet < > ( 1 ) ; for ( int i = 0 ; i < perms . length ; i ++ ) { IPermission p = perms [ i ] ; if ( ( p . getEffective ( ) == null || ! p . getEffective ( ) . after ( now ) ) && ( p . getExpires ( ) == null || p . getExpires ( ) . after ( now ) ) ) { rslt . add ( p ) ; } } return rslt ; }
Returns a Set containing those IPermission instances where the present date is neither after the permission expiration if present nor before the permission start date if present . Only permissions objects that have been filtered by this method should be checked .
34,918
static void throwIfUnrecognizedParamName ( Enumeration initParamNames ) throws ServletException { final Set < String > recognizedParameterNames = new HashSet < String > ( ) ; recognizedParameterNames . add ( ALLOW_MULTI_VALUED_PARAMETERS ) ; recognizedParameterNames . add ( PARAMETERS_TO_CHECK ) ; recognizedParameterNames . add ( CHARACTERS_TO_FORBID ) ; while ( initParamNames . hasMoreElements ( ) ) { final String initParamName = ( String ) initParamNames . nextElement ( ) ; if ( ! recognizedParameterNames . contains ( initParamName ) ) { throw new ServletException ( "Unrecognized init parameter [" + initParamName + "]. Failing safe. Typo" + " in the web.xml configuration? " + " Misunderstanding about the configuration " + RequestParameterPolicyEnforcementFilter . class . getSimpleName ( ) + " expects?" ) ; } } }
Examines the Filter init parameter names and throws ServletException if they contain an unrecognized init parameter name .
34,919
static Set < String > parseParametersToCheck ( final String initParamValue ) { final Set < String > parameterNames = new HashSet < String > ( ) ; if ( null == initParamValue ) { return parameterNames ; } final String [ ] tokens = initParamValue . split ( "\\s+" ) ; if ( 0 == tokens . length ) { throw new IllegalArgumentException ( "[" + initParamValue + "] had no tokens but should have had at least one token." ) ; } if ( 1 == tokens . length && "*" . equals ( tokens [ 0 ] ) ) { return parameterNames ; } for ( final String parameterName : tokens ) { if ( "*" . equals ( parameterName ) ) { throw new IllegalArgumentException ( "Star token encountered among other tokens in parsing [" + initParamValue + "]" ) ; } parameterNames . add ( parameterName ) ; } return parameterNames ; }
Parse the whitespace delimited String of parameters to check .
34,920
static void requireNotMultiValued ( final Set < String > parametersToCheck , final Map parameterMap ) { for ( final String parameterName : parametersToCheck ) { if ( parameterMap . containsKey ( parameterName ) ) { final String [ ] values = ( String [ ] ) parameterMap . get ( parameterName ) ; if ( values . length > 1 ) { throw new IllegalStateException ( "Parameter [" + parameterName + "] had multiple values [" + Arrays . toString ( values ) + "] but at most one value is allowable." ) ; } } } }
For each parameter to check verify that it has zero or one value .
34,921
public synchronized void authenticate ( ) throws PortalSecurityException { int i ; Enumeration e = mySubContexts . elements ( ) ; while ( e . hasMoreElements ( ) ) { ISecurityContext sctx = ( ( Entry ) e . nextElement ( ) ) . getCtx ( ) ; try { if ( sctx instanceof IParentAwareSecurityContext ) { ( ( IParentAwareSecurityContext ) sctx ) . authenticate ( this ) ; } else { sctx . authenticate ( ) ; } } catch ( Exception ex ) { log . error ( "Exception authenticating subcontext " + sctx , ex ) ; } if ( stopWhenAuthenticated && sctx . isAuthenticated ( ) ) { break ; } } if ( this . myOpaqueCredentials . credentialstring != null ) { for ( i = 0 ; i < this . myOpaqueCredentials . credentialstring . length ; i ++ ) this . myOpaqueCredentials . credentialstring [ i ] = 0 ; myOpaqueCredentials . credentialstring = null ; } return ; }
We walk the chain of subcontexts assigning principals and opaqueCredentials from the parent . Note that the contexts themselves should resist actually performing the assignment if an assignment has already been made to either the credentials or the UID .
34,922
public synchronized Enumeration getSubContexts ( ) { Enumeration e = mySubContexts . elements ( ) ; class Adapter implements Enumeration { Enumeration base ; public Adapter ( Enumeration e ) { this . base = e ; } public boolean hasMoreElements ( ) { return base . hasMoreElements ( ) ; } public Object nextElement ( ) { return ( ( Entry ) base . nextElement ( ) ) . getCtx ( ) ; } } return new Adapter ( e ) ; }
be returned in the order they appeared in the properties file .
34,923
public synchronized Enumeration getSubContextNames ( ) { Vector scNames = new Vector ( ) ; for ( int i = 0 ; i < mySubContexts . size ( ) ; i ++ ) { Entry entry = ( Entry ) mySubContexts . get ( i ) ; if ( entry . getKey ( ) != null ) { scNames . add ( entry . getKey ( ) ) ; } } return scNames . elements ( ) ; }
Returns an Enumeration of the names of the subcontexts .
34,924
public String initializeView ( PortletRequest req , Model model ) { final IUserInstance ui = userInstanceManager . getUserInstance ( portalRequestUtils . getCurrentPortalRequest ( ) ) ; final UserPreferencesManager upm = ( UserPreferencesManager ) ui . getPreferencesManager ( ) ; final IUserLayoutManager ulm = upm . getUserLayoutManager ( ) ; final IUserLayout userLayout = ulm . getUserLayout ( ) ; model . addAttribute ( "marketplaceFname" , this . marketplaceFName ) ; final List < IUserLayoutNodeDescription > collections = favoritesUtils . getFavoriteCollections ( userLayout ) ; model . addAttribute ( "collections" , collections ) ; final List < IUserLayoutNodeDescription > rawFavorites = favoritesUtils . getFavoritePortletLayoutNodes ( userLayout ) ; final String username = req . getRemoteUser ( ) != null ? req . getRemoteUser ( ) : PersonFactory . getGuestUsernames ( ) . get ( 0 ) ; final IAuthorizationPrincipal principal = authorizationService . newPrincipal ( username , IPerson . class ) ; final List < IUserLayoutNodeDescription > favorites = new ArrayList < > ( ) ; for ( IUserLayoutNodeDescription nodeDescription : rawFavorites ) { if ( nodeDescription instanceof IUserLayoutChannelDescription ) { final IUserLayoutChannelDescription channelDescription = ( IUserLayoutChannelDescription ) nodeDescription ; if ( principal . canRender ( channelDescription . getChannelPublishId ( ) ) ) { favorites . add ( nodeDescription ) ; } } } model . addAttribute ( "favorites" , favorites ) ; String viewName = "jsp/Favorites/view" ; if ( collections . isEmpty ( ) && favorites . isEmpty ( ) ) { viewName = "jsp/Favorites/view_zero" ; } logger . debug ( "Favorites Portlet VIEW mode render populated model [{}] for render by view {}." , model , viewName ) ; return viewName ; }
Handles all Favorites portlet VIEW mode renders . Populates model with user s favorites and selects a view to display those favorites .
34,925
protected final Date getExpiration ( RenderRequest renderRequest ) { final PortletSession portletSession = renderRequest . getPortletSession ( ) ; final Date rslt = new Date ( portletSession . getLastAccessedTime ( ) + ( ( long ) portletSession . getMaxInactiveInterval ( ) * 1000L ) ) ; return rslt ; }
Point at which the JWT expires
34,926
public boolean canPrincipalManage ( IAuthorizationPrincipal principal , String portletDefinitionId ) throws AuthorizationException { final String owner = IPermission . PORTAL_PUBLISH ; final String target = IPermission . PORTLET_PREFIX + portletDefinitionId ; IPortletDefinition portlet = this . portletDefinitionRegistry . getPortletDefinition ( portletDefinitionId ) ; if ( portlet == null ) { return doesPrincipalHavePermission ( principal , owner , IPermission . PORTLET_MANAGER_APPROVED_ACTIVITY , target ) ; } final IPortletLifecycleEntry highestLifecycleEntryDefined = portlet . getLifecycle ( ) . get ( portlet . getLifecycle ( ) . size ( ) - 1 ) ; String activity ; switch ( highestLifecycleEntryDefined . getLifecycleState ( ) ) { case CREATED : activity = IPermission . PORTLET_MANAGER_CREATED_ACTIVITY ; break ; case APPROVED : activity = IPermission . PORTLET_MANAGER_APPROVED_ACTIVITY ; break ; case PUBLISHED : activity = IPermission . PORTLET_MANAGER_ACTIVITY ; break ; case EXPIRED : activity = IPermission . PORTLET_MANAGER_EXPIRED_ACTIVITY ; break ; case MAINTENANCE : activity = IPermission . PORTLET_MANAGER_MAINTENANCE_ACTIVITY ; break ; default : final String msg = "Unrecognized portlet lifecycle state: " + highestLifecycleEntryDefined . getLifecycleState ( ) ; throw new IllegalStateException ( msg ) ; } return doesPrincipalHavePermission ( principal , owner , activity , target ) ; }
Answers if the principal has permission to MANAGE this Channel .
34,927
public boolean canPrincipalRender ( IAuthorizationPrincipal principal , String portletDefinitionId ) throws AuthorizationException { return canPrincipalSubscribe ( principal , portletDefinitionId ) ; }
Answers if the principal has permission to RENDER this Channel . This implementation currently delegates to the SUBSCRIBE permission .
34,928
public boolean canPrincipalSubscribe ( IAuthorizationPrincipal principal , String portletDefinitionId ) { String owner = IPermission . PORTAL_SUBSCRIBE ; IPortletDefinition portlet = this . portletDefinitionRegistry . getPortletDefinition ( portletDefinitionId ) ; if ( portlet == null ) { return false ; } String target = PermissionHelper . permissionTargetIdForPortletDefinition ( portlet ) ; PortletLifecycleState state = portlet . getLifecycleState ( ) ; String permission ; if ( state . equals ( PortletLifecycleState . PUBLISHED ) || state . equals ( PortletLifecycleState . MAINTENANCE ) ) { permission = IPermission . PORTLET_SUBSCRIBER_ACTIVITY ; } else if ( state . equals ( PortletLifecycleState . APPROVED ) ) { permission = IPermission . PORTLET_SUBSCRIBER_APPROVED_ACTIVITY ; } else if ( state . equals ( PortletLifecycleState . CREATED ) ) { permission = IPermission . PORTLET_SUBSCRIBER_CREATED_ACTIVITY ; } else if ( state . equals ( PortletLifecycleState . EXPIRED ) ) { permission = IPermission . PORTLET_SUBSCRIBER_EXPIRED_ACTIVITY ; } else { throw new AuthorizationException ( "Unrecognized lifecycle state for channel " + portletDefinitionId ) ; } return doesPrincipalHavePermission ( principal , owner , permission , target ) ; }
Answers if the principal has permission to SUBSCRIBE to this Channel .
34,929
public IAuthorizationPrincipal newPrincipal ( String key , Class type ) { final Tuple < String , Class > principalKey = new Tuple < > ( key , type ) ; final Element element = this . principalCache . get ( principalKey ) ; return ( IAuthorizationPrincipal ) element . getObjectValue ( ) ; }
Factory method for IAuthorizationPrincipal . First check the principal cache and if not present create the principal and cache it .
34,930
private IPermission [ ] primGetPermissionsForPrincipal ( IAuthorizationPrincipal principal ) throws AuthorizationException { if ( ! this . cachePermissions ) { return getUncachedPermissionsForPrincipal ( principal , null , null , null ) ; } IPermissionSet ps = null ; ps = cacheGet ( principal ) ; if ( ps == null ) synchronized ( principal ) { ps = cacheGet ( principal ) ; if ( ps == null ) { IPermission [ ] permissions = getUncachedPermissionsForPrincipal ( principal , null , null , null ) ; ps = new PermissionSetImpl ( permissions , principal ) ; cacheAdd ( ps ) ; } } return ps . getPermissions ( ) ; }
Returns permissions for a principal . First check the entity caching service and if the permissions have not been cached retrieve and cache them .
34,931
private String getUsernameForUserId ( int id ) { if ( id > 0 ) { String username = userIdentityStore . getPortalUserName ( id ) ; if ( username != null ) { return username ; } logger . warn ( "Invalid userID {} found when exporting a portlet; return system username instead" , id ) ; } return systemUsername ; }
Returns the username for a valid userId else the system username
34,932
private IPortletDefinition savePortletDefinition ( IPortletDefinition definition , List < PortletCategory > categories , Map < ExternalPermissionDefinition , Set < IGroupMember > > permissionMap ) { boolean newChannel = ( definition . getPortletDefinitionId ( ) == null ) ; definition = portletDefinitionDao . savePortletDefinition ( definition ) ; definition = portletDefinitionDao . getPortletDefinitionByFname ( definition . getFName ( ) ) ; final String defId = definition . getPortletDefinitionId ( ) . getStringId ( ) ; final IEntity portletDefEntity = GroupService . getEntity ( defId , IPortletDefinition . class ) ; synchronized ( this . groupUpdateLock ) { if ( ! newChannel ) { for ( IEntityGroup group : portletDefEntity . getAncestorGroups ( ) ) { group . removeChild ( portletDefEntity ) ; group . update ( ) ; } } for ( PortletCategory category : categories ) { final IEntityGroup categoryGroup = GroupService . findGroup ( category . getId ( ) ) ; categoryGroup . addChild ( portletDefEntity ) ; categoryGroup . updateMembers ( ) ; } final AuthorizationServiceFacade authService = AuthorizationServiceFacade . instance ( ) ; final String target = PermissionHelper . permissionTargetIdForPortletDefinition ( definition ) ; Map < String , Collection < ExternalPermissionDefinition > > permissionsBySystem = getPermissionsBySystem ( permissionMap . keySet ( ) ) ; for ( String system : permissionsBySystem . keySet ( ) ) { Collection < ExternalPermissionDefinition > systemPerms = permissionsBySystem . get ( system ) ; final IUpdatingPermissionManager upm = authService . newUpdatingPermissionManager ( system ) ; final List < IPermission > permissions = new ArrayList < > ( ) ; for ( ExternalPermissionDefinition permissionDef : systemPerms ) { Set < IGroupMember > members = permissionMap . get ( permissionDef ) ; for ( final IGroupMember member : members ) { final IAuthorizationPrincipal authPrincipal = authService . newPrincipal ( member ) ; final IPermission permEntity = upm . newPermission ( authPrincipal ) ; permEntity . setType ( IPermission . PERMISSION_TYPE_GRANT ) ; permEntity . setActivity ( permissionDef . getActivity ( ) ) ; permEntity . setTarget ( target ) ; permissions . add ( permEntity ) ; } } if ( ! newChannel ) { for ( ExternalPermissionDefinition permissionName : permissionMap . keySet ( ) ) { IPermission [ ] oldPermissions = upm . getPermissions ( permissionName . getActivity ( ) , target ) ; upm . removePermissions ( oldPermissions ) ; } } upm . addPermissions ( permissions . toArray ( new IPermission [ permissions . size ( ) ] ) ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Portlet " + defId + " has been " + ( newChannel ? "published" : "modified" ) + "." ) ; } return definition ; }
Save a portlet definition .
34,933
private static Calendar getCalendar ( Date date ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( date ) ; return calendar ; }
Utility method to convert a date to a calendar .
34,934
private Set < IGroupMember > toGroupMembers ( List < String > groupNames , String fname ) { final Set < IGroupMember > groups = new HashSet < > ( ) ; for ( String groupName : groupNames ) { EntityIdentifier [ ] gs = GroupService . searchForGroups ( groupName , IGroupConstants . SearchMethod . DISCRETE , IPerson . class ) ; IGroupMember group ; if ( gs != null && gs . length > 0 ) { group = GroupService . findGroup ( gs [ 0 ] . getKey ( ) ) ; } else { group = GroupService . findGroup ( groupName ) ; } if ( group == null ) { throw new IllegalArgumentException ( "No group '" + groupName + "' found when importing portlet: " + fname ) ; } groups . add ( group ) ; } return groups ; }
Convert a list of group names to a list of groups .
34,935
private ExternalPermissionDefinition toExternalPermissionDefinition ( String system , String activity ) { ExternalPermissionDefinition def = ExternalPermissionDefinition . find ( system , activity ) ; if ( def != null ) { return def ; } String delim = "" ; StringBuilder buffer = new StringBuilder ( ) ; for ( ExternalPermissionDefinition perm : ExternalPermissionDefinition . values ( ) ) { buffer . append ( delim ) ; buffer . append ( perm . toString ( ) ) ; delim = ", " ; } throw new IllegalArgumentException ( "Permission type " + system + "." + activity + " is not supported. " + "The only supported permissions at this time are: " + buffer . toString ( ) ) ; }
Check that a permission type from the XML file matches with a real permission .
34,936
public static void setCachingHeaders ( int maxAge , boolean publicScope , long lastModified , PortletResourceOutputHandler portletResourceOutputHandler ) { if ( maxAge != 0 ) { portletResourceOutputHandler . setDateHeader ( "Last-Modified" , lastModified ) ; if ( publicScope ) { portletResourceOutputHandler . setHeader ( "CacheControl" , "public" ) ; } else { portletResourceOutputHandler . setHeader ( "CacheControl" , "private" ) ; } if ( maxAge < 0 ) { maxAge = YEAR_OF_SECONDS ; } portletResourceOutputHandler . setDateHeader ( "Expires" , System . currentTimeMillis ( ) + TimeUnit . SECONDS . toMillis ( maxAge ) ) ; portletResourceOutputHandler . addHeader ( "CacheControl" , "max-age=" + maxAge ) ; } }
Set the Last - Modified CacheControl and Expires headers based on the maxAge publicScope and lastModified .
34,937
public void perform ( ) throws PortalException { Element plfNode = HandlerUtils . getPLFNode ( ilfNode , person , false , false ) ; if ( plfNode == null ) return ; changeRestriction ( Constants . ATT_MOVE_ALLOWED , plfNode , moveAllowed ) ; changeRestriction ( Constants . ATT_MOVE_ALLOWED , ilfNode , moveAllowed ) ; changeRestriction ( Constants . ATT_DELETE_ALLOWED , plfNode , deleteAllowed ) ; changeRestriction ( Constants . ATT_DELETE_ALLOWED , ilfNode , deleteAllowed ) ; changeRestriction ( Constants . ATT_EDIT_ALLOWED , plfNode , editAllowed ) ; changeRestriction ( Constants . ATT_EDIT_ALLOWED , ilfNode , editAllowed ) ; if ( plfNode . getAttribute ( Constants . ATT_CHANNEL_ID ) . equals ( "" ) ) { changeRestriction ( Constants . ATT_ADD_CHILD_ALLOWED , plfNode , addChildAllowed ) ; changeRestriction ( Constants . ATT_ADD_CHILD_ALLOWED , ilfNode , addChildAllowed ) ; } }
Pushes the indicated restriction attribute changes into both the ILF and PLF versions of the layouts since this will only be done when editing a fragment .
34,938
private String getProxyTicket ( PortletRequest request ) { final HttpServletRequest httpServletRequest = this . portalRequestUtils . getPortletHttpRequest ( request ) ; String targetService = null ; try { URL url = null ; int port = request . getServerPort ( ) ; if ( port == 80 || port == 443 ) url = new URL ( request . getScheme ( ) , request . getServerName ( ) , request . getContextPath ( ) ) ; else url = new URL ( request . getScheme ( ) , request . getServerName ( ) , request . getServerPort ( ) , request . getContextPath ( ) ) ; targetService = url . toString ( ) ; } catch ( MalformedURLException e ) { log . error ( "Failed to create a URL for the target portlet" , e ) ; e . printStackTrace ( ) ; return null ; } final IUserInstance userInstance = userInstanceManager . getUserInstance ( httpServletRequest ) ; final IPerson person = userInstance . getPerson ( ) ; final ISecurityContext context = person . getSecurityContext ( ) ; if ( context == null ) { log . error ( "no security context, no proxy ticket passed to the portlet" ) ; return null ; } ISecurityContext casContext = getCasContext ( context ) ; if ( casContext == null ) { log . debug ( "no CAS security context, no proxy ticket passed to the portlet" ) ; return null ; } if ( ! casContext . isAuthenticated ( ) ) { log . debug ( "no CAS authentication, no proxy ticket passed to the portlet" ) ; return null ; } String proxyTicket = null ; try { proxyTicket = ( ( ICasSecurityContext ) casContext ) . getCasServiceToken ( targetService ) ; log . debug ( "Put proxy ticket in userinfo: " + proxyTicket ) ; } catch ( CasProxyTicketAcquisitionException e ) { log . error ( "no proxy ticket passed to the portlet: " + e ) ; } return proxyTicket ; }
Attempt to get a proxy ticket for the current portlet .
34,939
@ SuppressWarnings ( "unchecked" ) private static ISecurityContext getCasContext ( ISecurityContext context ) { if ( context instanceof ICasSecurityContext ) { return context ; } Enumeration contextEnum = context . getSubContexts ( ) ; while ( contextEnum . hasMoreElements ( ) ) { ISecurityContext subContext = ( ISecurityContext ) contextEnum . nextElement ( ) ; if ( subContext instanceof ICasSecurityContext ) { return subContext ; } } return null ; }
Looks for a security context
34,940
protected List < AcademicTermDetail > getAcademicTermsAfter ( DateTime start ) { final List < AcademicTermDetail > terms = this . eventAggregationManagementDao . getAcademicTermDetails ( ) ; final int index = Collections . binarySearch ( terms , new AcademicTermDetailImpl ( start . toDateMidnight ( ) , start . plusDays ( 1 ) . toDateMidnight ( ) , "" ) ) ; if ( index > 0 ) { return terms . subList ( index , terms . size ( ) ) ; } else if ( index < 0 ) { return terms . subList ( - ( index + 1 ) , terms . size ( ) ) ; } return terms ; }
Return a sorted list of AcademicTermDetail objects where the the first element of the list where the first element is the first term that starts after the specified start DateTime .
34,941
protected File getFileRoot ( Class type ) { String path = getGroupsRootPath ( ) + type . getName ( ) ; File f = new File ( path ) ; return ( f . exists ( ) ) ? f : null ; }
Returns a File that is the root for groups of the given type .
34,942
private void primGetAllDirectoriesBelow ( File dir , Set allDirectories ) { File [ ] files = dir . listFiles ( fileFilter ) ; for ( int i = 0 ; i < files . length ; i ++ ) { if ( files [ i ] . isDirectory ( ) ) { primGetAllDirectoriesBelow ( files [ i ] , allDirectories ) ; allDirectories . add ( files [ i ] ) ; } } }
Returns all directories under dir .
34,943
@ RequestMapping ( value = "/deletePermission" , method = RequestMethod . POST ) public void deletePermission ( @ RequestParam ( "principal" ) String principal , @ RequestParam ( "owner" ) String owner , @ RequestParam ( "activity" ) String activity , @ RequestParam ( "target" ) String target , HttpServletRequest request , HttpServletResponse response ) throws Exception { final IPerson currentUser = personManager . getPerson ( ( HttpServletRequest ) request ) ; if ( ! permissionAdministrationHelper . canEditPermission ( currentUser , target ) || ! permissionAdministrationHelper . canViewPermission ( currentUser , target ) ) { response . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; return ; } JsonEntityBean bean = groupListHelper . getEntityForPrincipal ( principal ) ; if ( bean != null ) { IAuthorizationPrincipal p = groupListHelper . getPrincipalForEntity ( bean ) ; IPermission [ ] directPermissions = permissionStore . select ( owner , p . getPrincipalString ( ) , activity , target , null ) ; this . authorizationService . removePermissions ( directPermissions ) ; } else { log . warn ( "Unable to resolve the following principal (will " + "be omitted from the list of assignments): " + principal ) ; } response . setStatus ( HttpServletResponse . SC_OK ) ; return ; }
Deletes a specific permission
34,944
protected void cancelWorker ( HttpServletRequest request , IPortletExecutionWorker < ? > portletExecutionWorker ) { final IPortletWindowId portletWindowId = portletExecutionWorker . getPortletWindowId ( ) ; final IPortletWindow portletWindow = this . portletWindowRegistry . getPortletWindow ( request , portletWindowId ) ; this . logger . warn ( "{} has not completed, adding to hung-worker cleanup queue: {}" , portletExecutionWorker , portletWindow ) ; portletExecutionWorker . cancel ( ) ; this . portletExecutionEventFactory . publishPortletHungEvent ( request , this , portletExecutionWorker ) ; hungWorkers . offer ( portletExecutionWorker ) ; }
Cancel the worker and add it to the hung workers queue
34,945
public void startPortletHeaderRender ( IPortletWindowId portletWindowId , HttpServletRequest request , HttpServletResponse response ) { if ( doesPortletNeedHeaderWorker ( portletWindowId , request ) ) { this . startPortletHeaderRenderInternal ( portletWindowId , request , response ) ; } else { this . logger . debug ( "ignoring startPortletHeadRender request since containerRuntimeOption is not present for portletWindowId " + portletWindowId ) ; } }
Only actually starts rendering the head if the portlet has the javax . portlet . renderHeaders container - runtime - option present and set to true .
34,946
protected PortletRenderResult getPortletRenderResult ( IPortletWindowId portletWindowId , HttpServletRequest request , HttpServletResponse response ) throws Exception { final IPortletRenderExecutionWorker tracker = getRenderedPortletBodyWorker ( portletWindowId , request , response ) ; final long timeout = getPortletRenderTimeout ( portletWindowId , request ) ; return tracker . get ( timeout ) ; }
Returns the PortletRenderResult waiting up to the portlet s timeout
34,947
protected IPortletRenderExecutionWorker startPortletHeaderRenderInternal ( IPortletWindowId portletWindowId , HttpServletRequest request , HttpServletResponse response ) { IPortletRenderExecutionWorker portletHeaderRenderWorker = this . portletWorkerFactory . createRenderHeaderWorker ( request , response , portletWindowId ) ; portletHeaderRenderWorker . submit ( ) ; final Map < IPortletWindowId , IPortletRenderExecutionWorker > portletHeaderRenderingMap = this . getPortletHeaderRenderingMap ( request ) ; portletHeaderRenderingMap . put ( portletWindowId , portletHeaderRenderWorker ) ; return portletHeaderRenderWorker ; }
create and submit the portlet header rendering job to the thread pool
34,948
protected IPortletRenderExecutionWorker startPortletRenderInternal ( IPortletWindowId portletWindowId , HttpServletRequest request , HttpServletResponse response ) { final Map < IPortletWindowId , Exception > portletFailureMap = getPortletErrorMap ( request ) ; final Exception cause = portletFailureMap . remove ( portletWindowId ) ; final IPortletRenderExecutionWorker portletRenderExecutionWorker ; if ( null != cause ) { portletRenderExecutionWorker = this . portletWorkerFactory . createFailureWorker ( request , response , portletWindowId , cause ) ; } else { IPortletWindow portletWindow = portletWindowRegistry . getPortletWindow ( request , portletWindowId ) ; IPortletDefinition portletDef = portletWindow . getPortletEntity ( ) . getPortletDefinition ( ) ; if ( portletDef . getLifecycleState ( ) . equals ( PortletLifecycleState . MAINTENANCE ) ) { portletRenderExecutionWorker = this . portletWorkerFactory . createFailureWorker ( request , response , portletWindowId , new MaintenanceModeException ( ) ) ; } else { portletRenderExecutionWorker = this . portletWorkerFactory . createRenderWorker ( request , response , portletWindowId ) ; } } portletRenderExecutionWorker . submit ( ) ; final Map < IPortletWindowId , IPortletRenderExecutionWorker > portletRenderingMap = this . getPortletRenderingMap ( request ) ; portletRenderingMap . put ( portletWindowId , portletRenderExecutionWorker ) ; return portletRenderExecutionWorker ; }
create and submit the portlet content rendering job to the thread pool
34,949
private boolean add ( T e , boolean failWhenFull ) { final Queue < T > queue = this . getOrCreateQueue ( e ) ; this . writeLock . lock ( ) ; try { if ( this . size == this . capacity ) { if ( failWhenFull ) { throw new IllegalStateException ( "Queue is at capacity: " + this . capacity ) ; } return false ; } final boolean added = queue . add ( e ) ; if ( added ) { this . size ++ ; this . notEmpty . signal ( ) ; } return added ; } finally { this . writeLock . unlock ( ) ; } }
Adds the element to the queue
34,950
protected void deletePortletEntity ( HttpServletRequest request , IPortletEntity portletEntity , boolean cacheOnly ) { final IPortletEntityId portletEntityId = portletEntity . getPortletEntityId ( ) ; final PortletEntityCache < IPortletEntity > portletEntityMap = this . getPortletEntityMap ( request ) ; portletEntityMap . removeEntity ( portletEntityId ) ; final PortletEntityCache < PortletEntityData > portletEntityDataMap = this . getPortletEntityDataMap ( request ) ; portletEntityDataMap . removeEntity ( portletEntityId ) ; if ( ! cacheOnly && portletEntity instanceof PersistentPortletEntityWrapper ) { final IPortletEntity persistentEntity = ( ( PersistentPortletEntityWrapper ) portletEntity ) . getPersistentEntity ( ) ; try { this . portletEntityDao . deletePortletEntity ( persistentEntity ) ; } catch ( HibernateOptimisticLockingFailureException e ) { this . logger . warn ( "This persistent portlet has already been deleted: " + persistentEntity + ", trying to find and delete by layout node and user." ) ; final IPortletEntity existingPersistentEntity = this . portletEntityDao . getPortletEntity ( persistentEntity . getLayoutNodeId ( ) , persistentEntity . getUserId ( ) ) ; if ( existingPersistentEntity != null ) { this . portletEntityDao . deletePortletEntity ( existingPersistentEntity ) ; } } } }
Delete a portlet entity removes it from the request session and persistent stores
34,951
protected IPortletEntity getPortletEntity ( HttpServletRequest request , PortletEntityCache < IPortletEntity > portletEntityCache , IPortletEntityId portletEntityId , String layoutNodeId , int userId ) { IPortletEntity portletEntity ; if ( portletEntityId != null ) { portletEntity = portletEntityCache . getEntity ( portletEntityId ) ; } else { portletEntity = portletEntityCache . getEntity ( layoutNodeId , userId ) ; } if ( portletEntity != null ) { logger . trace ( "Found IPortletEntity {} in request cache" , portletEntity . getPortletEntityId ( ) ) ; return portletEntity ; } final PortletEntityCache < PortletEntityData > portletEntityDataMap = this . getPortletEntityDataMap ( request ) ; final PortletEntityData portletEntityData ; if ( portletEntityId != null ) { portletEntityData = portletEntityDataMap . getEntity ( portletEntityId ) ; } else { portletEntityData = portletEntityDataMap . getEntity ( layoutNodeId , userId ) ; } if ( portletEntityData != null ) { portletEntity = portletEntityCache . storeIfAbsentEntity ( portletEntityData . getPortletEntityId ( ) , new Function < IPortletEntityId , IPortletEntity > ( ) { public IPortletEntity apply ( IPortletEntityId input ) { logger . trace ( "Found PortletEntityData {} in session cache, caching wrapper in the request" , portletEntityData . getPortletEntityId ( ) ) ; return wrapPortletEntityData ( portletEntityData ) ; } } ) ; return portletEntity ; } if ( portletEntityId != null ) { if ( portletEntityId instanceof PortletEntityIdImpl ) { final PortletEntityIdImpl consistentPortletEntityId = ( PortletEntityIdImpl ) portletEntityId ; final String localLayoutNodeId = consistentPortletEntityId . getLayoutNodeId ( ) ; final int localUserId = consistentPortletEntityId . getUserId ( ) ; portletEntity = this . portletEntityDao . getPortletEntity ( localLayoutNodeId , localUserId ) ; } else { portletEntity = this . portletEntityDao . getPortletEntity ( portletEntityId ) ; } } else { portletEntity = this . portletEntityDao . getPortletEntity ( layoutNodeId , userId ) ; } if ( portletEntity != null ) { final IPortletEntityId consistentPortletEntityId = this . createConsistentPortletEntityId ( portletEntity ) ; final IPortletEntity anonPortletEntity = portletEntity ; portletEntity = portletEntityCache . storeIfAbsentEntity ( consistentPortletEntityId , new Function < IPortletEntityId , IPortletEntity > ( ) { public IPortletEntity apply ( IPortletEntityId input ) { logger . trace ( "Found persistent IPortletEntity {}, mapped id to {}, caching the wrapper in the request" , anonPortletEntity . getPortletEntityId ( ) , consistentPortletEntityId ) ; return new PersistentPortletEntityWrapper ( anonPortletEntity , consistentPortletEntityId ) ; } } ) ; return portletEntity ; } return null ; }
Lookup the portlet entity by layoutNodeId and userId
34,952
private static Element getEditSet ( Element node , Document plf , IPerson person , boolean create ) throws PortalException { Node child = node . getFirstChild ( ) ; while ( child != null ) { if ( child . getNodeName ( ) . equals ( Constants . ELM_EDIT_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 edit set node " + "Id for userId=" + person . getID ( ) , e ) ; } Element editSet = plf . createElement ( Constants . ELM_EDIT_SET ) ; editSet . setAttribute ( Constants . ATT_TYPE , Constants . ELM_EDIT_SET ) ; editSet . setAttribute ( Constants . ATT_ID , ID ) ; node . appendChild ( editSet ) ; return editSet ; }
Get the edit set if any stored in the passed in node . If not found and if the create flag is true then create a new edit set and add it as a child to the passed in node . Then return it .
34,953
static void addEditDirective ( Element plfNode , String attributeName , IPerson person ) throws PortalException { addDirective ( plfNode , attributeName , Constants . ELM_EDIT , person ) ; }
Create and append an edit directive to the edit set if not there . This only records that the attribute was changed and the value in the plf copy node should be used if allowed during the merge at login time .
34,954
public static void addPrefsDirective ( Element plfNode , String attributeName , IPerson person ) throws PortalException { addDirective ( plfNode , attributeName , Constants . ELM_PREF , person ) ; }
Create and append a user preferences edit directive to the edit set if not there . This only records that the attribute was changed . The value will be in the user preferences object for the user .
34,955
private static void addDirective ( Element plfNode , String attributeName , String type , IPerson person ) throws PortalException { Document plf = ( Document ) person . getAttribute ( Constants . PLF ) ; Element editSet = getEditSet ( plfNode , plf , person , true ) ; Element child = ( Element ) editSet . getFirstChild ( ) ; Element edit = null ; while ( child != null && edit == null ) { if ( child . getNodeName ( ) . equals ( type ) && child . getAttribute ( Constants . ATT_NAME ) . equals ( attributeName ) ) edit = child ; child = ( Element ) child . getNextSibling ( ) ; } if ( edit == null ) { String ID = null ; try { ID = getDLS ( ) . getNextStructDirectiveId ( person ) ; } catch ( Exception e ) { throw new PortalException ( "Exception encountered while " + "generating new edit node " + "Id for userId=" + person . getID ( ) , e ) ; } edit = plf . createElement ( type ) ; edit . setAttribute ( Constants . ATT_TYPE , type ) ; edit . setAttribute ( Constants . ATT_ID , ID ) ; edit . setAttribute ( Constants . ATT_NAME , attributeName ) ; editSet . appendChild ( edit ) ; } }
Create and append an edit directive to the edit set if not there .
34,956
public static boolean applyEditSet ( Element plfChild , Element original ) { Element editSet = null ; try { editSet = getEditSet ( plfChild , null , null , false ) ; } catch ( Exception e ) { return false ; } if ( editSet == null || editSet . getChildNodes ( ) . getLength ( ) == 0 ) return false ; if ( original . getAttribute ( Constants . ATT_EDIT_ALLOWED ) . equals ( "false" ) ) { plfChild . removeChild ( editSet ) ; return false ; } Document ilf = original . getOwnerDocument ( ) ; boolean attributeChanged = false ; Element edit = ( Element ) editSet . getFirstChild ( ) ; while ( edit != null ) { String attribName = edit . getAttribute ( Constants . ATT_NAME ) ; Attr attr = plfChild . getAttributeNode ( attribName ) ; if ( edit . getNodeName ( ) . equals ( Constants . ELM_PREF ) ) attributeChanged = true ; else if ( attr == null ) { attr = original . getAttributeNode ( attribName ) ; if ( attr == null ) editSet . removeChild ( edit ) ; else { original . removeAttribute ( attribName ) ; attributeChanged = true ; } } else { Attr origAttr = original . getAttributeNode ( attribName ) ; if ( origAttr == null ) { origAttr = ( Attr ) ilf . importNode ( attr , true ) ; original . setAttributeNode ( origAttr ) ; attributeChanged = true ; } else { if ( attr . getValue ( ) . equals ( origAttr . getValue ( ) ) ) { editSet . removeChild ( edit ) ; } else { origAttr . setValue ( attr . getValue ( ) ) ; attributeChanged = true ; } } } edit = ( Element ) edit . getNextSibling ( ) ; } return attributeChanged ; }
Evaluate whether attribute changes exist in the ilfChild and if so apply them . Returns true if some changes existed . If changes existed but matched those in the original node then they are not applicable are removed from the editSet and false is returned .
34,957
private static void removeDirective ( String elementId , String attributeName , String type , IPerson person ) { Document plf = ( Document ) person . getAttribute ( Constants . PLF ) ; Element node = plf . getElementById ( elementId ) ; if ( node == null ) return ; Element editSet = null ; try { editSet = getEditSet ( node , plf , person , false ) ; } catch ( Exception e ) { LOG . error ( e , e ) ; return ; } if ( editSet == null ) return ; Node child = editSet . getFirstChild ( ) ; while ( child != null ) { if ( child . getNodeName ( ) . equals ( type ) ) { Attr attr = ( ( Element ) child ) . getAttributeNode ( Constants . ATT_NAME ) ; if ( attr != null && attr . getValue ( ) . equals ( attributeName ) ) { editSet . removeChild ( child ) ; break ; } } child = child . getNextSibling ( ) ; } if ( editSet . getFirstChild ( ) == null ) node . removeChild ( editSet ) ; }
Searches for a command of the passed - in type and if found removes it from the user s PLF .
34,958
protected void removeExpiredPortletCookies ( HttpServletRequest request ) { Map < String , SessionOnlyPortletCookieImpl > sessionOnlyCookies = getSessionOnlyPortletCookieMap ( request ) ; for ( Entry < String , SessionOnlyPortletCookieImpl > entry : sessionOnlyCookies . entrySet ( ) ) { String key = entry . getKey ( ) ; SessionOnlyPortletCookieImpl sessionOnlyCookie = entry . getValue ( ) ; if ( sessionOnlyCookie . getExpires ( ) . isBeforeNow ( ) ) { sessionOnlyCookies . remove ( key ) ; } } }
Remove expired session only portlet cookies .
34,959
public InputSource resolveEntity ( String publicId , String systemId ) { InputStream inStream = null ; if ( systemId != null ) { if ( dtdName != null && systemId . indexOf ( dtdName ) != - 1 ) { inStream = getResourceAsStream ( dtdPath + "/" + dtdName ) ; } else if ( systemId . trim ( ) . equalsIgnoreCase ( "http://my.netscape.com/publish/formats/rss-0.91.dtd" ) ) { inStream = getResourceAsStream ( dtdPath + "/rss-0.91.dtd" ) ; } if ( null != inStream ) { return new InputSource ( inStream ) ; } } if ( publicId != null ) { publicId = publicId . trim ( ) ; for ( int i = 0 ; i < publicIds . length ; i ++ ) { if ( publicId . equalsIgnoreCase ( publicIds [ i ] . publicId ) ) { inStream = getResourceAsStream ( publicIds [ i ] . dtdFile ) ; if ( null != inStream ) { return new InputSource ( inStream ) ; } break ; } } } return null ; }
Sets up a new input source based on the dtd specified in the xml document
34,960
protected String verifyPortletWindowId ( HttpServletRequest request , IPortletWindowId portletWindowId ) { final IUserInstance userInstance = this . userInstanceManager . getUserInstance ( request ) ; final IUserPreferencesManager preferencesManager = userInstance . getPreferencesManager ( ) ; final IUserLayoutManager userLayoutManager = preferencesManager . getUserLayoutManager ( ) ; final IPortletWindow portletWindow = this . portletWindowRegistry . getPortletWindow ( request , portletWindowId ) ; final IPortletWindowId delegationParentWindowId = portletWindow . getDelegationParentId ( ) ; if ( delegationParentWindowId != null ) { return verifyPortletWindowId ( request , delegationParentWindowId ) ; } final IPortletEntity portletEntity = portletWindow . getPortletEntity ( ) ; final String channelSubscribeId = portletEntity . getLayoutNodeId ( ) ; final IUserLayoutNodeDescription node = userLayoutManager . getNode ( channelSubscribeId ) ; if ( node == null ) { throw new IllegalArgumentException ( "No layout node exists for id " + channelSubscribeId + " of window " + portletWindowId ) ; } return node . getId ( ) ; }
Verify the requested portlet window corresponds to a node in the user s layout and return the corresponding layout node id
34,961
private synchronized void initialize ( ) { Iterator types = EntityTypesLocator . getEntityTypes ( ) . getAllEntityTypes ( ) ; String factoryName = null ; while ( types . hasNext ( ) ) { Class type = ( Class ) types . next ( ) ; if ( type != Object . class ) { String factoryKey = "org.apereo.portal.services.EntityNameFinderService.NameFinderFactory.implementation_" + type . getName ( ) ; try { factoryName = PropertiesManager . getProperty ( factoryKey ) ; } catch ( Exception runtime ) { String dMsg = "EntityNameFinderService.initialize(): " + "could not find property for " + type . getName ( ) + " factory." ; log . debug ( dMsg ) ; } if ( factoryName != null ) { try { IEntityNameFinderFactory factory = ( IEntityNameFinderFactory ) Class . forName ( factoryName ) . newInstance ( ) ; getNameFinders ( ) . put ( type , factory . newFinder ( ) ) ; } catch ( Exception e ) { String eMsg = "EntityNameFinderService.initialize(): " + "Could not instantiate finder for " + type . getName ( ) + ": " ; log . error ( eMsg , e ) ; } } } } setInitialized ( true ) ; }
Gets all the entity types and tries to instantiate and cache a finder for each one . There needn t be a finder for every entity type so if there s no entry in the portal . properties we just log the fact and continue .
34,962
protected void synchronizeGroupMembersOnDelete ( IEntityGroup group ) throws GroupsException { GroupMemberImpl gmi = null ; for ( Iterator it = group . getChildren ( ) . iterator ( ) ; it . hasNext ( ) ; ) { gmi = ( GroupMemberImpl ) it . next ( ) ; gmi . invalidateInParentGroupsCache ( Collections . singleton ( ( IGroupMember ) gmi ) ) ; if ( cacheInUse ( ) ) { cacheUpdate ( gmi ) ; } } }
Remove the back pointers of the group members of the deleted group . Then update the cache to invalidate copies on peer servers .
34,963
protected void synchronizeGroupMembersOnUpdate ( IEntityGroup group ) throws GroupsException { EntityGroupImpl egi = ( EntityGroupImpl ) group ; GroupMemberImpl gmi = null ; for ( Iterator it = egi . getAddedMembers ( ) . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { gmi = ( GroupMemberImpl ) it . next ( ) ; gmi . invalidateInParentGroupsCache ( Collections . singleton ( ( IGroupMember ) gmi ) ) ; if ( cacheInUse ( ) ) { cacheUpdate ( gmi ) ; } } for ( Iterator it = egi . getRemovedMembers ( ) . values ( ) . iterator ( ) ; it . hasNext ( ) ; ) { gmi = ( GroupMemberImpl ) it . next ( ) ; gmi . invalidateInParentGroupsCache ( Collections . singleton ( ( IGroupMember ) gmi ) ) ; if ( cacheInUse ( ) ) { cacheUpdate ( gmi ) ; } } }
Adjust the back pointers of the updated group members to either add or remove the parent group . Then update the cache to invalidate copies on peer servers .
34,964
public Object doThreadContextClassLoaderUpdate ( ProceedingJoinPoint pjp ) throws Throwable { final Thread currentThread = Thread . currentThread ( ) ; final ClassLoader previousClassLoader = currentThread . getContextClassLoader ( ) ; Deque < ClassLoader > deque = PREVIOUS_CLASS_LOADER . get ( ) ; if ( deque == null ) { deque = new LinkedList < ClassLoader > ( ) ; PREVIOUS_CLASS_LOADER . set ( deque ) ; } deque . push ( previousClassLoader ) ; try { currentThread . setContextClassLoader ( PORTAL_CLASS_LOADER ) ; return pjp . proceed ( ) ; } finally { currentThread . setContextClassLoader ( previousClassLoader ) ; deque . removeFirst ( ) ; if ( deque . isEmpty ( ) ) { PREVIOUS_CLASS_LOADER . remove ( ) ; } } }
Wraps the targeted execution switching the current thread s context class loader to this classes class loader . Usage defined in persistanceContext . xml .
34,965
@ RequestMapping ( value = "/entity/{entityType}/{entityId}" , method = RequestMethod . DELETE ) public void deleteEntity ( @ PathVariable ( "entityType" ) String entityType , @ PathVariable ( "entityId" ) String entityId , HttpServletRequest request , HttpServletResponse response ) throws IOException { final IPerson person = personManager . getPerson ( request ) ; final EntityIdentifier ei = person . getEntityIdentifier ( ) ; final IAuthorizationPrincipal ap = AuthorizationServiceFacade . instance ( ) . newPrincipal ( ei . getKey ( ) , ei . getType ( ) ) ; if ( ! ap . hasPermission ( IPermission . PORTAL_SYSTEM , IPermission . DELETE_ACTIVITY , entityType ) ) { response . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; return ; } portalDataHandlerService . deleteData ( entityType , entityId ) ; response . setStatus ( HttpServletResponse . SC_NO_CONTENT ) ; }
Delete an uPortal database object . This method provides a REST interface for uPortal database object deletion .
34,966
public double getStandardDeviation ( ) { double stdDev = Double . NaN ; if ( getN ( ) > 0 ) { if ( getN ( ) > 1 ) { stdDev = FastMath . sqrt ( getVariance ( ) ) ; } else { stdDev = 0.0 ; } } return stdDev ; }
Returns the standard deviation of the values that have been added .
34,967
public void sendBatch ( ) { LrsStatement statement = null ; List < LrsStatement > list = new ArrayList < LrsStatement > ( ) ; while ( ( statement = statementQueue . poll ( ) ) != null ) { list . add ( statement ) ; } if ( ! list . isEmpty ( ) ) { postStatementList ( list ) ; } }
Send a batch of LRS statements . MUST BE SCHEDULED! Failure to properly configure this class will result in memory leaks .
34,968
private void postStatementList ( List < LrsStatement > list ) { try { ResponseEntity < Object > response = sendRequest ( STATEMENTS_REST_ENDPOINT , HttpMethod . POST , null , list , Object . class ) ; if ( response . getStatusCode ( ) . series ( ) == Series . SUCCESSFUL ) { logger . trace ( "LRS provider successfully sent to {}, statement list: {}" , getLRSUrl ( ) , list ) ; logger . trace ( "Sent batch statement. RESULTS: " + response . getBody ( ) . toString ( ) ) ; } else { logger . error ( "LRS provider failed to send to {}, statement list: {}" , getLRSUrl ( ) , list ) ; logger . error ( "- Response: {}" , response ) ; } } catch ( HttpClientErrorException e ) { logger . error ( "LRS provider for URL " + getLRSUrl ( ) + " failed to send statement list" , e ) ; logger . error ( "- Status: {}, Response: {}" , e . getStatusCode ( ) , e . getResponseBodyAsString ( ) ) ; } catch ( Exception e ) { logger . error ( "LRS provider for URL " + getLRSUrl ( ) + " failed to send statement list" , e ) ; } }
Send the list of batched LRS statements to the LRS .
34,969
public final void addValue ( double v ) { if ( isComplete ( ) ) { this . getLogger ( ) . warn ( "{} is already closed, the new value of {} will be ignored on: {}" , this . getClass ( ) . getSimpleName ( ) , v , this ) ; return ; } if ( this . statisticalSummary == null ) { this . statisticalSummary = new JpaStatisticalSummary ( ) ; } this . statisticalSummary . addValue ( v ) ; this . modified = true ; }
Add the value to the summary statistics
34,970
@ RequestMapping ( value = "/portletList" , method = RequestMethod . GET ) public ModelAndView listChannels ( WebRequest webRequest , HttpServletRequest request , @ RequestParam ( value = "type" , required = false ) String type ) { if ( TYPE_MANAGE . equals ( type ) ) { throw new UnsupportedOperationException ( "Moved to PortletRESTController under /api/portlets.json" ) ; } final IPerson user = personManager . getPerson ( request ) ; final Map < String , SortedSet < ? > > registry = getRegistryOriginal ( webRequest , user ) ; registry . put ( "channels" , new TreeSet < ChannelBean > ( ) ) ; return new ModelAndView ( "jsonView" , "registry" , registry ) ; }
Original pre - 4 . 3 version of this API . Always returns the entire contents of the Portlet Registry including uncategorized portlets to which the user has access . Access is based on the SUBSCRIBE permission .
34,971
public LrsStatement toLrsStatement ( PortalEvent event ) { return new LrsStatement ( getActor ( event ) , getVerb ( event ) , getLrsObject ( event ) ) ; }
Convert an event to an LrsStatement .
34,972
protected LrsActor getActor ( PortalEvent event ) { String username = event . getUserName ( ) ; return actorService . getLrsActor ( username ) ; }
Get the actor for an event .
34,973
protected URI buildUrn ( String ... parts ) { UrnBuilder builder = new UrnBuilder ( "UTF-8" , "tincan" , "uportal" , "activities" ) ; builder . add ( parts ) ; return builder . getUri ( ) ; }
Build the URN for the LrsStatement . This method attaches creates the base URN . Additional elements can be attached .
34,974
@ Bean ( name = "usernameAttributeProvider" ) public IUsernameAttributeProvider getUsernameAttributeProvider ( ) { final SimpleUsernameAttributeProvider rslt = new SimpleUsernameAttributeProvider ( ) ; rslt . setUsernameAttribute ( USERNAME_ATTRIBUTE ) ; return rslt ; }
Provides the default username attribute to use to the rest of the DAOs .
34,975
@ Bean ( name = "requestAttributeSourceFilter" ) public Filter getRequestAttributeSourceFilter ( ) { final RequestAttributeSourceFilter rslt = new RequestAttributeSourceFilter ( ) ; rslt . setAdditionalDescriptors ( getRequestAdditionalDescriptors ( ) ) ; rslt . setUsernameAttribute ( REMOTE_USER_ATTRIBUTE ) ; rslt . setRemoteUserAttribute ( REMOTE_USER_ATTRIBUTE ) ; rslt . setServerNameAttribute ( SERVER_NAME_ATTRIBUTE ) ; rslt . setProcessingPosition ( RequestAttributeSourceFilter . ProcessingPosition . BOTH ) ; Set < String > userAgent = new HashSet < > ( ) ; userAgent . add ( AGENT_DEVICE_ATTRIBUTE ) ; Map < String , Set < String > > headerAttributeMapping = new HashMap < > ( ) ; headerAttributeMapping . put ( USER_AGENT_KEY , userAgent ) ; rslt . setHeaderAttributeMapping ( headerAttributeMapping ) ; return rslt ; }
Servlet filter that creates an attribute for the serverName
34,976
@ Bean ( name = "sessionAttributesOverridesMap" ) @ Scope ( value = "globalSession" , proxyMode = ScopedProxyMode . TARGET_CLASS ) public Map getSessionAttributesOverridesMap ( ) { return new ConcurrentHashMap ( ) ; }
Store attribute overrides in a session scoped map to ensure overrides don t show up for other users and swapped attributes will be cleaned up on user logout .
34,977
@ Bean ( name = "personAttributeDao" ) @ Qualifier ( "personAttributeDao" ) public IPersonAttributeDao getPersonAttributeDao ( ) { final PortalRootPersonAttributeDao rslt = new PortalRootPersonAttributeDao ( ) ; rslt . setDelegatePersonAttributeDao ( getRequestAttributeMergingDao ( ) ) ; rslt . setAttributeOverridesMap ( getSessionAttributesOverridesMap ( ) ) ; return rslt ; }
Overrides DAO acts as the root it handles incorporating attributes from the attribute swapper utility wraps the caching DAO
34,978
@ Bean ( name = "requestAttributeMergingDao" ) @ Qualifier ( "uPortalInternal" ) public IPersonAttributeDao getRequestAttributeMergingDao ( ) { final MergingPersonAttributeDaoImpl rslt = new MergingPersonAttributeDaoImpl ( ) ; rslt . setUsernameAttributeProvider ( getUsernameAttributeProvider ( ) ) ; rslt . setMerger ( new ReplacingAttributeAdder ( ) ) ; final List < IPersonAttributeDao > daos = new ArrayList < > ( ) ; daos . add ( getRequestAttributesDao ( ) ) ; daos . add ( getCachingPersonAttributeDao ( ) ) ; rslt . setPersonAttributeDaos ( daos ) ; return rslt ; }
Merges attributes from the request with those from other DAOs .
34,979
@ Bean ( name = "requestAttributesDao" ) @ Qualifier ( "uPortalInternal" ) public IPersonAttributeDao getRequestAttributesDao ( ) { final AdditionalDescriptorsPersonAttributeDao rslt = new AdditionalDescriptorsPersonAttributeDao ( ) ; rslt . setDescriptors ( getRequestAdditionalDescriptors ( ) ) ; rslt . setUsernameAttributeProvider ( getUsernameAttributeProvider ( ) ) ; rslt . setCurrentUserProvider ( getCurrentUserProvider ( ) ) ; return rslt ; }
The person attributes DAO that returns the attributes from the request . Uses a currentUserProvider since the username may not always be provided by the request object .
34,980
@ Bean ( name = "cachingPersonAttributeDao" ) @ Qualifier ( "uPortalInternal" ) public IPersonAttributeDao getCachingPersonAttributeDao ( ) { final CachingPersonAttributeDaoImpl rslt = new CachingPersonAttributeDaoImpl ( ) ; rslt . setUsernameAttributeProvider ( getUsernameAttributeProvider ( ) ) ; rslt . setCacheNullResults ( true ) ; rslt . setCacheKeyGenerator ( getUserAttributeCacheKeyGenerator ( ) ) ; rslt . setUserInfoCache ( new MapCacheProvider < > ( userInfoCache ) ) ; rslt . setCachedPersonAttributesDao ( getMergingPersonAttributeDao ( ) ) ; return rslt ; }
Defines the order that the data providing DAOs are called results are cached by the outer caching DAO .
34,981
@ Bean ( name = "innerMergedPersonAttributeDaoList" ) public List < IPersonAttributeDao > getInnerMergedPersonAttributeDaoList ( ) { final List < IPersonAttributeDao > rslt = new ArrayList < > ( ) ; rslt . add ( getImpersonationStatusPersonAttributeDao ( ) ) ; rslt . add ( getUPortalAccountUserSource ( ) ) ; rslt . add ( getUPortalJdbcUserSource ( ) ) ; return rslt ; }
IPersonAttributeDao beans defined by implementors will be added to this list when the ApplicationContext comes up .
34,982
@ Bean ( name = "uPortalAccountUserSource" ) @ Qualifier ( "uPortalInternal" ) public IPersonAttributeDao getUPortalAccountUserSource ( ) { final LocalAccountPersonAttributeDao rslt = new LocalAccountPersonAttributeDao ( ) ; rslt . setLocalAccountDao ( localAccountDao ) ; rslt . setUsernameAttributeProvider ( getUsernameAttributeProvider ( ) ) ; final Map < String , String > queryAttributeMapping = new HashMap < > ( ) ; queryAttributeMapping . put ( USERNAME_ATTRIBUTE , USERNAME_ATTRIBUTE ) ; queryAttributeMapping . put ( GIVEN_NAME_ATTRIBUTE , GIVEN_NAME_ATTRIBUTE ) ; queryAttributeMapping . put ( SIR_NAME_ATTRIBUTE , SIR_NAME_ATTRIBUTE ) ; rslt . setQueryAttributeMapping ( queryAttributeMapping ) ; final Map < String , Set < String > > resultAttributeMapping = new HashMap < > ( ) ; resultAttributeMapping . put ( USERNAME_ATTRIBUTE , Stream . of ( USERNAME_ATTRIBUTE , UID_ATTRIBUTE , USER_LOGIN_ID_ATTRIBUTE ) . collect ( Collectors . toSet ( ) ) ) ; rslt . setResultAttributeMapping ( resultAttributeMapping ) ; return rslt ; }
Looks in the local person - directory data . This is only used for portal - local users such as fragment owners All attributes are searchable via this configuration results are cached by the underlying DAO .
34,983
@ Bean ( name = "uPortalJdbcUserSource" ) @ Qualifier ( "uPortalInternal" ) public IPersonAttributeDao getUPortalJdbcUserSource ( ) { final String sql = "SELECT USER_NAME FROM UP_USER WHERE {0}" ; final SingleRowJdbcPersonAttributeDao rslt = new SingleRowJdbcPersonAttributeDao ( personDb , sql ) ; rslt . setUsernameAttributeProvider ( getUsernameAttributeProvider ( ) ) ; rslt . setQueryAttributeMapping ( Collections . singletonMap ( USERNAME_ATTRIBUTE , USERNAME_COLUMN_NAME ) ) ; final Map < String , Set < String > > resultAttributeMapping = new HashMap < > ( ) ; resultAttributeMapping . put ( USERNAME_COLUMN_NAME , Stream . of ( USERNAME_ATTRIBUTE , UID_ATTRIBUTE , USER_LOGIN_ID_ATTRIBUTE ) . collect ( Collectors . toSet ( ) ) ) ; rslt . setResultAttributeMapping ( resultAttributeMapping ) ; return rslt ; }
Looks in the base UP_USER table doesn t find attributes but will ensure a result if it the user exists in the portal database and is searched for by username results are cached by the outer caching DAO .
34,984
static void addParameterChild ( Element node , String name , String value ) { if ( node != null ) { Document doc = node . getOwnerDocument ( ) ; Element parm = doc . createElement ( Constants . ELM_PARAMETER ) ; parm . setAttribute ( Constants . ATT_NAME , name ) ; parm . setAttribute ( Constants . ATT_VALUE , value ) ; parm . setAttribute ( Constants . ATT_OVERRIDE , Constants . CAN_OVERRIDE ) ; node . appendChild ( parm ) ; } }
Performs parameter child element creation in the passed in Element .
34,985
protected final < T > TypedQuery < T > createQuery ( CriteriaQuery < T > criteriaQuery ) { return this . getEntityManager ( ) . createQuery ( criteriaQuery ) ; }
Common logic for creating and configuring JPA queries
34,986
protected final < T > TypedQuery < T > createCachedQuery ( CriteriaQuery < T > criteriaQuery ) { final TypedQuery < T > query = this . getEntityManager ( ) . createQuery ( criteriaQuery ) ; final String cacheRegion = getCacheRegionName ( criteriaQuery ) ; query . setHint ( "org.hibernate.cacheable" , true ) ; query . setHint ( "org.hibernate.cacheRegion" , cacheRegion ) ; return query ; }
Important common logic for creating and configuring JPA queries cached in EhCache . This step is important for the sake of scalability .
34,987
protected final < T > String getCacheRegionName ( CriteriaQuery < T > criteriaQuery ) { final Set < Root < ? > > roots = criteriaQuery . getRoots ( ) ; final Class < ? > cacheRegionType = roots . iterator ( ) . next ( ) . getJavaType ( ) ; final String cacheRegion = cacheRegionType . getName ( ) + QUERY_SUFFIX ; if ( roots . size ( ) > 1 ) { logger . warn ( "Query " + criteriaQuery + " in " + this . getClass ( ) + " has " + roots . size ( ) + " roots. The first will be used to generated the cache region name: " + cacheRegion ) ; } return cacheRegion ; }
Creates the cache region name for the criteria query
34,988
protected Map session ( ) { Map session ; try { SimpleHash sessionHash = ( SimpleHash ) get ( "session" ) ; session = sessionHash . toMap ( ) ; } catch ( Exception e ) { logger ( ) . warn ( "failed to get a session map in context, returning session without data!!!" , e ) ; session = new HashMap ( ) ; } return Collections . unmodifiableMap ( session ) ; }
Returns reference to a current session map .
34,989
protected RenderBuilder render ( ) { String template = Router . getControllerPath ( getClass ( ) ) + "/" + RequestContext . getRoute ( ) . getActionName ( ) ; return super . render ( template , values ( ) ) ; }
Use this method in order to override a layout status code and content type .
34,990
public boolean actionSupportsHttpMethod ( String actionMethodName , HttpMethod httpMethod ) { if ( restful ( ) ) { return restfulActionSupportsHttpMethod ( actionMethodName , httpMethod ) || standardActionSupportsHttpMethod ( actionMethodName , httpMethod ) ; } else { return standardActionSupportsHttpMethod ( actionMethodName , httpMethod ) ; } }
Checks if the action supports an HTTP method according to its configuration .
34,991
protected Route recognize ( String uri , HttpMethod httpMethod ) throws ClassLoadException { if ( uri . endsWith ( "/" ) && uri . length ( ) > 1 ) { uri = uri . substring ( 0 , uri . length ( ) - 1 ) ; } ControllerPath controllerPath = getControllerPath ( uri ) ; Route route = matchCustom ( uri , controllerPath , httpMethod ) ; if ( route == null ) { if ( controllerPath . getControllerName ( ) == null ) { return null ; } String controllerClassName = getControllerClassName ( controllerPath ) ; AppController controller = createControllerInstance ( controllerClassName ) ; if ( uri . equals ( "/" ) && rootControllerName != null ) { route = new Route ( controller , "index" , httpMethod ) ; } else { route = controller . restful ( ) ? matchRestful ( uri , controllerPath , httpMethod , controller ) : matchStandard ( uri , controllerPath , controller , httpMethod ) ; } } if ( route != null ) { route . setIgnoreSpecs ( ignoreSpecs ) ; } else { logger . error ( "Failed to recognize URL: '" + uri + "'" ) ; throw new RouteException ( "Failed to map resource to URI: " + uri ) ; } return route ; }
This is a main method for recognizing a route to a controller ; used when a request is received .
34,992
private Route matchStandard ( String uri , ControllerPath controllerPathObject , AppController controller , HttpMethod method ) { String controllerPath = ( controllerPathObject . getControllerPackage ( ) != null ? "/" + controllerPathObject . getControllerPackage ( ) . replace ( "." , "/" ) : "" ) + "/" + controllerPathObject . getControllerName ( ) ; String theUri = uri . endsWith ( "/" ) ? uri . substring ( 0 , uri . length ( ) - 1 ) : uri ; if ( controllerPath . length ( ) == theUri . length ( ) ) { return new Route ( controller , "index" , method ) ; } String [ ] parts ; try { String tail = theUri . substring ( controllerPath . length ( ) + 1 ) ; parts = split ( tail , "/" ) ; } catch ( Exception e ) { throw new RouteException ( "Failed to parse route from: '" + uri + "'" , e ) ; } if ( parts . length == 1 ) { return new Route ( controller , parts [ 0 ] , method ) ; } if ( parts . length == 2 ) { return new Route ( controller , parts [ 0 ] , parts [ 1 ] , method ) ; } LOGGER . warn ( "Failed to find action for request: " + uri ) ; return null ; }
Will match a standard non - restful route .
34,993
protected static String findControllerNamePart ( String pack , String uri ) { String temp = uri . startsWith ( "/" ) ? uri . substring ( 1 ) : uri ; temp = temp . replace ( "/" , "." ) ; if ( temp . length ( ) > pack . length ( ) ) temp = temp . substring ( pack . length ( ) + 1 ) ; if ( temp . equals ( "" ) ) throw new ControllerException ( "You defined a controller package '" + pack + "', but did not specify controller name" ) ; return temp . split ( "\\." ) [ 0 ] ; }
Now that we know that this controller is under a package need to find the controller short name .
34,994
protected String findPackageSuffix ( String uri ) { String temp = uri . startsWith ( "/" ) ? uri . substring ( 1 ) : uri ; temp = temp . replace ( "." , "_" ) ; temp = temp . replace ( "/" , "." ) ; List < String > candidates = new ArrayList < > ( ) ; for ( String pack : Configuration . getControllerPackages ( ) ) { if ( temp . startsWith ( pack ) && ( temp . length ( ) == pack . length ( ) || temp . length ( ) > pack . length ( ) && temp . charAt ( pack . length ( ) ) == '.' ) ) { candidates . add ( pack ) ; } } int resultIndex = 0 ; int size = 0 ; for ( int i = 0 ; i < candidates . size ( ) ; i ++ ) { String candidate = candidates . get ( i ) ; if ( candidate . length ( ) > size ) { size = candidate . length ( ) ; resultIndex = i ; } } return ! candidates . isEmpty ( ) ? candidates . get ( resultIndex ) : null ; }
Finds a part of a package name which can be found in between app . controllers and short name of class .
34,995
public < T extends AppController > RouteBuilder to ( Class < T > type ) { boolean hasControllerSegment = false ; for ( Segment segment : segments ) { hasControllerSegment = segment . controller ; } if ( type != null && hasControllerSegment ) { throw new IllegalArgumentException ( "Cannot combine {controller} segment and .to(\"...\") method. Failed route: " + routeConfig ) ; } this . type = type ; return this ; }
Allows to wire a route to a controller .
34,996
public RouteBuilder action ( String action ) { boolean hasActionSegment = false ; for ( Segment segment : segments ) { hasActionSegment = segment . action ; } if ( action != null && hasActionSegment ) { throw new IllegalArgumentException ( "Cannot combine {action} segment and .action(\"...\") method. Failed route: " + routeConfig ) ; } this . actionName = action ; return this ; }
Name of action to which a route is mapped .
34,997
public RouteBuilder get ( ) { if ( ! methods . contains ( HttpMethod . GET ) ) { methods . add ( HttpMethod . GET ) ; } return this ; }
Specifies that this route is mapped to HTTP GET method .
34,998
public RouteBuilder post ( ) { if ( ! methods . contains ( HttpMethod . POST ) ) { methods . add ( HttpMethod . POST ) ; } return this ; }
Specifies that this route is mapped to HTTP POST method .
34,999
public RouteBuilder options ( ) { if ( ! methods . contains ( HttpMethod . OPTIONS ) ) { methods . add ( HttpMethod . OPTIONS ) ; } return this ; }
Specifies that this route is mapped to HTTP OPTIONS method .