Package org.sakaiproject.entitybroker
Interface DeveloperHelperService
-
public interface DeveloperHelperServiceIncludes methods which are likely to be helpful to developers who are implementing entity providers in Sakai and working with references- Author:
- Aaron Zeckoski (aaron@caret.cam.ac.uk)
-
-
Field Summary
Fields Modifier and Type Field Description static StringADMIN_USER_IDstatic StringADMIN_USER_REFstatic StringSETTING_AUTO_DDLBoolean type: if true then there will be data preloads and DDL creation, if false then data preloads are disabled (and will cause exceptions if preload data is missing)static StringSETTING_PORTAL_URLString type: gets the URL to the portal on this server (or just returns the server URL if no portal in use)static StringSETTING_SERVER_IDString type: gets the unique id of this server (safe for clustering if used)static StringSETTING_SERVER_NAMEString type: gets the printable name of this serverstatic StringSETTING_SERVER_URLString type: gets the URL to this server
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description <T> TcloneBean(T bean, int maxDepth, String[] propertiesToSkip)Deep clone a bean (object) and all the values in it into a brand new object of the same type, this will traverse the bean and will make new objects for all non-null values contained in the object, the level indicates the number of contained objects to traverse and clone, setting this to zero will only clone basic type values in the bean, setting this to one will clone basic fields, references, and collections in the bean, etc.
This is mostly useful for making a copy of a hibernate object so it will no longer be the persistent object with the hibernate proxies and lazy loading<T> Tconvert(Object object, Class<T> type)Converts an object to any other object if possiblevoidcopyBean(Object orig, Object dest, int maxDepth, String[] fieldNamesToSkip, boolean ignoreNulls)Deep copies one bean (object) into another, this is primarily for copying between identical types of objects but it can also handle copying between objects which are quite different, this does not just do a reference copy of the values but actually creates new objects in the current classloader and traverses through all properties of the object to make a complete deep copyMap<String,Object>decodeData(String data, String format)Decode a string of a specified format into a java map of simple objects
Returned map can be fed intopopulate(Object, Map)if you want to convert it into a known object type
Types are likely to require conversion as guesses are made about the right formats, use of theconvert(Object, Class)method is recommended
Current formats supported: JSON, XMLStringencodeData(Object data, String format, String name, Map<String,Object> properties)Encode data into a given format, can handle any java object, note that unsupported formats and invalid data will result in an exception
Current formats supported: JSON, XML, HTMLbooleanentityExists(String reference)Convenience method fromEntityBroker
Check if an entity exists by the globally unique reference string, (the global reference string will consist of the entity prefix and any local ID).ObjectfetchEntity(String reference)Convenience method fromEntityBroker
Fetches a concrete object representing this entity reference; either one from theResolvablecapability if implemented by the responsibleEntityProvider, or else from the underlying legacy Sakai entity systemvoidfireEvent(String eventName, String reference)Convenience method fromEntityBroker
Fire an event to Sakai with the specified name, targetted at the supplied reference, which should be a reference to an existing entity managed by this broker
NOTE: This will allow events to be fired for references without a broker or invalid references<T> TgetConfigurationSetting(String settingName, T defaultValue)Retrieves settings from the configuration service (sakai.properties)LocalegetCurrentLocale()StringgetCurrentLocationId()StringgetCurrentLocationReference()StringgetCurrentToolReference()StringgetCurrentUserId()Get the user entity id (e.g. not eid or username) of the current user if there is one, this is not equivalent to the current user reference
recommend you usegetCurrentUserReference()insteadStringgetCurrentUserReference()Get the user entity reference (e.g.Set<String>getEntityReferencesForUserAndPermission(String userReference, String permission)Find the entity references which a user has a specific permission in, this is most commonly used to get the list of sites which a user has a permission in but it will work for any entity type which uses Sakai permissionsStringgetEntityURL(String reference, String viewKey, String extension)Convenience method fromEntityBroker
Get the full absolute URL to the entity view defined by these params, this will fail-safe to a direct URL to an entity space URL if that is all that is available, this will use the default entity URL template associated with the viewKey and include an optional extension if specified (these will be inferred if they are missing)StringgetLocationIdFromRef(String locationReference)StringgetLocationReferenceURL(String locationReference)StringgetMessage(String prefix, String messageKey)Gets messages from the entity message bundles (the entities which implementDescribeableor a sub interface),StringgetPortalURL()StringgetServerURL()StringgetStartingLocationReference()SakaiToolDatagetToolData(String toolRegistrationId, String locationReference)StringgetToolIdFromToolRef(String toolReference)Translate a tool entity reference into a tool IdStringgetToolViewURL(String toolRegistrationId, String localView, Map<String,String> parameters, String locationReference)Generate a URL to a tool which will work from anywhere and can carry parameters with it
NOTE: you should set the A tag target="_top" if you are inside an existing tool iFrameStringgetUserHomeLocationReference(String userReference)Get the entity reference of the location of a user's workspace/homespaceStringgetUserHomeLocationURL(String userReference)StringgetUserIdFromRef(String userReference)Translate the user entity reference into a userIdSet<String>getUserReferencesForEntityReference(String reference, String permission)Get the user references which have the given permission in the given entity reference, this is most commonly used to get the users which have a permission in a site but it should work for any entity type which uses Sakai permissionsStringgetUserRefFromUserEid(String userEid)Translate the user EID (username/loginname typicaly) into a user referenceStringgetUserRefFromUserId(String userId)Translate the userId into a user entity reference, (may or may not validate the userId first)booleanisEntityRequestInternal(String reference)Checks to see if the current entity request is internal (and therefore can optionally bypass some or all security), see theRequestStorage(fromRequestStorablecapability) for more infobooleanisUserAdmin(String userReference)Check if this user has super admin level access (permissions)booleanisUserAllowedInEntityReference(String userReference, String permission, String reference)Check if a user has a specified permission for the entity reference, primarily a convenience method for checking location permissionsList<String>populate(Object object, Map<String,Object> properties)Populates an object with the values in the properties map, this will not fail if the fieldName in the map is not a property on the object or the fieldName cannot be written to with the value in the object.voidregisterPermission(String permission)Register a permission key as a valid permission for use in Sakai, permissions will not appear unless they are registered each time Sakai starts up so you should run this in your service init methodStringrestoreCurrentUser()Restores the current user to the one from beforesetCurrentUser(String)was called or does nothing if there was no previous user storedStringsetCurrentUser(String userReference)Set the current user to match the supplied user reference, the current user reference will be stored and returned (may be null), this is primarily useful when you need to switch a user to an admin or to some other user temporarily OR there is no current user but something you are calling expects to find one
-
-
-
Field Detail
-
SETTING_SERVER_NAME
static final String SETTING_SERVER_NAME
String type: gets the printable name of this server- See Also:
- Constant Field Values
-
SETTING_SERVER_ID
static final String SETTING_SERVER_ID
String type: gets the unique id of this server (safe for clustering if used)- See Also:
- Constant Field Values
-
SETTING_SERVER_URL
static final String SETTING_SERVER_URL
String type: gets the URL to this server- See Also:
- Constant Field Values
-
SETTING_PORTAL_URL
static final String SETTING_PORTAL_URL
String type: gets the URL to the portal on this server (or just returns the server URL if no portal in use)- See Also:
- Constant Field Values
-
SETTING_AUTO_DDL
static final String SETTING_AUTO_DDL
Boolean type: if true then there will be data preloads and DDL creation, if false then data preloads are disabled (and will cause exceptions if preload data is missing)- See Also:
- Constant Field Values
-
ADMIN_USER_ID
static final String ADMIN_USER_ID
- See Also:
- Constant Field Values
-
ADMIN_USER_REF
static final String ADMIN_USER_REF
- See Also:
- Constant Field Values
-
-
Method Detail
-
entityExists
boolean entityExists(String reference)
Convenience method fromEntityBroker
Check if an entity exists by the globally unique reference string, (the global reference string will consist of the entity prefix and any local ID). If noEntityProviderfor the reference is found which implementsCoreEntityProvider, this method will returntrueby default, in other words, this cannot determine if a legacy entity exists, only a new entity- Parameters:
reference- a globally unique reference to an entity, consists of the entity prefix and optional segments (normally the id at least)- Returns:
- true if the entity exists, false otherwise
-
getEntityURL
String getEntityURL(String reference, String viewKey, String extension)
Convenience method fromEntityBroker
Get the full absolute URL to the entity view defined by these params, this will fail-safe to a direct URL to an entity space URL if that is all that is available, this will use the default entity URL template associated with the viewKey and include an optional extension if specified (these will be inferred if they are missing)- Parameters:
reference- a globally unique reference to an entity, consists of the entity prefix and optionally the local idviewKey- the specific view type to get the URL for, use the VIEW_* constants fromEntityView(e.g.EntityView.VIEW_LIST), can be null to determine the key automaticallyextension- the optional extension to add to the end which defines the expected data which is returned, use constants inFormats(e.g.Formats.XML), can be null to use no extension, default is assumed to be html if none is set- Returns:
- the full URL string to a specific entity or space, (e.g. http://server/direct/prefix/id)
-
fireEvent
void fireEvent(String eventName, String reference)
Convenience method fromEntityBroker
Fire an event to Sakai with the specified name, targetted at the supplied reference, which should be a reference to an existing entity managed by this broker
NOTE: This will allow events to be fired for references without a broker or invalid references- Parameters:
eventName- a string which represents the name of the event (e.g. announcement.create), cannot be null or emptyreference- a globally unique reference to an entity, consists of the entity prefix and optional segments, cannot be null or empty
-
fetchEntity
Object fetchEntity(String reference)
Convenience method fromEntityBroker
Fetches a concrete object representing this entity reference; either one from theResolvablecapability if implemented by the responsibleEntityProvider, or else from the underlying legacy Sakai entity system- Parameters:
reference- a globally unique reference to an entity, consists of the entity prefix and optional segments- Returns:
- an object which represents the entity or null if none can be found
-
getMessage
String getMessage(String prefix, String messageKey)
Gets messages from the entity message bundles (the entities which implementDescribeableor a sub interface),- Parameters:
prefix- the string which represents a type of entity handled by an entity providermessageKey- the message bundle property key- Returns:
- the property value string OR null if none found
-
getConfigurationSetting
<T> T getConfigurationSetting(String settingName, T defaultValue)
Retrieves settings from the configuration service (sakai.properties)- Parameters:
settingName- the name of the setting to retrieve, Should be a string name: e.g. auto.ddl, mystuff.config, etc. OR one of the SETTING constants (e.gSETTING_AUTO_DDL)defaultValue- a specified default value to return if this setting cannot be found, NOTE: You can set the default value to null but you must specify the class type in parens- Returns:
- the value of the configuration setting OR the default value if none can be found
-
getCurrentUserReference
String getCurrentUserReference()
Get the user entity reference (e.g. /user/{userId} - not id, eid, or username) of the current user if there is one, this is not equivalent to the current user id- Returns:
- the user entity reference (e.g. /user/{userId} - not id, eid, or username) OR null if none
-
getCurrentUserId
String getCurrentUserId()
Get the user entity id (e.g. not eid or username) of the current user if there is one, this is not equivalent to the current user reference
recommend you usegetCurrentUserReference()instead- Returns:
- the user id OR null if there is no current user (or the user is anonymous)
-
getUserIdFromRef
String getUserIdFromRef(String userReference)
Translate the user entity reference into a userId- Parameters:
userReference- the user entity reference (e.g. /user/{userId} - not id, eid, or username)- Returns:
- the userId as extracted from this user entity reference (needed for some Sakai API operations)
-
getUserRefFromUserId
String getUserRefFromUserId(String userId)
Translate the userId into a user entity reference, (may or may not validate the userId first)- Parameters:
userId- the internal user Id (not the eid or username)- Returns:
- the user entity reference (e.g. /user/{userId})
-
getUserRefFromUserEid
String getUserRefFromUserEid(String userEid)
Translate the user EID (username/loginname typicaly) into a user reference- Parameters:
userEid- the external user Id (probably the loginname or username)- Returns:
- the user entity reference (e.g. /user/{userId}) OR null if the eid is invalid
-
getCurrentLocale
Locale getCurrentLocale()
- Returns:
- the Locale for the current user or the system set locale
-
setCurrentUser
String setCurrentUser(String userReference)
Set the current user to match the supplied user reference, the current user reference will be stored and returned (may be null), this is primarily useful when you need to switch a user to an admin or to some other user temporarily OR there is no current user but something you are calling expects to find one- Parameters:
userReference- the user entity reference (e.g. /user/{userId} - not id, eid, or username)- Returns:
- the previous current user entity reference
- Throws:
IllegalArgumentException- if the userReference is invalid
-
restoreCurrentUser
String restoreCurrentUser()
Restores the current user to the one from beforesetCurrentUser(String)was called or does nothing if there was no previous user stored- Returns:
- the restored current user reference OR null if there was no user to restore
-
getCurrentLocationReference
String getCurrentLocationReference()
- Returns:
- the entity reference (/site/{siteId}) of the current location for the current session (represents the current site/group of the current user in the system)
-
getCurrentLocationId
String getCurrentLocationId()
- Returns:
- the entity id of the current location for the current session
(represents the current site/group of the current user in the system)
recommend you usegetCurrentLocationReference()instead
-
getLocationIdFromRef
String getLocationIdFromRef(String locationReference)
- Parameters:
locationReference- the location reference (/site/{siteId})- Returns:
- the location id
-
getStartingLocationReference
String getStartingLocationReference()
- Returns:
- the entity reference of the location which is the main starting point for the system (in Sakai this is probably the reference to the gateway site)
-
getUserHomeLocationReference
String getUserHomeLocationReference(String userReference)
Get the entity reference of the location of a user's workspace/homespace- Parameters:
userReference- the user entity reference (e.g. /user/{userId} - not id, eid, or username)- Returns:
- the entity reference of the location OR null if it cannot be generated
-
getCurrentToolReference
String getCurrentToolReference()
- Returns:
- the entity reference of the current active tool for the current session (represents the tool that is currently being used by the current user in the system)
-
getToolIdFromToolRef
String getToolIdFromToolRef(String toolReference)
Translate a tool entity reference into a tool Id- Parameters:
toolReference- the entity reference of a tool (e.g. /tool/{toolId})- Returns:
- the toolId (needed for other Sakai API operations)
-
getToolData
SakaiToolData getToolData(String toolRegistrationId, String locationReference)
- Parameters:
toolRegistrationId- this is the id string from the Sakai tool registration XML file (i.e. sakai.mytool.xml) and will probably look something like "sakai.mytool"locationReference- (optional) an entity reference to a location (e.g. /site/siteId) OR null if it should be for the current site- Returns:
- an object which contains data about a tool
- Throws:
IllegalArgumentException- if any parameters are invalid or a tool with this toolRegistrationId cannot be located in the given location
-
isUserAdmin
boolean isUserAdmin(String userReference)
Check if this user has super admin level access (permissions)- Parameters:
userReference- the user entity reference (e.g. /user/{userId} - not id, eid, or username)- Returns:
- true if the user has admin access, false otherwise
-
isUserAllowedInEntityReference
boolean isUserAllowedInEntityReference(String userReference, String permission, String reference)
Check if a user has a specified permission for the entity reference, primarily a convenience method for checking location permissions- Parameters:
userReference- the user entity reference (e.g. /user/{userId} - not id, eid, or username)permission- a permission string constantreference- a globally unique reference to an entity, consists of the entity prefix and optional segments (normally the id at least)- Returns:
- true if allowed, false otherwise
-
getEntityReferencesForUserAndPermission
Set<String> getEntityReferencesForUserAndPermission(String userReference, String permission)
Find the entity references which a user has a specific permission in, this is most commonly used to get the list of sites which a user has a permission in but it will work for any entity type which uses Sakai permissions- Parameters:
userReference- the user entity reference (e.g. /user/{userId} - not id, eid, or username)permission- a permission string constant- Returns:
- a set of entity references - a globally unique reference to an entity, consists of the entity prefix and optional segments (normally the id at least)
-
getUserReferencesForEntityReference
Set<String> getUserReferencesForEntityReference(String reference, String permission)
Get the user references which have the given permission in the given entity reference, this is most commonly used to get the users which have a permission in a site but it should work for any entity type which uses Sakai permissions- Parameters:
reference- a globally unique reference to an entity, consists of the entity prefix and optional segments (normally the id at least)permission- a permission string constant- Returns:
- a set of user entity references (e.g. /user/{userId} - not id, eid, or username)
-
registerPermission
void registerPermission(String permission)
Register a permission key as a valid permission for use in Sakai, permissions will not appear unless they are registered each time Sakai starts up so you should run this in your service init method- Parameters:
permission- the permission key (e.g.: toolname.read.all, toolname.delete.owned)
-
isEntityRequestInternal
boolean isEntityRequestInternal(String reference)
Checks to see if the current entity request is internal (and therefore can optionally bypass some or all security), see theRequestStorage(fromRequestStorablecapability) for more info- Parameters:
reference- a globally unique reference to an entity, consists of the entity prefix and optional segments (normally the id at least)- Returns:
- true if the current request is internal OR false if external or REST based
-
getPortalURL
String getPortalURL()
- Returns:
- the full portal URL as Sakai understands it (e.g. http://server:port/portal)
-
getServerURL
String getServerURL()
- Returns:
- the full server base URL (e.g. http://server:port)
-
getLocationReferenceURL
String getLocationReferenceURL(String locationReference)
- Parameters:
locationReference- an entity reference to a location (e.g. /site/siteId)- Returns:
- the full URL to a location (e.g. http://server:port/portal/site/siteId)
- Throws:
IllegalArgumentException- if this reference does not appear to be valid
-
getUserHomeLocationURL
String getUserHomeLocationURL(String userReference)
- Parameters:
userReference- the user entity reference (e.g. /user/{userId} - not id, eid, or username)- Returns:
- the full URL to a user's workspace/homespace (e.g. http://server:port/portal/~someuser)
- Throws:
IllegalArgumentException- if this user reference does not appear to be valid
-
getToolViewURL
String getToolViewURL(String toolRegistrationId, String localView, Map<String,String> parameters, String locationReference)
Generate a URL to a tool which will work from anywhere and can carry parameters with it
NOTE: you should set the A tag target="_top" if you are inside an existing tool iFrame- Parameters:
toolRegistrationId- this is the id string from the Sakai tool registration XML file (i.e. sakai.mytool.xml) and will probably look something like "sakai.mytool"localView- (optional) the local URL of the view/page to navigate to within the tool OR null to go to the starting view/page, examples: /view, /page.jsp, /path/to/someview, make sure you include the leading slash ("/")parameters- (optional) a map of parameters to include in the URL and send along to the tool (these will be turned into GET parameters in the URL), the map should contain parameterName -> parameterValue (e.g. "thing" -> "value")locationReference- (optional) an entity reference to a location (e.g. /site/siteId) OR null if it should be for the current site- Returns:
- a full URL to a tool (e.g. http://server:port/portal/site/siteId/page/pageId?toolstate-toolpid=/view?thing=value)
- Throws:
IllegalArgumentException- if any parameters are invalid or a tool with this toolRegistrationId cannot be located in the given location
-
cloneBean
<T> T cloneBean(T bean, int maxDepth, String[] propertiesToSkip)Deep clone a bean (object) and all the values in it into a brand new object of the same type, this will traverse the bean and will make new objects for all non-null values contained in the object, the level indicates the number of contained objects to traverse and clone, setting this to zero will only clone basic type values in the bean, setting this to one will clone basic fields, references, and collections in the bean, etc.
This is mostly useful for making a copy of a hibernate object so it will no longer be the persistent object with the hibernate proxies and lazy loading- Type Parameters:
T-- Parameters:
bean- any java bean, this can also be a list, map, array, or any simple object, it does not have to be a custom object or even a java bean, also works with apache beanutils DynaBeansmaxDepth- the number of objects to follow when traveling through the object and copying the values from it, 0 means to only copy the simple values in the object, any objects will be ignored and will end up as nulls, 1 means to follow the first objects found and copy all of their simple values as well, and so forthpropertiesToSkip- the names of properties to skip while cloning this object, this only has an effect on the bottom level of the object, any properties found on child objects will always be copied (if the maxDepth allows)- Returns:
- the clone of the bean
- Throws:
IllegalArgumentException- if there is a failure cloning the bean
-
copyBean
void copyBean(Object orig, Object dest, int maxDepth, String[] fieldNamesToSkip, boolean ignoreNulls)
Deep copies one bean (object) into another, this is primarily for copying between identical types of objects but it can also handle copying between objects which are quite different, this does not just do a reference copy of the values but actually creates new objects in the current classloader and traverses through all properties of the object to make a complete deep copy- Parameters:
original- the original object to copy fromdestination- the object to copy the values to (must have the same fields with the same types)maxDepth- the number of objects to follow when traveling through the object and copying the values from it, 0 means to only copy the simple values in the object, any objects will be ignored and will end up as nulls, 1 means to follow the first objects found and copy all of their simple values as well, and so forthfieldNamesToSkip- the names of fields to skip while cloning this object, this only has an effect on the bottom level of the object, any fields found on child objects will always be copied (if the maxDepth allows)ignoreNulls- if true then nulls are not copied and the destination retains the value it has, if false then nulls are copied and the destination value will become a null if the original value is a null- Throws:
IllegalArgumentException- if the copy cannot be completed because the objects to copy do not have matching fields or types
-
populate
List<String> populate(Object object, Map<String,Object> properties)
Populates an object with the values in the properties map, this will not fail if the fieldName in the map is not a property on the object or the fieldName cannot be written to with the value in the object. This will attempt to convert the provided object values into the right values to place in the object
NOTE: simple types like numbers and strings can almost always be converted from just about anything though they will probably end up as 0 or ""
Setting fields supports simple, nested, indexed, and mapped values:
Simple: Get/set a field in a bean (or map), Example: "title", "id"
Nested: Get/set a field in a bean which is contained in another bean, Example: "someBean.title", "someBean.id"
Indexed: Get/set a list/array item by index in a bean, Example: "myList[1]", "anArray[2]"
Mapped: Get/set a map entry by key in a bean, Example: "myMap(key)", "someMap(thing)"- Parameters:
object- any objectproperties- a map of fieldNames -> Object- Returns:
- the list of fieldNames which were successfully written to the object
- Throws:
IllegalArgumentException- if the arguments are invalid
-
convert
<T> T convert(Object object, Class<T> type)
Converts an object to any other object if possible- Type Parameters:
T-- Parameters:
object- any objecttype- any class type that you want to try to convert the object to- Returns:
- the converted value (allows null to pass through except in the case of primitives which become the primitive default)
- Throws:
UnsupportedOperationException- if the conversion cannot be completed
-
encodeData
String encodeData(Object data, String format, String name, Map<String,Object> properties)
Encode data into a given format, can handle any java object, note that unsupported formats and invalid data will result in an exception
Current formats supported: JSON, XML, HTML- Parameters:
data- the data to encodeformat- the format to use for output (fromFormats)name- (optional) the name to use for the encoded data (e.g. root node for XML)properties- (optional) extra properties to add into the encoding, ignored if encoded object is not a map or bean- Returns:
- the encoded string in the requested format
- Throws:
UnsupportedOperationException- if the data cannot be encodedIllegalArgumentException- if the format requested cannot be encoded because there is no encoder
-
decodeData
Map<String,Object> decodeData(String data, String format)
Decode a string of a specified format into a java map of simple objects
Returned map can be fed intopopulate(Object, Map)if you want to convert it into a known object type
Types are likely to require conversion as guesses are made about the right formats, use of theconvert(Object, Class)method is recommended
Current formats supported: JSON, XML- Parameters:
data- encoded dataformat- the format of the encoded data (fromFormats)- Returns:
- a map containing all the data derived from the encoded data
- Throws:
UnsupportedOperationException- if the data cannot be decodedIllegalArgumentException- if the data cannot be decoded because there is no decoder for that format
-
-