Additional web services for Sakai
Additional web services for Sakai
I have written a number of additional web services for Sakai and they are included below. If you find these useful, please let me know!
Additional web services
These are web services I have written but are not yet in any official Sakai release
#getResourcesForSite - Gets an XML doc of the resources in a site, with URL, type etc.
#archiveSite - Archives a site
Available in 2.7
These services will be part of the future 2.7 release
#getGroupsInSite - Gets XML doc of all groups in a site, incl id, title and description.
#getUserEmail - Get's the email address for a given user (the original was session based, this is more flexible)
#getAllUsers - Gets a list of all user accounts. You can restrict what is returned, see the doc.
#addNewToolToAllWorkspaces - Adds a tool to all My Workspace sites
#copyRole - Copies a role from one authzgroup (or site) to another. Useful for mass population/synchronisation of roles across sites.
#getUserType - Gets the type of a user's account
#getSessionForUser - Creates a session for a given user without knowing their password. Only admin can access this one (for security reasons)
Available since 2.6
These services are now part of the main Sakai web service set as of 2.6 and onwards
#getUsersInAuthzGroup - Gets XML doc of all users in an authzgroup (or site)
#getUsersInAuthzGroupWithRole - Gets XML doc of all users in an authzgroup (or site) with the given role(s), incl username, displayname, role.
#removeMemberFromSite - Remove an individual member from a site (similar to removeMemberFromAuthzGroup in the original SakaiScript, but acts on Site rather than AuthzGroup)
#getSiteTitle - Returns title of a site.
#getSiteDescription - Returns description of a site.
#getSiteSkin - Returns the skin of a site.
#isSiteJoinable - Returns if site is joinable or not
#checkForUserInAuthzGroup - Checks if a user exists in an authzgroup (or site)
#changeSiteTitle - Modifies a site's title
#changeSiteSkin - Modifies a site's skin
#changeSiteJoinable - Modifies a site's joinable status
#changeSiteIconUrl - Modifies a site's iconurl
#changeSiteDescription - Modifies a site's description
#getSiteProperty - Get a custom property of a site
#setSiteProperty - Set a custom property for a site
#removeSiteProperty - Remove a custom property for a site
#checkForAuthzGroup - Check if a given authzgroup exists
#checkForRoleInAuthzGroup - Check if a role exists in a given authzgroup
#getUserDisplayName - Gets the displayname of a given user (the original was session based, this is more flexible)
#searchForUsers - Search for users that meet the given criteria, returns xml
Gradebook services
#SakaiGradebook the beginning of a Gradebook web service set for 2.4.x and beyond. The existing set of services used deprecated API calls so this has been rewritten.
Deprecated web services
These are some service I have written which I no longer use or maintain, but kept here for reference
#addMembersToSiteFromXML - Processes an XML fragment (see method for schema) and adds the users to a site
#removeMembersFromSiteFromXML - Processes an XML fragment (see method for schema) and removes users from a site
Additional web services
//IN PROGRESS //when finished will return an xml doc with urls etc of the resources in a given site //based on the work by Mark Norton and David Horwitz //requires following additional imports import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.content.api.ContentCollection; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentEntity; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; public String getResourcesForSite(String sessionid, String siteid) throws AxisFault { Session s = establishSession(sessionid); try { //check valid siteid was given //get the collectionid String collectionId = ""; ContentHostingService chs = new ContentHostingService(); collectionId = chs.getSiteCollection(siteid); //get the collection ContentCollection collection = chs.getCollection(collectionId); //get the list of entities in this collection List entities = collection.getMemberResources(); //start xml doc Document dom = Xml.createDocument(); Node list = dom.createElement("list"); dom.appendChild(list); //iterate over entities list and create xml object for (Iterator i = entities.iterator(); i.hasNext();) { String id = null; // The resource or collection id. String name = null; // The display name. String type = null; // The resource type. String url = null; // The URL. ContentEntity entity = (ContentEntity)i.next(); // Get the entity id id = entity.getId(); // Get the entity display name. ResourceProperties props = entity.getProperties(); name = props.getProperty(ResourceProperties.PROP_DISPLAY_NAME); // Get the entity resource type. //if (entity.isCollection()) { //type = ContentHosting.RESOURCE_TYPE_COLLECTION; // } else { //type = ContentHosting.RESOURCE_TYPE_RESOURCE; //} type = "fixthis"; // Get the entity URL url = entity.getUrl(); // Create the resource element. Node item = dom.createElement("resource"); // Create the id child element. Node resId = dom.createElement("id"); resId.appendChild (dom.createTextNode(id)); // Create the name child element. Node resName = dom.createElement("name"); resName.appendChild( dom.createTextNode(name) ); // Create the type child element. Node resType = dom.createElement("type"); resType.appendChild(dom.createTextNode(type)); // Create the URL child element. Node resUrl = dom.createElement("url"); resUrl.appendChild(dom.createTextNode(url)); //append the child nodes to the item item.appendChild(resId); item.appendChild(resName); item.appendChild(resType); item.appendChild(resUrl); //append the wholte item node to the list list.appendChild(item); } return Xml.writeDocumentToString(dom); } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); //return "<exception/>"; } }
/** * Archive a site * * @param sessionid the id of a valid session, must be the admin user * @param siteid the id of the site to be archived * @return string of messages from archive output * * @throws AxisFault * */ public String archiveSite(String sessionid, String siteid) throws AxisFault { Session session = establishSession(sessionid); if(!session.getUserId().equals(UserDirectoryService.ADMIN_ID)) { LOG.warn("WS archiveSite(): Permission denied. Restricted to admin user."); throw new AxisFault("WS archiveSite(): Permission denied. Restricted to admin user."); } return ArchiveService.archive(siteid); }
Available in 2.7
/** * Get list of groups in a site * * @param sessionid the id of a valid session * @param siteid the id of the site to retrieve the group list for * @return xml doc of the list of groups, title and description * @throws AxisFault returns <exception /> string if exception encountered and logs it * */ public String getGroupsInSite(String sessionid, String siteid) throws AxisFault { Session s = establishSession(sessionid); try { Site site = SiteService.getSite(siteid); Document dom = Xml.createDocument(); Node list = dom.createElement("list"); dom.appendChild(list); for (Iterator iter = site.getGroups().iterator(); iter.hasNext();) { Group group = (Group) iter.next(); Node groupNode = dom.createElement("group"); Node groupId = dom.createElement("id"); groupId.appendChild(dom.createTextNode(group.getId())); Node groupTitle = dom.createElement("title"); groupTitle.appendChild(dom.createTextNode(group.getTitle())); Node groupDesc = dom.createElement("description"); groupDesc.appendChild(dom.createTextNode(group.getDescription())); groupNode.appendChild(groupId); groupNode.appendChild(groupTitle); groupNode.appendChild(groupDesc); list.appendChild(groupNode); } return Xml.writeDocumentToString(dom); } catch (Exception e) { LOG.error("WS getGroupsInSite(): " + e.getClass().getName() + " : " + e.getMessage()); return "<exception/>"; } }
/** * Gets the email address for a given user * * Differs from original above as that one uses the session to get the displayname hence you must know this in advance or be logged in to the web services * with that user. This uses a userid as well so we could be logged in as admin and retrieve the email address for any user. * * @param sessionid the id of a valid session * @param userid the login username (ie jsmith26) of the user you want the email address for * @return the display name for the user * @throws AxisFault * */ public String getUserEmail( String sessionid, String userid ) throws AxisFault { Session session = establishSession(sessionid); try { User user = UserDirectoryService.getUserByEid(userid); return user.getEmail(); } catch (Exception e) { LOG.error("WS getUserEmail() failed for user: " + userid + " : " + e.getClass().getName() + " : " + e.getMessage()); return ""; } }
/** * Gets all user accounts as XML. Currently returns userId, eid, displayName and type. * * @param sessionid the id of a valid session for the admin user * @return XML or exception * @throws AxisFault * * Optional sakai.properties: * #specify the list of users to ignore separated by a comma, no spaces. Defaults to 'admin,postmaster'. * webservice.specialUsers=admin,postmaster * */ public String getAllUsers(String sessionid) throws AxisFault { Session session = establishSession(sessionid); //check that ONLY admin is accessing this if(!session.getUserId().equals(UserDirectoryService.ADMIN_ID)) { LOG.warn("WS getAllUsers() failed. Restricted to admin user."); throw new AxisFault("WS failed. Restricted to admin user."); } try { //get special users String config = ServerConfigurationService.getString("webservice.specialUsers", "admin,postmaster"); String[] items = StringUtils.split(config, ','); List<String> specialUsers = Arrays.asList(items); //get all users List<User> allUsers = UserDirectoryService.getUsers(); //check size if(allUsers == null || allUsers.size() == 0) { return "<list/>"; } Document dom = Xml.createDocument(); Node list = dom.createElement("list"); dom.appendChild(list); for (Iterator i = allUsers.iterator(); i.hasNext();) { User user = (User) i.next(); //skip if this user is in the specialUser list if(specialUsers.contains(user.getEid())) { continue; } Node item = dom.createElement("item"); Node userId = dom.createElement("userId"); userId.appendChild(dom.createTextNode(user.getId())); Node eid = dom.createElement("eid"); eid.appendChild(dom.createTextNode(user.getEid())); Node displayName = dom.createElement("displayName"); displayName.appendChild(dom.createTextNode(user.getDisplayName())); Node type = dom.createElement("type"); type.appendChild(dom.createTextNode(user.getType())); item.appendChild(userId); item.appendChild(eid); item.appendChild(displayName); item.appendChild(type); list.appendChild(item); } return Xml.writeDocumentToString(dom); } catch (Exception e) { LOG.error("WS getAllUsers(): " + e.getClass().getName() + " : " + e.getMessage()); return "<exception/>"; } }
/** * Adds a tool to all My Workspace sites * * @param sessionid the id of a valid session for the admin user * @param toolid the id of the tool you want to add (ie sakai.profile2) * @param pagetitle the title of the page shown in the site navigation * @param tooltitle the title of the tool shown in the main portlet * @param pagelayout single or double column (0 or 1). Any other value will revert to 0. * @param position integer specifying the position within other pages on the site (0 means top, for right at the bottom a large enough number, ie 99) * @param popup boolean for if it should be a popup window or not * * @return success or exception * @throws AxisFault * * Sakai properties: * #specify the list of users to ignore separated by a comma, no spaces. Defaults to 'admin,postmaster'. * webservice.specialUsers=admin,postmaster * */ public String addNewToolToAllWorkspaces(String sessionid, String toolid, String pagetitle, String tooltitle, int pagelayout, int position, boolean popup) throws AxisFault { Session session = establishSession(sessionid); //check that ONLY admin is accessing this if(!session.getUserId().equals(UserDirectoryService.ADMIN_ID)) { LOG.warn("WS addNewToolToAllWorkspaces() failed. Restricted to admin user."); throw new AxisFault("WS failed. Restricted to admin user."); } try { //get special users String config = ServerConfigurationService.getString("webservice.specialUsers", "admin,postmaster"); String[] items = StringUtils.split(config, ','); List<String> specialUsers = Arrays.asList(items); //now get all users List<String> allUsers = new ArrayList<String>(); List<User> users = UserDirectoryService.getUsers(); for (Iterator i = users.iterator(); i.hasNext();) { User user = (User) i.next(); allUsers.add(user.getId()); } //remove special users allUsers.removeAll(specialUsers); //now add a page to each site, and the tool to that page for (Iterator j = allUsers.iterator(); j.hasNext();) { String userid = StringUtils.trim((String)j.next()); LOG.info("Processing user:" + userid); String myWorkspaceId = SiteService.getUserSiteId(userid); Site siteEdit = null; SitePage sitePageEdit = null; try { siteEdit = SiteService.getSite(myWorkspaceId); } catch (IdUnusedException e) { LOG.error("No workspace for user: " + myWorkspaceId + ", skipping..."); continue; } sitePageEdit = siteEdit.addPage(); sitePageEdit.setTitle(pagetitle); sitePageEdit.setLayout(pagelayout); //KNL-250, SAK-16819 - if position too large, will throw ArrayIndexOutOfBoundsException //deal with this here and just set to the number of pages - 1 so its at the bottom. int numPages = siteEdit.getPages().size(); if(position > numPages) { position = numPages-1; } sitePageEdit.setPosition(position); sitePageEdit.setPopup(popup); ToolConfiguration tool = sitePageEdit.addTool(); Tool t = tool.getTool(); tool.setTool(toolid, ToolManager.getTool(toolid)); tool.setTitle(tooltitle); SiteService.save(siteEdit); LOG.info("Page added for user:" + userid); } return "success"; } catch (Exception e) { LOG.error("WS addNewToolToAllWorkspaces(): " + e.getClass().getName() + " : " + e.getMessage()); return e.getClass().getName() + " : " + e.getMessage(); } }
/** * Copies a role from one authzgroup to another. Useful for mass population/synchronisation * * The sessionid argument must be a valid session for the admin user ONLY otherwise it will fail. * The authzgroup arguments for sites should start with /site/SITEID, likewise for site groups etc * * @param sessionid the sessionid of a valid session for the admin user * @param authzgroupid1 the authgroupid of the site you want to copy the role FROM * @param authzgroupid2 the authgroupid of the site you want to copy the role TO * @param roleid the id of the role you want to copy * @param description the description of the new role * @return string of success * @throws AxisFault if not admin user, if new role cannot be created, if functions differ after the new role is made * * @since 21st May 2008 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String copyRole( String sessionid, String authzgroupid1, String authzgroupid2, String roleid, String description) throws AxisFault { Session session = establishSession(sessionid); Set existingfunctions; Set newfunctions; Set existingroles; ArrayList existingroleids; Iterator iRoles; boolean createRole = false; Role role2; //check only admin if(!session.getUserId().equals(UserDirectoryService.ADMIN_ID)) { LOG.warn("WS copyRole(): Permission denied. Restricted to admin user."); throw new AxisFault("WS copyRole(): Permission denied. Restricted to admin user."); } try { //open authzgroup1 AuthzGroup authzgroup1 = AuthzGroupService.getAuthzGroup(authzgroupid1); //get role that we want to copy Role role1 = authzgroup1.getRole(roleid); //get functions that are in this role existingfunctions = role1.getAllowedFunctions(); LOG.warn("WS copyRole(): existing functions in role " + roleid + " in " + authzgroupid1 + ": " + new ArrayList(existingfunctions).toString()); //open authzgroup2 AuthzGroup authzgroup2 = AuthzGroupService.getAuthzGroup(authzgroupid2); //get roles in authzgroup2 existingroles = authzgroup2.getRoles(); existingroleids = new ArrayList(); //iterate over roles, get the roleId from the role, add to arraylist for checking for (iRoles = existingroles.iterator(); iRoles.hasNext();) { Role existingrole = (Role)iRoles.next(); existingroleids.add(existingrole.getId()); } LOG.warn("WS copyRole(): existing roles in " + authzgroupid2 + ": " + existingroleids.toString()); //if this roleid exists in the authzgroup already... if(existingroleids.contains(roleid)) { LOG.warn("WS copyRole(): role " + roleid + " exists in " + authzgroupid2 + ". This role will updated."); } else { LOG.warn("WS copyRole(): role " + roleid + " does not exist in " + authzgroupid2 + ". This role will be created."); //create this role in authzgroup2 role2 = authzgroup2.addRole(roleid); //save authzgroup change AuthzGroupService.save(authzgroup2); //reopen authzgroup2 for checking authzgroup2 = AuthzGroupService.getAuthzGroup(authzgroupid2); //check the role was actually created by getting set again and iterating existingroles = authzgroup2.getRoles(); existingroleids = new ArrayList(); //iterate over roles, get the roleId from the role, add to arraylist for checking for (iRoles = existingroles.iterator(); iRoles.hasNext();) { Role existingrole = (Role)iRoles.next(); existingroleids.add(existingrole.getId()); } LOG.warn("WS copyRole(): existing roles in " + authzgroupid2 + " after addition: " + existingroleids.toString()); //if role now exists, ok, else fault. if(existingroleids.contains(roleid)) { LOG.warn("WS copyRole(): role " + roleid + " was created in " + authzgroupid2 + "."); } else { LOG.warn("WS copyRole(): role " + roleid + " could not be created in " + authzgroupid2 + "."); throw new AxisFault("WS copyRole(): role " + roleid + " could not be created in " + authzgroupid2 + "."); } } //get this role role2 = authzgroup2.getRole(roleid); //add Set of functions to this role role2.allowFunctions(existingfunctions); //set description role2.setDescription(description); //save authzgroup change AuthzGroupService.save(authzgroup2); //reopen authzgroup2 for checking authzgroup2 = AuthzGroupService.getAuthzGroup(authzgroupid2); //get role we want to check role2 = authzgroup2.getRole(roleid); //get Set of functions that are now in this role newfunctions = role2.getAllowedFunctions(); //compare existingfunctions with newfunctions to see that they match if(newfunctions.containsAll(existingfunctions)) { LOG.warn("WS copyRole(): functions added successfully to role " + roleid + " in " + authzgroupid2 + "."); } else { LOG.warn("WS copyRole(): functions in roles differ after addition."); throw new AxisFault("WS copyRole(): functions in roles differ after addition."); } } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Get a user's type (for their account) * * @param sessionid the id of a valid session * @param userid the userid of the person you want the type for * @return type if set or blank * @throws AxisFault * */ public String getUserType( String sessionid, String userid ) throws AxisFault { Session session = establishSession(sessionid); try { User user = UserDirectoryService.getUserByEid(userid); return user.getType(); } catch (Exception e) { LOG.warn("WS getUserType() failed for user: " + userid); return ""; } }
/** * Creates and returns the session ID for a given user. * * The sessionid argument must be a valid session for the admin user ONLY otherwise it will fail. * The userid argument must be the EID (ie jsmith) of a valid user. * This new sessionid can then be used with getSitesUserCanAccess() to get the sites for the given user. * * @param sessionid the sessionid of a valid session for the admin user * @param userid the eid of the user you want to create a session for * @return the sessionid for the user specified * @throws AxisFault if any data is missing, * not admin user initially, * or session cannot be established * * @link requires * import org.apache.axis.Constants; * import org.apache.axis.MessageContext; * import org.sakaiproject.event.api.UsageSession; * import org.sakaiproject.event.cover.UsageSessionService; * import org.sakaiproject.event.cover.EventTrackingService; * * @since 8th Jan 2008, modified 21st August to include presence registering * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String getSessionForUser(String sessionid, String userid) throws AxisFault { Session session = establishSession(sessionid); //check that ONLY admin is accessing this if(!session.getUserId().equals(UserDirectoryService.ADMIN_ID)) { LOG.warn("WS getSessionForUser() failed. Restricted to admin user."); throw new AxisFault("WS failed. Restricted to admin user."); } try { //check for empty userid if (userid == null || userid.equals("")) { LOG.warn("WS getSessionForUser() failed. Param userid empty."); throw new AxisFault("WS failed. Param userid empty."); } //get ip address for establishing session MessageContext messageContext = MessageContext.getCurrentContext(); String ipAddress = messageContext.getStrProp(Constants.MC_REMOTE_ADDR); //start a new session Session newsession = SessionManager.startSession(); SessionManager.setCurrentSession(newsession); //inject this session with new user values User user = UserDirectoryService.getUserByEid(userid); newsession.setUserEid(userid); newsession.setUserId(user.getId()); //register the session with presence UsageSession usagesession = UsageSessionService.startSession(user.getId(),ipAddress,"SakaiScript.jws getSessionForUser()"); // update the user's externally provided realm definitions AuthzGroupService.refreshUser(user.getId()); // post the login event EventTrackingService.post(EventTrackingService.newEvent("user.login", null, true)); if (newsession == null){ LOG.warn("WS getSessionForUser() failed. Unable to establish session for userid="+userid); throw new AxisFault("WS failed. Unable to establish session"); } else { LOG.warn("WS getSessionForUser() OK. Established session for userid="+userid+" session="+newsession.getId()); return newsession.getId(); } } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } }
Available since 2.6
/** * Gets list of ALL users in an authzgroup * * * @param sessionid the id of a valid session * @param authzgroupid the id of the authzgroup or site you want to get the users in (if site: /site/SITEID) * @return xml doc of the list of users, display name and roleid * @throws AxisFault returns <exception /> string if exception encountered * * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String getUsersInAuthzGroup(String sessionid, String authzgroupid) throws AxisFault { Session s = establishSession(sessionid); try { AuthzGroup azg = AuthzGroupService.getAuthzGroup(authzgroupid); Document dom = Xml.createDocument(); Node list = dom.createElement("list"); dom.appendChild(list); for (Iterator i = azg.getUsers().iterator(); i.hasNext(); ) { String id = (String) i.next(); try { User user = UserDirectoryService.getUser(id); Node userNode = dom.createElement("user"); Node userId = dom.createElement("id"); userId.appendChild(dom.createTextNode(user.getEid())); Node userName = dom.createElement("name"); userName.appendChild(dom.createTextNode(user.getDisplayName())); Node userRole = dom.createElement("role"); userRole.appendChild(dom.createTextNode(role)); userNode.appendChild(userId); userNode.appendChild(userName); userNode.appendChild(userRole); list.appendChild(userNode); } catch (Exception e) { //Exception with this user, log the error, skip this user and continue to the next LOG.warn("WS getUsersInAuthzGroup(): error processing user " + id + " : " + e.getClass().getName() + " : " + e.getMessage()); } } return Xml.writeDocumentToString(dom); } catch (Exception e) { LOG.warn("WS getUsersInAuthzGroup(): " + e.getClass().getName() + " : " + e.getMessage()); return "<exception/>"; } }
/** Get list of users in an authzgroup with the given role(s) * * @param sessionid the id of a valid session, generally the admin user * @param authzgroupid the id of the authzgroup or site site (if site: /site/siteid) you want to get the users in * @param authzgrouproles the roles that you want to filter on (string with spaces as delimiters) * @return xml doc of the list of users, display name and roleid * @throws AxisFault returns <exception /> string if exception encountered * * @since September 2007. Modified July 2008 to accept multiple roles as args * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String getUsersInAuthzGroupWithRole(String sessionid, String authzgroupid, String authzgrouproles) throws AxisFault { Session s = establishSession(sessionid); try { AuthzGroup azg = AuthzGroupService.getAuthzGroup(authzgroupid); Document dom = Xml.createDocument(); Node list = dom.createElement("list"); dom.appendChild(list); //split the authzgroup roles into a string[] then add into arraylist. //Done this way so we dont need any extra imports (ie using List<String> authzgrouprolesList = Arrays.asList(authzgrouprolesArr)); String[] authzgrouprolesArr = authzgrouproles.split(" "); ArrayList<String> authzgrouprolesList = new ArrayList<String>(); for(int i=0; i< authzgrouprolesArr.length; i++) { authzgrouprolesList.add(authzgrouprolesArr[i]); } //iterate over each role in the list... for (Iterator j = authzgrouprolesList.iterator(); j.hasNext(); ) { String role = (String) j.next(); //now get all the users in the authzgroup with this role and add to xml doc for (Iterator k = azg.getUsersHasRole(role).iterator(); k.hasNext(); ) { String id = (String) k.next(); try { User user = UserDirectoryService.getUser(id); Node userNode = dom.createElement("user"); Node userId = dom.createElement("id"); userId.appendChild(dom.createTextNode(user.getEid())); Node userName = dom.createElement("name"); userName.appendChild(dom.createTextNode(user.getDisplayName())); Node userRole = dom.createElement("role"); userRole.appendChild(dom.createTextNode(role)); userNode.appendChild(userId); userNode.appendChild(userName); userNode.appendChild(userRole); list.appendChild(userNode); } catch (Exception e) { //skip this user //we need this here because otherwise the userdirectoryservice throws an error //if the person no longer exists in Sakai/LDAP. this catches it and allows it to return normally by just skipping the person. LOG.warn("WS getUsersInAuthzGroupWithRole(): error processing user " + id + " : " + e.getClass().getName() + " : " + e.getMessage()); } } } return Xml.writeDocumentToString(dom); } catch (Exception e) { LOG.warn("WS getUsersInAuthzGroupWithRoles(): error " + e.getClass().getName() + " : " + e.getMessage()); return "<exception/>"; } }
/** * Removes a member from a given site * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to remove the user from * @return success or string containing error * @throws AxisFault * * @since Sept 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String removeMemberFromSite(String sessionid, String siteid, String eid) throws AxisFault { Session session = establishSession(sessionid); try { Site site = SiteService.getSite(siteid); String userid = UserDirectoryService.getUserByEid(eid).getId(); site.removeMember(userid); SiteService.save(site); } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Get a site's title * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want the title of * @return title of the site or string containing error * @throws AxisFault * * @since Sept 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String getSiteTitle(String sessionid, String siteid) throws AxisFault { Session s = establishSession(sessionid); String siteTitle = ""; try { Site site = SiteService.getSite(siteid); siteTitle = site.getTitle(); } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } return siteTitle; }
/** * Get a site's description * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want the description of * @return description of the site or string containing error * @throws AxisFault * * @since Sept 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String getSiteDescription(String sessionid, String siteid) throws AxisFault { Session s = establishSession(sessionid); String siteDescription = ""; try { Site site = SiteService.getSite(siteid); siteDescription = site.getDescription(); } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } return siteDescription; }
/** * Get a site's skin * * @param sessionid the id of a valid session * @param siteid the id of the site you want the skin of * @return skin for the site or string containing error * @throws AxisFault * */ public String getSiteSkin(String sessionid, String siteid) throws AxisFault { Session s = establishSession(sessionid); String siteSkin = ""; try { Site site = SiteService.getSkin(siteid); siteSkin = site.getSkin(); } catch (Exception e) { LOG.error("WS getSiteSkin(): " + e.getClass().getName() + " : " + e.getMessage()); return e.getClass().getName() + " : " + e.getMessage(); } return siteSkin; }
/** * Get a site's joinable status * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want the joinable status of * @return true if joinable, false if not or error. Could also print a log error if error * @throws AxisFault * * @since Sept 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public boolean isSiteJoinable(String sessionid, String siteid) throws AxisFault { Session s = establishSession(sessionid); try { Site site = SiteService.getSite(siteid); if(site.isJoinable()) { return true; } else { return false; } } catch (Exception e) { return false; } }
/** * Check if a user is in a particular authzgroup * Since a site is an authgroup in itself, we can re-use this for both functions (checking site overall, and checking individual group if desired) * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to check for the user in * @param eid the userid of the person you want to check * @return true if in site, false if not or error. Could also print a log error if error * @throws AxisFault * * @since Sept 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public boolean checkForUserInAuthzGroup(String sessionid, String siteid, String eid) throws AxisFault { Session s = establishSession(sessionid); try { AuthzGroup azg = AuthzGroupService.getAuthzGroup(siteid); for (Iterator i = azg.getUsers().iterator(); i.hasNext(); ) { String id = (String) i.next(); User user = UserDirectoryService.getUser(id); if(user.getEid().equals(eid)) { return true; } } return false; } catch (Exception e) { return false; } }
/** * Change the title of a site * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to change the title of * @param title the new title * @return success or string containing error * @throws AxisFault * * @since Oct 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String changeSiteTitle( String sessionid, String siteid, String title) throws AxisFault { Session session = establishSession(sessionid); try { Site siteEdit = null; siteEdit = SiteService.getSite(siteid); siteEdit.setTitle(title); SiteService.save(siteEdit); } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Change the skin of a site * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to change the skin of * @param title the new skin value (make sure its in /library/skin/<yourskin>) * @return success or string containing error * @throws AxisFault * * @since Oct 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String changeSiteSkin( String sessionid, String siteid, String skin) throws AxisFault { Session session = establishSession(sessionid); try { Site siteEdit = null; siteEdit = SiteService.getSite(siteid); siteEdit.setSkin(skin); SiteService.save(siteEdit); } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Make a site joinable or not, depending on the params sent * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to change the status of * @param joinable boolean if its joinable or not * @param joinerrole the role that users who join the site will be given * @param publicview boolean if the site is to be public or not. if its joinable it should probably be public so people can find it, but if its public it doesnt need to be joinable. * @return success or string containing error * @throws AxisFault * * @since Oct 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String changeSiteJoinable( String sessionid, String siteid, boolean joinable, String joinerrole, boolean publicview) throws AxisFault { Session session = establishSession(sessionid); try { Site siteEdit = null; siteEdit = SiteService.getSite(siteid); siteEdit.setJoinable(joinable); siteEdit.setJoinerRole(joinerrole); siteEdit.setPubView(publicview); SiteService.save(siteEdit); } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Change the icon of a site (top left hand corner of site) * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to change the icon of * @param title the new icon value (publically accessible url - suggest its in Resources for the site or other public spot) * @return success or string containing error * @throws AxisFault * * @since Nov 2007 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String changeSiteIconUrl( String sessionid, String siteid, String iconurl) throws AxisFault { Session session = establishSession(sessionid); try { Site siteEdit = null; siteEdit = SiteService.getSite(siteid); siteEdit.setIconUrl(iconurl); SiteService.save(siteEdit); } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Change the description of a site * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to change the title of * @param description the new description * @return success or string containing error * @throws AxisFault * * @since Sept 2008 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String changeSiteDescription( String sessionid, String siteid, String description) throws AxisFault { Session session = establishSession(sessionid); try { Site siteEdit = null; siteEdit = SiteService.getSite(siteid); siteEdit.setDescription(description); SiteService.save(siteEdit); } catch (Exception e) { LOG.warn("WS changeSiteDescription(): error " + e.getClass().getName() + " : " + e.getMessage()); return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Get a custom property of a site * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to get the property from * @param propname the name of the property you want * @return the property or blank if not found/property is blank * @throws AxisFault * * @since Aug 2008 * * @link Requires import org.sakaiproject.entity.api.ResourceProperties; * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String getSiteProperty(String sessionid, String siteid, String propname) throws AxisFault { Session session = establishSession(sessionid); try { //get site handle Site site = SiteService.getSite(siteid); //get list of properties for this site ResourceProperties props = site.getProperties(); //get the property that we wanted, as a string. this wont return multi valued ones //would need to use getPropertyList() for that, but then need to return XML since its a list. String propvalue = props.getProperty(propname); return propvalue; } catch (Exception e) { LOG.warn("WS getSiteProperty(): error " + e.getClass().getName() + " : " + e.getMessage()); } return ""; }
/** * Set a custom property for a site * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to set the property for * @param propname the name of the property you want to set * @param propvalue the name of the property you want to set * @return success if true or exception * @throws AxisFault * * @since Aug 2008 * * @link Requires import org.sakaiproject.entity.api.ResourcePropertiesEdit; * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String setSiteProperty(String sessionid, String siteid, String propname, String propvalue) throws AxisFault { Session session = establishSession(sessionid); try { //get site handle Site site = SiteService.getSite(siteid); //get properties in edit mode ResourcePropertiesEdit props = site.getPropertiesEdit(); //add property props.addProperty(propname, propvalue); //save site SiteService.save(site); } catch (Exception e) { LOG.warn("WS setSiteProperty(): error " + e.getClass().getName() + " : " + e.getMessage()); return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Remove a custom property for a site * * @param sessionid the id of a valid session, generally the admin user * @param siteid the id of the site you want to remove the property from * @param propname the name of the property you want to remove * @return success if true or exception * @throws AxisFault * * @since Aug 2008 * * @link Requires import org.sakaiproject.entity.api.ResourcePropertiesEdit; * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String removeSiteProperty( String sessionid, String siteid, String propname) throws AxisFault { Session session = establishSession(sessionid); try { //get site handle Site site = SiteService.getSite(siteid); //get properties in edit mode ResourcePropertiesEdit props = site.getPropertiesEdit(); //remove property //if the property doesn't exist it will still return success. this is fine. props.removeProperty(propname); //save site SiteService.save(site); } catch (Exception e) { LOG.warn("WS removeSiteProperty(): error " + e.getClass().getName() + " : " + e.getMessage()); return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/** * Check if an authzgroup exists, similar to checkForSite, but does authzgroup instead (e.g. for checking if !site.template exists which checkForSite cannot do.) * * @param sessionid the id of a valid session, generally the admin user * @param authzgroupid the id of the authzgroup you want to check * @return true/false * @throws AxisFault * * @since Aug 2008 * * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public boolean checkForAuthzGroup(String sessionid, String authzgroupid) throws AxisFault { Session s = establishSession(sessionid); try { AuthzGroup authzgroup = null; authzgroup = AuthzGroupService.getAuthzGroup(authzgroupid); if (authzgroup != null) { return true; } else { return false; } } catch (Exception e) { return false; } }
/** * Check if a role exists in a given authzgroup * * @param sessionid the id of a valid session, generally the admin user * @param authzgroupid the id of the authzgroup you want to check * @param roleid the id of the role you want to check for * @return true/false * @throws AxisFault * * @since Aug 2008 * * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public boolean checkForRoleInAuthzGroup(String sessionid, String authzgroupid, String roleid) throws AxisFault { Session session = establishSession(sessionid); try { //open authzgroup AuthzGroup authzgroup = AuthzGroupService.getAuthzGroup(authzgroupid); //see if we can get the role in this authzgroup. will either return the Role, or null Role role = authzgroup.getRole(roleid); if(role != null) { return true; } return false; } catch (Exception e) { LOG.warn("WS checkForRoleInAuthzGroup(): error " + e.getClass().getName() + " : " + e.getMessage()); return false; } }
/** * Gets the display name for a given user. * * Differs from original in that that one used the session to get the displayname, this uses a userid * * @param sessionid the sessionid of a valid session for the admin user * @param userid the eid of the user you want the name of * @return the display name for the user * @throws AxisFault * * @since 17th July 2008 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String getUserDisplayName( String sessionid, String userid ) throws AxisFault { Session session = establishSession(sessionid); try { User user = UserDirectoryService.getUserByEid(userid); return user.getDisplayName(); } catch (Exception e) { LOG.warn("WS getUserDisplayName() failed for user: " + userid); return ""; } }
/** * Search all the users that match this criteria in id or email, first or last name, returning a subset of records within the record range given (sorted by sort name). * * @param sessionid the id of a valid session, generally the admin user * @param criteria the search criteria. * @param first the first record position to return. * @param last the last record position to return. * @return xml doc of list of records * @throws AxisFault * * @since Aug 2008 * * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) */ public String searchForUsers(String sessionid, String criteria, int first, int last) throws AxisFault { Session session = establishSession(sessionid); try { //validate input if(("").equals(criteria)) { LOG.warn("WS searchForUsers(): error: no search criteria"); return "<exception/>"; } if(first == 0 || last == 0) { LOG.warn("WS searchForUsers(): error: invalid ranges"); return "<exception/>"; } List users = UserDirectoryService.searchUsers(criteria, first, last); Document dom = Xml.createDocument(); Node list = dom.createElement("list"); dom.appendChild(list); for (Iterator i = users.iterator(); i.hasNext();) { User user = (User) i.next(); try { Node userNode = dom.createElement("user"); Node userId = dom.createElement("id"); userId.appendChild(dom.createTextNode(user.getId())); Node userEid = dom.createElement("eid"); userEid.appendChild(dom.createTextNode(user.getEid())); Node userName = dom.createElement("name"); userName.appendChild(dom.createTextNode(user.getDisplayName())); Node userEmail = dom.createElement("email"); userEmail.appendChild(dom.createTextNode(user.getEmail())); userNode.appendChild(userId); userNode.appendChild(userEid); userNode.appendChild(userName); userNode.appendChild(userEmail); list.appendChild(userNode); } catch (Exception e) { //log this error and continue otherwise we get nothing LOG.warn("WS searchForUsers(): error: " + e.getClass().getName() + " : " + e.getMessage()); } } //add total size node Node total = dom.createElement("total"); total.appendChild(dom.createTextNode(Integer.toString(users.size()))); list.appendChild(total); return Xml.writeDocumentToString(dom); } catch (Exception e) { LOG.warn("WS searchForUsers(): error " + e.getClass().getName() + " : " + e.getMessage()); return "<exception/>"; } }
SakaiGradebook.jws
Much of the code here is based on the original by Rutgers, however I have updated it for Sakai 2.4. This is the whole file.
It's not finished though!
/* * SakaiGradebook.jws - updated for Sakai 2.4.x by Steve Swinsburg (s.swinsburg@lancaster.ac.uk) * */ import java.util.Date; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.util.Set; import java.util.Collection; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.cover.SessionManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.authz.api.AuthzGroup; import org.sakaiproject.authz.api.Role; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.user.api.UserEdit; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.user.api.User; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.service.gradebook.shared.GradebookService; import org.sakaiproject.service.gradebook.shared.Assignment; import java.util.Properties; import java.util.Calendar; import org.apache.axis.AxisFault; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.util.Xml; //import org.w3c.dom.Document; //import org.w3c.dom.Element; //import org.w3c.dom.Node; //import org.w3c.dom.NodeList; public class SakaiGradebook { private Session establishSession(String id) throws AxisFault { Session s = SessionManager.getSession(id); if (s == null) { throw new AxisFault("Session "+id+" is not active"); } s.setActive(); SessionManager.setCurrentSession(s); return s; } //TODO // addAssignment() // getAssignmentScore() // setAssignmentScore() //see gradebook/service/impl/src/java/org/sakaiproject/component/gradebook/GradebookServiceHibernateImpl.java public String getAssignments(String sessionid, String siteid) throws AxisFault { //THIS NEEDS TO BE CHANGED TO OUTPUT XML AS ASSIGNEMNT TITLES CAN HAVE ANY CHARACTEDR IN THEM, THUS NO SUITABLE DELIMITER Session session = establishSession(sessionid); String retval = ""; String userid = ""; try { //get user from session userid = session.getUserId(); System.err.println(userid); //init gradebook GradebookService gs = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); //check user is allowed to access gradebook if (!gs.isUserAbleToGradeStudent(siteid, userid)) { return "Permission Denied"; } //get assignments List assignments = gs.getAssignments(siteid); for (Iterator iAssignment = assignments.iterator(); iAssignment.hasNext();) { Assignment a = (Assignment)iAssignment.next(); retval = retval + "," + a.getName(); } } catch (Exception e) { return e.getClass().getName() + " : " + e.getMessage(); } if (retval.length() == 0) { return retval; } else { return retval.substring(1); } } private boolean isUserAbleToGradeStudent(String siteid, String userid) throws AxisFault { boolean retval = false; try { GradebookService gs = (GradebookService) ComponentManager.get("org.sakaiproject.service.gradebook.GradebookService"); retval = gs.isUserAbleToGradeStudent(siteid, userid); return retval; } catch (Exception e) { System.err.println( e.getClass().getName() + " : " + e.getMessage()); //return false; } return false; } }
Deprecated
/** * Parses a given string of xml for a bunch of attributes, like siteid, role, users etc, and adds them to the site. * * Must follow the proper schema. Also requires another import org.w3c.dom.NodeList; and maybe another one, you'll see when you run it ;) * Also it adds them one at a time, saving after each, which is slow and unnecessary. As a result I've stopped using it. but you can modify it pretty easily. * * @param xml the properly formatted xml * @return string with info about each user addition. * @throws AxisFault * * @since Feb 2008 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) * @deprecated */ public String addMembersToSiteFromXML(String xml) { ArrayList<String> usersToAdd = new ArrayList<String>(); String sessionid = ""; String siteid = ""; String roleid = ""; String username = ""; NodeList nl; Node n; StringBuilder sb = new StringBuilder(); try { Document doc = Xml.readDocumentFromString(xml); //this is the Sakai equiv of next 3 lines //DOMParser parser = new DOMParser(); //parser.parse(new InputSource(new StringReader(xml))); //Document doc = parser.getDocument(); //get the session from the XML nl = doc.getElementsByTagName("session"); n = nl.item(0); //System.out.println(n.getNodeName() + " " + n.getTextContent()); sessionid = n.getTextContent(); //get the siteid from the XML nl = doc.getElementsByTagName("siteid"); n = nl.item(0); //System.out.println(n.getNodeName() + " " + n.getTextContent()); siteid = n.getTextContent(); //get the role from the XML nl = doc.getElementsByTagName("roleid"); n = nl.item(0); //System.out.println(n.getNodeName() + " " + n.getTextContent()); roleid = n.getTextContent(); //get the usernames, add to list nl = doc.getElementsByTagName("username"); for (int i=0; i<nl.getLength(); i++) { n = nl.item(i); //System.out.print(n.getTextContent() + " "); usersToAdd.add(n.getTextContent()); } //validate session Session session = establishSession(sessionid); //get the site Site site = SiteService.getSite(siteid); //add users to site Iterator<String> itUsersToAdd = usersToAdd.iterator(); while(itUsersToAdd.hasNext()) { //get username username = (String)itUsersToAdd.next(); String userid = UserDirectoryService.getUserByEid(username).getId(); site.addMember(userid,roleid,true,false); LOG.warn("WS addMemberToSiteFromXML() added username: " + username + ", userid: " + userid + ", site: " + siteid + ", role: " + roleid); sb.append(username + " "); SiteService.save(site); } LOG.warn("WS addMembersToSiteFromXML() ended successfully"); return "success"; } catch (Exception e) { LOG.warn("WS addMemberToSiteFromXML() failed. " + e.getClass().getName() + " : " + e.getMessage()); sb.append(username + " " + e.getClass().getName() + " : " + e.getMessage()); return sb.toString(); } }
/** * Parses a given string of xml for a bunch of attributes, like siteid, role, users etc, and removes them from the site. * * Must follow the proper schema. Also requires another import org.w3c.dom.NodeList; and maybe another one, you'll see when you run it ;) * Also it removes them one at a time, saving after each, which is slow and unnecessary. As a result I've stopped using it. but you can modify it pretty easily. * * @param xml the properly formatted xml * @return string with info about each user removal. * @throws AxisFault * * @since Feb 2008 * * @author Steve Swinsburg (s.swinsburg@lancaster.ac.uk) * @deprecated */ public String removeMembersFromSiteFromXML(String xml) { ArrayList<String> usersToRemove = new ArrayList<String>(); String sessionid = ""; String siteid = ""; String roleid = ""; String username = ""; NodeList nl; Node n; StringBuilder sb = new StringBuilder(); try { Document doc = Xml.readDocumentFromString(xml); //this is the Sakai equiv of next 3 lines //DOMParser parser = new DOMParser(); //parser.parse(new InputSource(new StringReader(xml))); //Document doc = parser.getDocument(); //get the session from the XML nl = doc.getElementsByTagName("session"); n = nl.item(0); //System.out.println(n.getNodeName() + " " + n.getTextContent()); sessionid = n.getTextContent(); //get the siteid from the XML nl = doc.getElementsByTagName("siteid"); n = nl.item(0); //System.out.println(n.getNodeName() + " " + n.getTextContent()); siteid = n.getTextContent(); //get the role from the XML /* nl = doc.getElementsByTagName("roleid"); n = nl.item(0); //System.out.println(n.getNodeName() + " " + n.getTextContent()); roleid = n.getTextContent(); */ //get the usernames, add to list nl = doc.getElementsByTagName("username"); for (int i=0; i<nl.getLength(); i++) { n = nl.item(i); //System.out.print(n.getTextContent() + " "); usersToRemove.add(n.getTextContent()); } //validate session Session session = establishSession(sessionid); //get the site Site site = SiteService.getSite(siteid); //add users to site Iterator<String> itUsersToRemove = usersToRemove.iterator(); while(itUsersToRemove.hasNext()) { //get username username = (String)itUsersToRemove.next(); String userid = UserDirectoryService.getUserByEid(username).getId(); site.removeMember(userid); LOG.warn("WS removeMembersFromSiteFromXML() removed username: " + username + ", userid: " + userid + ", site: " + siteid); sb.append(username + " "); SiteService.save(site); } LOG.warn("WS removeMembersFromSiteFromXML() ended successfully"); return "success"; } catch (Exception e) { LOG.warn("WS removeMembersFromSiteFromXML() failed. " + e.getClass().getName() + " : " + e.getMessage()); sb.append(username + " " + e.getClass().getName() + " : " + e.getMessage()); return sb.toString(); } }
Keywords: WSGradebook.jws SakaiGradebook.jws SakaiScript.jws jws wsdl