org.sakaiproject.entitybroker
Interface DeveloperHelperService


public interface DeveloperHelperService

Includes 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
static String ADMIN_USER_ID
           
static String ADMIN_USER_REF
           
static 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)
static 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)
static String SETTING_SERVER_ID
          String type: gets the unique id of this server (safe for clustering if used)
static String SETTING_SERVER_NAME
          String type: gets the printable name of this server
static String SETTING_SERVER_URL
          String type: gets the URL to this server
 
Method Summary
<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.
<T> T
convert(Object object, Class<T> type)
          Converts an object to any other object if possible
 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
 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 into populate(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 the convert(Object, Class) method is recommended
Current formats supported: JSON, XML
 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
 boolean entityExists(String reference)
          Convenience method from EntityBroker
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).
 Object fetchEntity(String reference)
          Convenience method from EntityBroker
Fetches a concrete object representing this entity reference; either one from the Resolvable capability if implemented by the responsible EntityProvider, or else from the underlying legacy Sakai entity system
 void fireEvent(String eventName, String reference)
          Convenience method from EntityBroker
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> T
getConfigurationSetting(String settingName, T defaultValue)
          Retrieves settings from the configuration service (sakai.properties)
 Locale getCurrentLocale()
           
 String getCurrentLocationId()
           
 String getCurrentLocationReference()
           
 String getCurrentToolReference()
           
 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 use getCurrentUserReference() instead
 String getCurrentUserReference()
          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 permissions
 String getEntityURL(String reference, String viewKey, String extension)
          Convenience method from EntityBroker
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)
 String getLocationIdFromRef(String locationReference)
           
 String getLocationReferenceURL(String locationReference)
           
 String getMessage(String prefix, String messageKey)
          Gets messages from the entity message bundles (the entities which implement Describeable or a sub interface),
 String getPortalURL()
           
 String getServerURL()
           
 String getStartingLocationReference()
           
 SakaiToolData getToolData(String toolRegistrationId, String locationReference)
           
 String getToolIdFromToolRef(String toolReference)
          Translate a tool entity reference into a tool Id
 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
 String getUserHomeLocationReference(String userReference)
          Get the entity reference of the location of a user's workspace/homespace
 String getUserHomeLocationURL(String userReference)
           
 String getUserIdFromRef(String userReference)
          Translate the user entity reference into a userId
 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
 String getUserRefFromUserEid(String userEid)
          Translate the user EID (username/loginname typicaly) into a user reference
 String getUserRefFromUserId(String userId)
          Translate the userId into a user entity reference, (may or may not validate the userId first)
 boolean isEntityRequestInternal(String reference)
          Checks to see if the current entity request is internal (and therefore can optionally bypass some or all security), see the RequestStorage (from RequestStorable capability) for more info
 boolean isUserAdmin(String userReference)
          Check if this user has super admin level access (permissions)
 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
 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.
 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
 String restoreCurrentUser()
          Restores the current user to the one from before setCurrentUser(String) was called or does nothing if there was no previous user stored
 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
 

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 from EntityBroker
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 no EntityProvider for the reference is found which implements CoreEntityProvider, this method will return true by 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 from EntityBroker
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 id
viewKey - the specific view type to get the URL for, use the VIEW_* constants from EntityView (e.g. EntityView.VIEW_LIST), can be null to determine the key automatically
extension - the optional extension to add to the end which defines the expected data which is returned, use constants in Formats (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 from EntityBroker
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 empty
reference - 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 from EntityBroker
Fetches a concrete object representing this entity reference; either one from the Resolvable capability if implemented by the responsible EntityProvider, 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 implement Describeable or a sub interface),

Parameters:
prefix - the string which represents a type of entity handled by an entity provider
messageKey - 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.g SETTING_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 use getCurrentUserReference() 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 before setCurrentUser(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 use getCurrentLocationReference() 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 constant
reference - 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 the RequestStorage (from RequestStorable capability) 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 DynaBeans
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 forth
propertiesToSkip - 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 from
destination - 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 forth
fieldNamesToSkip - 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 object
properties - 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 object
type - 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 encode
format - the format to use for output (from Formats)
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 encoded
IllegalArgumentException - 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 into populate(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 the convert(Object, Class) method is recommended
Current formats supported: JSON, XML

Parameters:
data - encoded data
format - the format of the encoded data (from Formats)
Returns:
a map containing all the data derived from the encoded data
Throws:
UnsupportedOperationException - if the data cannot be decoded
IllegalArgumentException - if the data cannot be decoded because there is no decoder for that format


Copyright © 2007-2013 Sakai Project. All Rights Reserved.