Index: citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java =================================================================== --- citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java (revision 107777) +++ citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java (revision 109899) @@ -22,33 +22,42 @@ package org.sakaiproject.citation.tool; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; -import java.io.InputStream; -import java.io.InputStreamReader; - +import java.text.DateFormat; +import java.text.ParseException; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Date; import java.util.Enumeration; +import java.util.HashMap; import java.util.Hashtable; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.Stack; +import java.util.SortedSet; +import java.util.TreeSet; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import net.sf.json.JSONObject; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.sakaiproject.antivirus.api.VirusFoundException; import org.sakaiproject.authz.api.SecurityAdvisor; -import org.sakaiproject.authz.cover.SecurityService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.RunData; @@ -59,27 +68,30 @@ import org.sakaiproject.citation.api.CitationCollection; import org.sakaiproject.citation.api.CitationHelper; import org.sakaiproject.citation.api.CitationIterator; +import org.sakaiproject.citation.api.CitationService; +import org.sakaiproject.citation.api.ConfigurationService; import org.sakaiproject.citation.api.Schema; +import org.sakaiproject.citation.api.Schema.Field; import org.sakaiproject.citation.api.SearchCategory; import org.sakaiproject.citation.api.SearchDatabaseHierarchy; -import org.sakaiproject.citation.api.Schema.Field; -import org.sakaiproject.citation.cover.CitationService; -import org.sakaiproject.citation.cover.ConfigurationService; -import org.sakaiproject.citation.cover.SearchManager; +import org.sakaiproject.citation.api.SearchManager; import org.sakaiproject.citation.util.api.SearchCancelException; import org.sakaiproject.citation.util.api.SearchException; import org.sakaiproject.citation.util.api.SearchQuery; import org.sakaiproject.component.cover.ComponentManager; +import org.sakaiproject.content.api.ContentCollection; +import org.sakaiproject.content.api.ContentEntity; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentResourceEdit; +import org.sakaiproject.content.api.GroupAwareEntity.AccessMode; import org.sakaiproject.content.api.ResourceToolAction; import org.sakaiproject.content.api.ResourceToolActionPipe; import org.sakaiproject.content.api.ResourceType; +import org.sakaiproject.entity.api.EntityManager; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; -import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.NotificationService; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.exception.IdInvalidException; @@ -87,26 +99,32 @@ import org.sakaiproject.exception.IdUniquenessException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.InUseException; +import org.sakaiproject.exception.InconsistentException; import org.sakaiproject.exception.OverQuotaException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.ServerOverloadException; import org.sakaiproject.exception.TypeException; +import org.sakaiproject.site.api.Group; +import org.sakaiproject.site.api.Site; +import org.sakaiproject.site.api.SiteService; +import org.sakaiproject.time.api.Time; +import org.sakaiproject.time.cover.TimeService; +import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolException; +import org.sakaiproject.tool.api.ToolManager; import org.sakaiproject.tool.api.ToolSession; -import org.sakaiproject.tool.cover.SessionManager; -import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.Validator; +import org.sakaiproject.util.api.FormattedText; /** * */ public class CitationHelperAction extends VelocityPortletPaneledAction { - /** * This class contains constants and utility methods to maintain state of * the advanced search form UI and process submitted data @@ -459,7 +477,18 @@ protected final static Log logger = LogFactory.getLog(CitationHelperAction.class); public static ResourceLoader rb = new ResourceLoader("citations"); + + protected CitationService citationService; + protected ConfigurationService configurationService; + protected SearchManager searchManager; + protected ContentHostingService contentService; + protected EntityManager entityManager; + protected SessionManager sessionManager; + + protected static FormattedText formattedText; + protected static ToolManager toolManager; + public static final Integer DEFAULT_RESULTS_PAGE_SIZE = new Integer(10); public static final Integer DEFAULT_LIST_PAGE_SIZE = new Integer(10); @@ -486,6 +515,7 @@ */ public enum Mode { + NEW_RESOURCE, DATABASE, CREATE, EDIT, @@ -515,8 +545,8 @@ protected static final String STATE_RESOURCES_ADD = CitationHelper.CITATION_PREFIX + "resources_add"; protected static final String STATE_CURRENT_DATABASES = CitationHelper.CITATION_PREFIX + "current_databases"; protected static final String STATE_CANCEL_PAGE = CitationHelper.CITATION_PREFIX + "cancel_page"; - protected static final String STATE_COLLECTION_ID = CitationHelper.CITATION_PREFIX + "collection_id"; - protected static final String STATE_COLLECTION = CitationHelper.CITATION_PREFIX + "collection"; + protected static final String STATE_CITATION_COLLECTION_ID = CitationHelper.CITATION_PREFIX + "citation_collection_id"; + protected static final String STATE_CITATION_COLLECTION = CitationHelper.CITATION_PREFIX + "citation_collection"; protected static final String STATE_CITATION_ID = CitationHelper.CITATION_PREFIX + "citation_id"; protected static final String STATE_COLLECTION_TITLE = CitationHelper.CITATION_PREFIX + "collection_name"; protected static final String STATE_CURRENT_REPOSITORY = CitationHelper.CITATION_PREFIX + "current_repository"; @@ -538,6 +568,9 @@ protected static final String STATE_SEARCH_INFO = CitationHelper.CITATION_PREFIX + "search_info"; protected static final String STATE_BASIC_SEARCH = CitationHelper.CITATION_PREFIX + "basic_search"; protected static final String STATE_SEARCH_RESULTS = CitationHelper.CITATION_PREFIX + "search_results"; + protected static final String STATE_RESOURCE_ENTITY_PROPERTIES = CitationHelper.CITATION_PREFIX + "citationList_properties"; + + protected static final String TEMPLATE_NEW_RESOURCE = "citation/new_resource"; protected static final String TEMPLATE_CREATE = "citation/create"; protected static final String TEMPLATE_EDIT = "citation/edit"; protected static final String TEMPLATE_ERROR = "citation/error"; @@ -550,8 +583,47 @@ protected static final String TEMPLATE_RESULTS = "citation/results"; protected static final String TEMPLATE_VIEW = "citation/view"; protected static final String TEMPLATE_DATABASE = "citation/_databases"; + + protected static final String PROP_ACCESS_MODE = "accessMode"; + protected static final String PROP_IS_COLLECTION = "isCollection"; + protected static final String PROP_IS_DROPBOX = "isDropbox"; + protected static final String PROP_IS_GROUP_INHERITED = "isGroupInherited"; + protected static final String PROP_IS_GROUP_POSSIBLE = "isGroupPossible"; + protected static final String PROP_IS_HIDDEN = "isHidden"; + protected static final String PROP_IS_PUBVIEW = "isPubview"; + protected static final String PROP_IS_PUBVIEW_INHERITED = "isPubviewInherited"; + protected static final String PROP_IS_PUBVIEW_POSSIBLE = "isPubviewPossible"; + protected static final String PROP_IS_SINGLE_GROUP_INHERITED = "isSingleGroupInherited"; + protected static final String PROP_IS_SITE_COLLECTION = "isSiteCollection"; + protected static final String PROP_IS_SITE_ONLY = "isSiteOnly"; + protected static final String PROP_IS_USER_SITE = "isUserSite"; + protected static final String PROP_POSSIBLE_GROUPS = "possibleGroups"; + protected static final String PROP_RELEASE_DATE = "releaseDate"; + protected static final String PROP_RELEASE_DATE_STR = "releaseDateStr"; + protected static final String PROP_RETRACT_DATE = "retractDate"; + protected static final String PROP_RETRACT_DATE_STR = "retractDateStr"; + protected static final String PROP_USE_RELEASE_DATE = "useReleaseDate"; + protected static final String PROP_USE_RETRACT_DATE = "useRetractDate"; + public static final String CITATION_ACTION = "citation_action"; + public static final String UPDATE_RESOURCE = "update_resource"; + public static final String CREATE_RESOURCE = "create_resource"; + public static final String IMPORT_CITATIONS = "import_citations"; + public static final String MIMETYPE_JSON = "application/json"; + public static final String MIMETYPE_HTML = "text/html"; + public static final String REQUESTED_MIMETYPE = "requested_mimetype"; + + public static final String CHARSET_UTF8 = "UTF-8"; + + /** A long representing the number of milliseconds in one week. Used for date calculations */ + public static final long ONE_DAY = 24L * 60L * 60L * 1000L; + + /** A long representing the number of milliseconds in one week. Used for date calculations */ + public static final long ONE_WEEK = 7L * ONE_DAY; + + + /** * Check for the helper-done case locally and handle it before letting the VPPA.toolModeDispatch() handle the actual dispatch. * @see org.sakaiproject.cheftool.VelocityPortletPaneledAction#toolModeDispatch(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @@ -559,8 +631,9 @@ protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res) throws ToolException { + logger.debug("toolModeDispatch()"); //SessionState sstate = getState(req); - ToolSession toolSession = SessionManager.getCurrentToolSession(); + ToolSession toolSession = getSessionManager().getCurrentToolSession(); //String mode = (String) sstate.getAttribute(ResourceToolAction.STATE_MODE); //Object started = toolSession.getAttribute(ResourceToolAction.STARTED); @@ -570,7 +643,7 @@ if ( done != null || !initHelper( getState(req) ) ) { toolSession.removeAttribute(ResourceToolAction.STARTED); - Tool tool = ToolManager.getCurrentTool(); + Tool tool = getToolManager().getCurrentTool(); String url = (String) toolSession.getAttribute(tool.getId() + Tool.HELPER_DONE_URL); @@ -591,13 +664,508 @@ super.toolModeDispatch(methodBase, methodExt, req, res); } + public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { + logger.info("doPost()"); + +// Enumeration names = req.getHeaderNames(); +// while(names.hasMoreElements()) { +// String name = names.nextElement(); +// String value = req.getHeader(name); +// logger.info("doPost() header " + name + " == " + value); +// } +// +// Cookie[] cookies = req.getCookies(); +// for(Cookie cookie : cookies) { +// logger.info("doPost() ==cookie== " + cookie.getName() + " == " + cookie.getValue()); +// } + + // handle AJAX requests here and send other requests on to the VPPA dispatcher + String isAjaxRequest = req.getParameter("ajaxRequest"); + if(isAjaxRequest != null && isAjaxRequest.trim().equalsIgnoreCase(Boolean.toString(true))) { + ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS); + if(params == null) { + params = new ParameterParser(req); + } + + SessionState state = getState(req); + + // Check whether this is an AJAX request expecting a JSON response and if it is + // dispatch the request to the buildJsonResponse() method, avoiding VPPA's + // html rendering. Other options might be HTML-fragment, XML, etc. + //String requestedMimetype = (String) toolSession.getAttribute(REQUESTED_MIMETYPE); + String requestedMimetype = params.getString(REQUESTED_MIMETYPE); + logger.info("doPost() requestedMimetype == " + requestedMimetype); + if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_JSON)) { + doPostJsonResponse(params, state, req, res); + } else if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_HTML)) { + doPostHtmlFragmentResponse(params, state, req, res); + } + + return; + } + super.doPost(req, res); + } + + protected void doPostHtmlFragmentResponse(ParameterParser params, + SessionState state, HttpServletRequest req, HttpServletResponse res) { + Map result = this.ensureCitationListExists(params, state, req, res); + + res.setCharacterEncoding(CHARSET_UTF8); + res.setContentType(MIMETYPE_HTML); + + String sakai_csrf_token = params.getString("sakai_csrf_token"); + if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) { + setVmReference("sakai_csrf_token", sakai_csrf_token, req); + } + + for(Map.Entry entry : result.entrySet()) { + setVmReference(entry.getKey(), entry.getValue(), req); + } + } + + protected void doPostJsonResponse(ParameterParser params, + SessionState state, HttpServletRequest req, HttpServletResponse res) { + + res.setCharacterEncoding(CHARSET_UTF8); + res.setContentType(MIMETYPE_JSON); + + Map jsonMap = new HashMap(); + String sakai_csrf_token = params.getString("sakai_csrf_token"); + if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) { + jsonMap.put("sakai_csrf_token", sakai_csrf_token); + } + + String citation_action = params.getString("citation_action"); + if(citation_action != null && citation_action.trim().equals(UPDATE_RESOURCE)) { + Map result = this.updateCitationList(params, state, req, res); + jsonMap.putAll(result); + } else { + Map result = this.createCitationList(params, state, req, res); + jsonMap.putAll(result); + } + + // convert to json string + String jsonString = JSONObject.fromObject(jsonMap).toString(); + try { + PrintWriter writer = res.getWriter(); + writer.print(jsonString); + writer.flush(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + protected Map createCitationList(ParameterParser params, + SessionState state, HttpServletRequest req, HttpServletResponse res) { + Map results = new HashMap(); + results.putAll(this.ensureCitationListExists(params, state, req, res)); + return results; + } + + protected Map updateCitationList(ParameterParser params, + SessionState state, HttpServletRequest req, HttpServletResponse res) { + Map results = new HashMap(); + + String resourceId = params.getString("resourceId"); + String message = null; + if(resourceId == null) { + results.putAll(this.ensureCitationListExists(params, state, req, res)); + } else { + try { + ContentResourceEdit edit = getContentService().editResource(resourceId); + this.captureDisplayName(params, state, edit, results); + this.captureAccess(params, state, edit, results); + this.captureAvailability(params, edit, results); + getContentService().commitResource(edit); + message = "Resource updated"; + } catch (IdUnusedException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (TypeException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (InUseException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (PermissionException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (OverQuotaException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (ServerOverloadException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (VirusFoundException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } + if(message != null && ! message.trim().equals("")) { + results.put("message", message); + } + } + return results; + } + + protected Map ensureCitationListExists(ParameterParser params, + SessionState state, HttpServletRequest req, HttpServletResponse res) { + Map results = new HashMap(); + String message = null; + + String displayName = params.getString("displayName"); + if(displayName == null) { + // error ?? + } + + CitationCollection cCollection = this.getCitationCollection(state, true); + + if(cCollection == null) { + // error + } else { + String citationCollectionId = cCollection.getId(); + + String collectionId = params.getString("collectionId"); + if(collectionId == null || collectionId.trim().equals("")) { + ToolSession toolSession = getSessionManager().getCurrentToolSession(); + ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); + collectionId = pipe.getContentEntity().getId(); + } + + ContentResource resource = null; + String resourceId = params.getString("resourceId"); + if(resourceId == null || resourceId.trim().equals("")) { + // create resource + if(collectionId == null) { + // error? + message = rb.getString("resource.null_collectionId.error"); + } else { + int priority = 0; + + // create resource + try { + ContentResourceEdit edit = getContentService().addResource(collectionId, displayName, null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); + edit.setResourceType(CitationService.CITATION_LIST_ID); + byte[] bytes = citationCollectionId.getBytes(); + edit.setContent(bytes ); + captureAccess(params, state, edit, results); + captureAvailability(params, edit, results); + ResourceProperties properties = edit.getPropertiesEdit(); + properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName); + + getContentService().commitResource(edit, priority); + resourceId = edit.getId(); + message = rb.getFormattedMessage("resource.new.success", new String[]{ displayName }); + } catch (IdUniquenessException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (IdLengthException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (IdInvalidException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (OverQuotaException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (ServerOverloadException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (PermissionException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } catch (IdUnusedException e) { + // TODO Auto-generated catch block + message = e.getMessage(); + e.printStackTrace(); + } + } + + + } else { + // get resource + // possibly revise displayName, other properties + // commit changes + // report success/failure + } + results.put("citationCollectionId", citationCollectionId); + results.put("resourceId", resourceId); + results.put("collectionId", collectionId); + } + results.put("message", message); + + return results; + } + + protected void captureDisplayName(ParameterParser params, SessionState state, + ContentResourceEdit edit, Map results) { + String displayName = params.getString("displayName"); + if(displayName == null || displayName.trim().equals("")) { + throw new RuntimeException("invalid name for resource: " + displayName); + } + String oldDisplayName = edit.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME); + if(oldDisplayName == null || ! oldDisplayName.equals(displayName)) { + ResourcePropertiesEdit props = edit.getPropertiesEdit(); + props.removeProperty(ResourceProperties.PROP_DISPLAY_NAME); + props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName); + results.put("displayName", displayName); + } + + } + + /** + * @param params + * @param edit + * @param results TODO + */ + protected void captureAvailability(ParameterParser params, + ContentResourceEdit edit, Map results) { + boolean hidden = params.getBoolean("hidden"); + boolean useReleaseDate = params.getBoolean("use_start_date"); + DateFormat df = DateFormat.getDateTimeInstance(); + Time releaseDate = null; + if(useReleaseDate) { + String releaseDateStr = params.getString(PROP_RELEASE_DATE); + if(releaseDateStr != null) { + try { + releaseDate = TimeService.newTime(df.parse(releaseDateStr).getTime()); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + Time retractDate = null; + boolean useRetractDate = params.getBoolean("use_end_date"); + if(useRetractDate) { + String retractDateStr = params.getString(PROP_RETRACT_DATE); + if(retractDateStr != null) { + try { + retractDate = TimeService.newTime(df.parse(retractDateStr).getTime()); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + boolean oldHidden = edit.isHidden(); + Time oldReleaseDate = edit.getReleaseDate(); + Time oldRetractDate = edit.getRetractDate(); + boolean changesFound = false; + if(oldHidden != hidden) { + results.put(PROP_IS_HIDDEN, Boolean.toString(hidden)); + changesFound = true; + } + if(oldReleaseDate == null && releaseDate == null) { + // no change here + } else if((oldReleaseDate == null) || ! oldReleaseDate.equals(releaseDate)) { + if(releaseDate == null) { + results.put(PROP_RELEASE_DATE_STR, df.format(new Date())); + } else { + results.put(PROP_RELEASE_DATE_STR, df.format(new Date(releaseDate.getTime()))); + } + results.put(PROP_RELEASE_DATE, releaseDate); + results.put(PROP_USE_RELEASE_DATE, useReleaseDate); + changesFound = true; + } + if(oldRetractDate == null && retractDate == null) { + // no change here + } else if (oldRetractDate == null || ! oldRetractDate.equals(retractDate)) { + if(retractDate == null) { + results.put(PROP_RETRACT_DATE_STR, df.format(new Date(System.currentTimeMillis() + ONE_WEEK))); + } else { + results.put(PROP_RETRACT_DATE_STR, df.format(new Date(retractDate.getTime() ))); + } + results.put(PROP_RETRACT_DATE, retractDate); + changesFound = true; + } + if(changesFound) { + edit.setAvailability(hidden, releaseDate, retractDate); + } + } + + protected void captureAccess(ParameterParser params, SessionState state, + ContentResourceEdit edit, Map results) { + + Map entityProperties = (Map) state.getAttribute(STATE_RESOURCE_ENTITY_PROPERTIES); + boolean changesFound = false; + String access_mode = params.getString("access_mode"); + if(access_mode == null) { + access_mode = AccessMode.INHERITED.toString(); + } + String oldAccessMode = entityProperties.get(PROP_ACCESS_MODE).toString(); + if(oldAccessMode == null) { + oldAccessMode = AccessMode.INHERITED.toString(); + } + if(! access_mode.equals(oldAccessMode)) { + results.put(PROP_ACCESS_MODE, AccessMode.fromString(access_mode)); + changesFound = true; + } + if(AccessMode.GROUPED.toString().equals(access_mode)) { + // we inherit more than one group and must check whether group access changes at this item + String[] access_groups = params.getStrings("access_groups"); + + SortedSet new_groups = new TreeSet(); + if(access_groups != null) { + new_groups.addAll(Arrays.asList(access_groups)); + } + + List> possibleGroups = (List>) entityProperties.get(PROP_POSSIBLE_GROUPS); + if(possibleGroups == null) { + possibleGroups = new ArrayList>(); + } + Map possibleGroupMap = mapGroupRefs(possibleGroups); + SortedSet new_group_refs = convertToRefs(new_groups, possibleGroupMap ); + + boolean groups_are_inherited = (new_groups.size() == possibleGroupMap.size()) && possibleGroupMap.keySet().containsAll(new_groups); + + try { + if(groups_are_inherited) { + edit.clearGroupAccess(); + edit.setGroupAccess(new_group_refs); + } else { + edit.setGroupAccess(new_group_refs); + } + edit.clearPublicAccess(); + } catch (InconsistentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (PermissionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } else if("public".equals(access_mode)) { + Boolean isPubviewInherited = (Boolean) entityProperties.get(PROP_IS_PUBVIEW_INHERITED); + if(isPubviewInherited == null || ! isPubviewInherited) { + try { + edit.setPublicAccess(); + } catch (InconsistentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (PermissionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } else if(AccessMode.INHERITED.toString().equals(access_mode)) { + try { + edit.clearGroupAccess(); + edit.clearPublicAccess(); + } catch (InconsistentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (PermissionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + // isPubview + results.put(PROP_IS_PUBVIEW, getContentService().isPubView(edit.getId())); + // isPubviewInherited + results.put(PROP_IS_PUBVIEW_INHERITED, new Boolean(getContentService().isInheritingPubView(edit.getId()))); + // isPubviewPossible + Boolean preventPublicDisplay = (Boolean) state.getAttribute("resources.request.prevent_public_display"); + if(preventPublicDisplay == null) { + preventPublicDisplay = Boolean.FALSE; + } + results.put(PROP_IS_PUBVIEW_POSSIBLE, new Boolean(! preventPublicDisplay.booleanValue())); + + // accessMode + results.put(PROP_ACCESS_MODE, edit.getAccess()); + // isGroupInherited + results.put(PROP_IS_GROUP_INHERITED, AccessMode.GROUPED == edit.getInheritedAccess()); + // possibleGroups + Collection inheritedGroupObjs = edit.getInheritedGroupObjects(); + Map> groups = new HashMap>(); + if(inheritedGroupObjs != null) { + for(Group group : inheritedGroupObjs) { + Map grp = new HashMap(); + grp.put("groupId", group.getId()); + grp.put("title", group.getTitle()); + grp.put("description", group.getDescription()); + grp.put("entityRef", group.getReference()); + groups.put(grp.get("groupId"), grp); + } + } + results.put(PROP_POSSIBLE_GROUPS, groups); + // isGroupPossible + results.put(PROP_IS_GROUP_POSSIBLE, new Boolean(groups != null && groups.size() > 0)); + // isSingleGroupInherited + results.put(PROP_IS_SINGLE_GROUP_INHERITED, new Boolean(groups != null && groups.size() == 1)); + // isSiteOnly = ! isPubviewPossible && ! isGroupPossible + results.put(PROP_IS_SITE_ONLY, new Boolean(preventPublicDisplay.booleanValue() && (groups == null || groups.size() < 1))); + // isUserSite + SiteService siteService = (SiteService) ComponentManager.get(SiteService.class); + Reference ref = getEntityManager().newReference(edit.getReference()); + results.put(PROP_IS_USER_SITE, siteService.isUserSite(ref.getContext())); + } + + private Map mapGroupRefs( + List> possibleGroups) { + + Map groupRefMap = new HashMap(); + for(Map groupInfo : possibleGroups) { + if(groupInfo.get("groupId") != null && groupInfo.get("entityRef") != null) { + groupRefMap.put(groupInfo.get("groupId"), groupInfo.get("entityRef")); + } + } + return groupRefMap ; + } + + public SortedSet convertToRefs(Collection groupIds, Map possibleGroupMap) + { + SortedSet groupRefs = new TreeSet(); + for(String groupId : groupIds) + { + String groupRef = possibleGroupMap.get(groupId); + if(groupRef != null) + { + groupRefs.add(groupRef); + } + } + return groupRefs; + + } + + protected void preserveEntityIds(ParameterParser params, SessionState state) { + String resourceId = params.getString("resourceId"); + String citationCollectionId = params.getString("citationCollectionId"); + + if(resourceId == null || resourceId.trim().equals("")) { + // do nothing + } else { + state.setAttribute(CitationHelper.RESOURCE_ID, resourceId); + } + + if(citationCollectionId == null || citationCollectionId.trim().equals("")) { + // do nothing + } else { + state.setAttribute(CitationHelper.CITATION_COLLECTION_ID, citationCollectionId); + } + + } + protected void putCitationCollectionDetails( Context context, SessionState state ) { // get the citation list title String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); - ContentHostingService contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); - String refStr = contentService.getReference(resourceId); - Reference ref = EntityManager.newReference(refStr); + String refStr = getContentService().getReference(resourceId); + Reference ref = getEntityManager().newReference(refStr); String collectionTitle = null; if( ref != null ) { @@ -608,11 +1176,11 @@ } if( collectionTitle != null && !collectionTitle.trim().equals("") ) { - context.put( "collectionTitle", Validator.escapeHtml(collectionTitle)); + context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle)); } // get the collection we're now working on - String collectionId = (String)state.getAttribute(STATE_COLLECTION_ID); + String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID); context.put( "collectionId", collectionId ); CitationCollection collection = getCitationCollection(state, false); @@ -641,6 +1209,7 @@ // validator context.put("xilator", new Validator()); + context.put("FORM_NAME", "importForm"); int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}); context.put("requestStateId", requestStateId); @@ -668,9 +1237,8 @@ // get the citation list title String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); - ContentHostingService contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); - String refStr = contentService.getReference(resourceId); - Reference ref = EntityManager.newReference(refStr); + String refStr = getContentService().getReference(resourceId); + Reference ref = getEntityManager().newReference(refStr); String collectionTitle = null; if( ref != null ) { @@ -681,16 +1249,16 @@ } if( collectionTitle != null && !collectionTitle.trim().equals("") ) { - context.put( "collectionTitle", Validator.escapeHtml(collectionTitle)); + context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle)); } // get the collection we're now working on - String collectionId = (String)state.getAttribute(STATE_COLLECTION_ID); + String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID); context.put( "collectionId", collectionId ); - CitationCollection collection = getCitationCollection(state, false); + CitationCollection citationCollection = getCitationCollection(state, false); int collectionSize = 0; - if(collection == null) + if(citationCollection == null) { logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + collectionId ); @@ -702,17 +1270,17 @@ else { // get the size of the list - collectionSize = collection.size(); + collectionSize = citationCollection.size(); } context.put( "collectionSize", new Integer( collectionSize ) ); Locale locale = rb.getLocale(); - List> saveciteClients = ConfigurationService.getSaveciteClientsForLocale(locale); + List> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale); if(saveciteClients != null) { for(Map client : saveciteClients) { - String saveciteUrl = SearchManager.getSaveciteUrl(contentService.getUuid(resourceId),client.get("id")); + String saveciteUrl = getSearchManager().getSaveciteUrl(getContentService().getUuid(resourceId),client.get("id")); try { client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8")); } catch (UnsupportedEncodingException e) { @@ -726,9 +1294,9 @@ // determine which features to display - if( ConfigurationService.isGoogleScholarEnabled() ) + if( getConfigurationService().isGoogleScholarEnabled() ) { - String googleUrl = SearchManager.getGoogleScholarUrl(contentService.getUuid(resourceId)); + String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId)); context.put( "googleUrl", googleUrl ); // object array for formatted messages @@ -736,7 +1304,7 @@ context.put( "googleArgs", googleArgs ); } - if( ConfigurationService.librarySearchEnabled() ) + if( getConfigurationService().librarySearchEnabled() ) { context.put( "searchLibrary", Boolean.TRUE ); } @@ -775,10 +1343,10 @@ context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM); - List schemas = CitationService.getSchemas(); + List schemas = getCitationService().getSchemas(); context.put("TEMPLATES", schemas); - Schema defaultSchema = CitationService.getDefaultSchema(); + Schema defaultSchema = getCitationService().getDefaultSchema(); context.put("DEFAULT_TEMPLATE", defaultSchema); // Object array for instruction message @@ -875,11 +1443,11 @@ context.put("citation", citation); String citationId = (String) state.getAttribute(CitationHelper.CITATION_EDIT_ID); - String collectionId = (String) state.getAttribute(STATE_COLLECTION_ID); + String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID); context.put("citationId", citationId); context.put("collectionId", collectionId); - List schemas = CitationService.getSchemas(); + List schemas = getCitationService().getSchemas(); context.put("TEMPLATES", schemas); context.put("DEFAULT_TEMPLATE", citation.getSchema()); @@ -949,9 +1517,8 @@ // get the citation list title String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); - ContentHostingService contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); - String refStr = contentService.getReference(resourceId); - Reference ref = EntityManager.newReference(refStr); + String refStr = getContentService().getReference(resourceId); + Reference ref = getEntityManager().newReference(refStr); String collectionTitle = null; if( ref != null ) { @@ -962,10 +1529,10 @@ } if( collectionTitle != null && !collectionTitle.trim().equals("") ) { - context.put( "collectionTitle", Validator.escapeHtml(collectionTitle)); + context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle)); } - context.put("openUrlLabel", ConfigurationService.getSiteConfigOpenUrlLabel()); + context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel()); context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM); @@ -1026,7 +1593,7 @@ /* * Object arrays for formatted messages */ - Object[] instrMainArgs = { ConfigurationService.getSiteConfigOpenUrlLabel() }; + Object[] instrMainArgs = { getConfigurationService().getSiteConfigOpenUrlLabel() }; context.put( "instrMainArgs", instrMainArgs ); Object[] instrSubArgs = { rb.getString( "label.finish" ) }; @@ -1068,37 +1635,37 @@ */ protected CitationCollection getCitationCollection(SessionState state, boolean create) { - CitationCollection collection = (CitationCollection) state.getAttribute(STATE_COLLECTION); - if(collection == null) + CitationCollection citationCollection = (CitationCollection) state.getAttribute(STATE_CITATION_COLLECTION); + if(citationCollection == null) { - String collectionId = (String) state.getAttribute(STATE_COLLECTION_ID); - if(collectionId == null && create) + String citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID); + if(citationCollectionId == null && create) { - collection = CitationService.addCollection(); - state.setAttribute(STATE_COLLECTION_ID, collection.getId()); + citationCollection = getCitationService().addCollection(); + getCitationService().save(citationCollection); } else { try { - collection = CitationService.getCollection(collectionId); + citationCollection = getCitationService().getCollection(citationCollectionId); } catch (IdUnusedException e) { - logger.warn("IdUnusedException: CitationHelperAction.getCitationCollection() unable to access citationCollection " + collectionId); + logger.warn("IdUnusedException: CitationHelperAction.getCitationCollection() unable to access citationCollection " + citationCollectionId); } - if(collection == null && create) + if(citationCollection == null && create) { - collection = CitationService.addCollection(); - state.setAttribute(STATE_COLLECTION_ID, collection.getId()); + citationCollection = getCitationService().addCollection(); + getCitationService().save(citationCollection); } } - if(collection != null) - { - state.setAttribute(STATE_COLLECTION, collection); + if(citationCollection != null) { + state.setAttribute(STATE_CITATION_COLLECTION, citationCollection); + state.setAttribute(STATE_CITATION_COLLECTION_ID, citationCollection.getId()); } } - return collection; + return citationCollection; } /** @@ -1108,6 +1675,7 @@ */ public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) { + logger.debug("buildMainPanelContext()"); // always put appropriate bundle in velocity context context.put("tlang", rb); @@ -1130,7 +1698,8 @@ { // mode really shouldn't be null here logger.warn( "buildMainPanelContext() getting null Mode from state" ); - mode = Mode.ADD_CITATIONS; + mode = Mode.NEW_RESOURCE; + //mode = Mode.ADD_CITATIONS; setMode(state, mode); } @@ -1139,6 +1708,9 @@ switch(mode) { + case NEW_RESOURCE: + template = buildNewResourcePanelContext(portlet, context, rundata, state); + break; case IMPORT_CITATIONS: template = buildImportCitationsPanelContext(portlet, context, rundata, state); break; @@ -1181,6 +1753,211 @@ } // buildMainPanelContext + public String buildNewResourcePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) { + + logger.debug("buildNewResourcePanelContext()"); + + context.put("MIMETYPE_JSON", MIMETYPE_JSON); + context.put("REQUESTED_MIMETYPE", REQUESTED_MIMETYPE); + + context.put("xilator", new Validator()); + + context.put("availability_is_enabled", Boolean.TRUE); + context.put("GROUP_ACCESS", AccessMode.GROUPED); + context.put("INHERITED_ACCESS", AccessMode.INHERITED); + + Boolean resourceAdd = (Boolean) state.getAttribute(STATE_RESOURCES_ADD); + if(resourceAdd != null && resourceAdd.equals(true)) { + context.put("resourceAdd", Boolean.TRUE); + context.put(CITATION_ACTION, CREATE_RESOURCE); + } else { + context.put(CITATION_ACTION, UPDATE_RESOURCE); + } + + // resource-related + String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); + String citationCollectionId = null; + ContentResource resource = null; + Map contentProperties = null; + if(resourceId == null) { + } else { + try { + resource = getContentService().getResource(resourceId); + } catch (IdUnusedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (TypeException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (PermissionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + +// String guid = getContentService().getUuid(resourceId); +// context.put("RESOURCE_ID", guid); + } + + if(resource == null) { + context.put(CITATION_ACTION, CREATE_RESOURCE); + + ToolSession toolSession = getSessionManager().getCurrentToolSession(); + ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); + String collectionId = pipe.getContentEntity().getId(); + ContentCollection collection; + try { + collection = getContentService().getCollection(collectionId); + contentProperties = this.getProperties(collection, state); + } catch (IdUnusedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (TypeException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (PermissionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } else { + ResourceProperties props = resource.getProperties(); + contentProperties = this.getProperties(resource, state); + context.put("resourceTitle", props.getProperty(ResourceProperties.PROP_DISPLAY_NAME)); + context.put("resourceId", resourceId); + try { + citationCollectionId = new String(resource.getContent()); + } catch (ServerOverloadException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + context.put(CITATION_ACTION, UPDATE_RESOURCE); + } + if(contentProperties == null) { + contentProperties = new HashMap(); + } + context.put("contentProperties", contentProperties); + int collectionSize = 0; + CitationCollection citationCollection = null; + if(citationCollectionId == null) { + citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID); + //String citationCollectionId = (String) state.getAttribute(CitationHelper.CITATION_COLLECTION_ID); + } + if(citationCollectionId == null) { + + } else { + citationCollection = getCitationCollection(state, true); + if(citationCollection == null) { + logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + citationCollectionId ); + + int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}); + context.put("requestStateId", requestStateId); + + return TEMPLATE_ERROR; + } else { + // get the size of the list + collectionSize = citationCollection.size(); + } + context.put("collectionId", citationCollectionId); + } + context.put( "collectionSize", new Integer( collectionSize ) ); + + + Locale locale = rb.getLocale(); + List> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale); + + if(saveciteClients != null) { + for(Map client : saveciteClients) { + String saveciteUrl = getSearchManager().getSaveciteUrl(getContentService().getUuid(resourceId),client.get("id")); + try { + client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8")); + } catch (UnsupportedEncodingException e) { + logger.warn("Error encoding savecite URL",e); + } + + } + + context.put("saveciteClients",saveciteClients); + } + + // determine which features to display + if( getConfigurationService().isGoogleScholarEnabled() ) { + String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId)); + context.put( "googleUrl", googleUrl ); + + // object array for formatted messages + Object[] googleArgs = { rb.getString( "linkLabel.google" ) }; + context.put( "googleArgs", googleArgs ); + } + + if( getConfigurationService().librarySearchEnabled() ) { + context.put( "searchLibrary", Boolean.TRUE ); + } + + if(citationCollection == null || citationCollection.size() <= 0) { + + } else { + context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel()); + + //context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM); + + // collection size + context.put( "collectionSize", new Integer( citationCollection.size() ) ); + + // export URLs + String exportUrlSel = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL); + String exportUrlAll = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL); + context.put("exportUrlSel", exportUrlSel); + context.put("exportUrlAll", exportUrlAll); + + Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE); + if(listPageSize == null) + { + listPageSize = DEFAULT_LIST_PAGE_SIZE; + state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize); + } + context.put("listPageSize", listPageSize); + + CitationIterator newIterator = citationCollection.iterator(); + CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR); + if(oldIterator != null) + { + newIterator.setPageSize(listPageSize.intValue()); + newIterator.setStart(oldIterator.getStart()); +// newIterator.setPage(oldIterator.getPage()); + } + context.put("citations", newIterator); + context.put("citationCollectionId", citationCollection.getId()); + if(! citationCollection.isEmpty()) + { + context.put("show_citations", Boolean.TRUE); + +// int page = newIterator.getPage(); +// int pageSize = newIterator.getPageSize(); + int totalSize = citationCollection.size(); + + int start = newIterator.getStart(); + int end = newIterator.getEnd(); +// int start = page * pageSize + 1; +// int end = Math.min((page + 1) * pageSize, totalSize); + + Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)}; + String showing = (String) rb.getFormattedMessage("showing.results", position); + context.put("showing", showing); + } + state.setAttribute(STATE_LIST_ITERATOR, newIterator); + + // constant schema identifier + context.put( "titleProperty", Schema.TITLE ); + + int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}); + context.put("requestStateId", requestStateId); + + + } + + return TEMPLATE_NEW_RESOURCE; + } + /** * @param portlet * @param context @@ -1196,7 +1973,7 @@ context.put( "citationId", state.getAttribute( STATE_CITATION_ID ) ); // get the collection we're now working on - String collectionId = (String)state.getAttribute(STATE_COLLECTION_ID); + String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID); context.put( "collectionId", collectionId ); int size = 0; @@ -1311,7 +2088,7 @@ context.put(PARAM_FORM_NAME, ELEMENT_ID_RESULTS_FORM); // OpenURL Label - context.put( "openUrlLabel", ConfigurationService.getSiteConfigOpenUrlLabel() ); + context.put( "openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel() ); // object arrays for formatted messages Object[] instrMainArgs = { rb.getString( "add.results" ) }; @@ -1398,8 +2175,7 @@ // resource-related String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); - ContentHostingService contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); - String guid = contentService.getUuid(resourceId); + String guid = getContentService().getUuid(resourceId); context.put("RESOURCE_ID", guid); // category information from hierarchy @@ -1428,7 +2204,7 @@ context.put(PARAM_FORM_NAME, ELEMENT_ID_SEARCH_FORM); // OpenURL Label - context.put( "openUrlLabel", ConfigurationService.getSiteConfigOpenUrlLabel() ); + context.put( "openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel() ); // object arrays for formatted messages Object[] instrArgs = { rb.getString( "submit.search" ) }; @@ -1486,11 +2262,11 @@ context.put("citation", citation); String citationId = (String) state.getAttribute(CitationHelper.CITATION_VIEW_ID); - String collectionId = (String) state.getAttribute(STATE_COLLECTION_ID); + String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID); context.put("citationId", citationId); context.put("collectionId", collectionId); - List schemas = CitationService.getSchemas(); + List schemas = getCitationService().getSchemas(); context.put("TEMPLATES", schemas); context.put("DEFAULT_TEMPLATE", citation.getSchema()); @@ -1545,7 +2321,7 @@ public void doFinish ( RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); - ToolSession toolSession = SessionManager.getCurrentToolSession(); + ToolSession toolSession = getSessionManager().getCurrentToolSession(); ParameterParser params = data.getParameters(); int requestStateId = params.getInt("requestStateId", 0); @@ -1564,116 +2340,120 @@ int citationCount = 0; - if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE) - { - /* PIPE remove */ -// SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); - - // delete the temporary resource - String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); - ContentHostingService contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); - ContentResource tempResource = null; - try - { - // get the temp resource - tempResource = contentService.getResource(temporaryResourceId); - - // use the temp resource to 'create' the real resource - pipe.setRevisedContent(tempResource.getContent()); - - // remove the temp resource - if( CitationService.allowRemoveCitationList( temporaryResourceId ) ) - { - // setup a SecurityAdvisor - CitationListSecurityAdviser advisor = new CitationListSecurityAdviser( - SessionManager.getCurrentSessionUserId(), - ContentHostingService.AUTH_RESOURCE_REMOVE_ANY, - tempResource.getReference() ); - - try { - SecurityService.pushAdvisor(advisor); - - // remove temp resource - contentService.removeResource(temporaryResourceId); - } catch(Exception e) { - logger.warn("Exception removing temporary resource for a citation list: " + temporaryResourceId + " --> " + e); - } finally { - // pop advisor - SecurityService.popAdvisor(); - } - - tempResource = null; - } - } - catch (PermissionException e) - { - // TODO Auto-generated catch block - logger.warn("PermissionException ", e); - } - catch (IdUnusedException e) - { - // TODO Auto-generated catch block - logger.warn("IdUnusedException ", e); - } - catch (TypeException e) - { - // TODO Auto-generated catch block - logger.warn("TypeException ", e); - } -// catch (InUseException e) -// { +// if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE_BY_HELPER) +// { +// /* PIPE remove */ +//// SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); +// +// SecurityService securityService = (SecurityService) ComponentManager.get(SecurityService.class); +// // delete the temporary resource +// String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); +// ContentResource tempResource = null; +// try +// { +// // get the temp resource +// tempResource = getContentService().getResource(temporaryResourceId); +// +// // use the temp resource to 'create' the real resource +// pipe.setRevisedContent(tempResource.getContent()); +// +// // remove the temp resource +// if( getCitationService().allowRemoveCitationList( temporaryResourceId ) ) +// { +// // setup a SecurityAdvisor +// CitationListSecurityAdviser advisor = new CitationListSecurityAdviser( +// getSessionManager().getCurrentSessionUserId(), +// ContentHostingService.AUTH_RESOURCE_REMOVE_ANY, +// tempResource.getReference() ); +// +// try { +// securityService.pushAdvisor(advisor); +// +// // remove temp resource +// getContentService().removeResource(temporaryResourceId); +// } catch(Exception e) { +// logger.warn("Exception removing temporary resource for a citation list: " + temporaryResourceId + " --> " + e); +// } finally { +// // pop advisor +// securityService.popAdvisor(advisor); +// } +// +// tempResource = null; +// } +// } +// catch (PermissionException e) +// { // // TODO Auto-generated catch block -// logger.warn("InUseException ", e); -// } - catch (ServerOverloadException e) - { - // TODO Auto-generated catch block - logger.warn("ServerOverloadException ", e); - } - catch (Exception e) - { - // TODO Auto-generated catch block - logger.warn("Exception ", e); - } - } +// logger.warn("PermissionException ", e); +// } +// catch (IdUnusedException e) +// { +// // TODO Auto-generated catch block +// logger.warn("IdUnusedException ", e); +// } +// catch (TypeException e) +// { +// // TODO Auto-generated catch block +// logger.warn("TypeException ", e); +// } +//// catch (InUseException e) +//// { +//// // TODO Auto-generated catch block +//// logger.warn("InUseException ", e); +//// } +// catch (ServerOverloadException e) +// { +// // TODO Auto-generated catch block +// logger.warn("ServerOverloadException ", e); +// } +// catch (Exception e) +// { +// // TODO Auto-generated catch block +// logger.warn("Exception ", e); +// } +// } - // set content (mime) type - pipe.setRevisedMimeType(ResourceType.MIME_TYPE_HTML); - pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML); +// // set content (mime) type +// pipe.setRevisedMimeType(ResourceType.MIME_TYPE_HTML); +// pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML); +// +// // set the alternative_reference to point to reference_root for CitationService +// pipe.setRevisedResourceProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT); - // set the alternative_reference to point to reference_root for CitationService - pipe.setRevisedResourceProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, org.sakaiproject.citation.api.CitationService.REFERENCE_ROOT); - /* PIPE remove */ // SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); // get the collection we're now working on CitationCollection collection = getCitationCollection(state, true); + if(collection == null) { + // error + } else { + + String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID); + + String[] args = new String[]{ Integer.toString(collection.size()) }; + String size_str = rb.getFormattedMessage("citation.count", args); + pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_LENGTH, size_str); + + // leave helper mode + pipe.setActionCanceled(false); + pipe.setErrorEncountered(false); + pipe.setActionCompleted(true); + + toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); + toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED); + + cleanup(toolSession, CitationHelper.CITATION_PREFIX, state); + + // Remove session sort + state.removeAttribute("sort"); + + // Remove session collection + state.removeAttribute(STATE_CITATION_COLLECTION_ID); + state.removeAttribute(STATE_CITATION_COLLECTION); + + state.removeAttribute("fromListPage"); + } - String collectionId = (String) state.getAttribute(STATE_COLLECTION_ID); - - String[] args = new String[]{ Integer.toString(collection.size()) }; - String size_str =rb.getFormattedMessage("citation.count", args); - pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_LENGTH, size_str); - - // leave helper mode - pipe.setActionCanceled(false); - pipe.setErrorEncountered(false); - pipe.setActionCompleted(true); - - toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); - toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED); - - cleanup(toolSession, CitationHelper.CITATION_PREFIX, state); - - // Remove session sort - state.removeAttribute("sort"); - - // Remove session collection - state.removeAttribute(STATE_COLLECTION_ID); - state.removeAttribute(STATE_COLLECTION); - - state.removeAttribute("fromListPage"); - } // doFinish /** @@ -1682,7 +2462,7 @@ public void doCancel(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); - ToolSession toolSession = SessionManager.getCurrentToolSession(); + ToolSession toolSession = getSessionManager().getCurrentToolSession(); ParameterParser params = data.getParameters(); int requestStateId = params.getInt("requestStateId", 0); @@ -1699,45 +2479,44 @@ return; } - if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE) + if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE_BY_HELPER) { // TODO: delete the citation collection and all citations // TODO: delete the temporary resource - String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); - ContentHostingService contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); - ContentResourceEdit edit = null; - try - { - edit = contentService.editResource(temporaryResourceId); - contentService.removeResource(edit); - edit = null; - } - catch (PermissionException e) - { - // TODO Auto-generated catch block - logger.warn("PermissionException ", e); - } - catch (IdUnusedException e) - { - // TODO Auto-generated catch block - logger.warn("IdUnusedException ", e); - } - catch (TypeException e) - { - // TODO Auto-generated catch block - logger.warn("TypeException ", e); - } - catch (InUseException e) - { - // TODO Auto-generated catch block - logger.warn("InUseException ", e); - } - - if(edit != null) - { - contentService.cancelResource(edit); - } +// String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID); +// ContentResourceEdit edit = null; +// try +// { +// edit = getContentService().editResource(temporaryResourceId); +// getContentService().removeResource(edit); +// edit = null; +// } +// catch (PermissionException e) +// { +// // TODO Auto-generated catch block +// logger.warn("PermissionException ", e); +// } +// catch (IdUnusedException e) +// { +// // TODO Auto-generated catch block +// logger.warn("IdUnusedException ", e); +// } +// catch (TypeException e) +// { +// // TODO Auto-generated catch block +// logger.warn("TypeException ", e); +// } +// catch (InUseException e) +// { +// // TODO Auto-generated catch block +// logger.warn("InUseException ", e); +// } +// +// if(edit != null) +// { +// getContentService().cancelResource(edit); +// } } // leave helper mode @@ -1781,20 +2560,25 @@ } CitationCollection permCollection = getCitationCollection(state, true); - for(int i = 0; i < citationIds.length; i++) - { - try + if(permCollection == null) { + // error + } else { + + for(int i = 0; i < citationIds.length; i++) { - Citation citation = tempCollection.getCitation(citationIds[i]); - citation.setAdded(true); - permCollection.add(citation); + try + { + Citation citation = tempCollection.getCitation(citationIds[i]); + citation.setAdded(true); + permCollection.add(citation); + } + catch(IdUnusedException ex) + { + logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId); + } } - catch(IdUnusedException ex) - { - logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId); - } + getCitationService().save(permCollection); } - CitationService.save(permCollection); // setMode(state, Mode.LIST); } @@ -1825,21 +2609,26 @@ } CitationCollection permCollection = getCitationCollection(state, true); - for(int i = 0; i < citationIds.length; i++) - { - try + if(permCollection == null) { + // error + } else { + for(int i = 0; i < citationIds.length; i++) { - Citation citation = tempCollection.getCitation(citationIds[i]); - citation.setAdded(false); - permCollection.remove(citation); + try + { + Citation citation = tempCollection.getCitation(citationIds[i]); + citation.setAdded(false); + permCollection.remove(citation); + } + catch(IdUnusedException ex) + { + logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId); + } } - catch(IdUnusedException ex) - { - logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId); - } + getCitationService().save(permCollection); } - CitationService.save(permCollection); - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } public void doDatabasePopulate( RunData data ) @@ -1886,6 +2675,8 @@ int requestStateId = params.getInt("requestStateId", 0); restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); + + this.preserveEntityIds(params, state); setMode(state, Mode.IMPORT_CITATIONS); @@ -1906,6 +2697,8 @@ int requestStateId = params.getInt("requestStateId", 0); restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); + this.preserveEntityIds(params, state); + Iterator iter = params.getNames(); String param = null; @@ -1921,170 +2714,187 @@ if(collectionId == null) { - collectionId = (String) state.getAttribute(STATE_COLLECTION_ID); + collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID); } CitationCollection collection = null; collection = getCitationCollection(state, false); - - String ristext = params.get("ristext"); - - // We're going to read the RIS file from the submitted form's textarea first. If that's - // empty we'll read it from the uploaded file. We'll crate a BufferedReader in either - // circumstance so that the parsing code need not know where the ris text came from. - java.io.BufferedReader bread = null; - - if (ristext.trim().length() > 0) // form has text in the risimport textarea - { - java.io.StringReader risStringReader = new java.io.StringReader(ristext); - bread = new java.io.BufferedReader(risStringReader); - logger.debug( "String buffered reader ready"); - - } // end RIS text is in the textarea - else // textarea empty, set the read of the import from the file - { - String upload = params.get("risupload"); - logger.debug( "Upload String = " + upload); - - FileItem risImport = params.getFileItem("risupload"); - - if (risImport == null) - { - logger.debug( "risImport is null."); - return; - } - - logger.debug("Filename = " + risImport.getFileName()); - - - InputStream risImportStream = risImport.getInputStream(); - -/* - // Let's try to use UTF-8 encoding - - InputStreamReader isr = null; - - try - { - isr = new InputStreamReader(risImportStream, "UTF-8"); - } - catch(UnsupportedEncodingException e) - { - logger.warn("doImport() - could not set codeset to UTF-8"); - - } - - // For some reason we couldn't create a UTF-8 enabled InputStreamReader. Fall back - // to just a default InputStreamReader - - if (isr == null) - { - isr = new InputStreamReader(risImportStream); - } - - bread = new java.io.BufferedReader(isr); - } // end set the read of the import from the uploaded file. -*/ - - // below is needed if UTF-8 above is commented out - InputStreamReader isr = new InputStreamReader(risImportStream); - bread = new java.io.BufferedReader(isr); - } // end set the read of the import from the uploaded file. - - // The below code is a major work in progress. - // This code is for demonstration purposes only. No gambling or production use! - - StringBuilder fileString = new StringBuilder(); - String importLine = null; - java.util.List importList = new java.util.ArrayList(); - - // Read the BufferedReader and populate the importList. Each entry in the list - // is a line in the RIS import "file". - try - { - while ((importLine = bread.readLine()) != null) + if(collection == null) { + // error + } else { + String ristext = params.get("ristext"); + + // We're going to read the RIS file from the submitted form's textarea first. If that's + // empty we'll read it from the uploaded file. We'll crate a BufferedReader in either + // circumstance so that the parsing code need not know where the ris text came from. + java.io.BufferedReader bread = null; + + if (ristext.trim().length() > 0) // form has text in the risimport textarea { - importLine = importLine.trim(); - - if (importLine != null && importLine.length() > 2) + java.io.StringReader risStringReader = new java.io.StringReader(ristext); + bread = new java.io.BufferedReader(risStringReader); + logger.debug( "String buffered reader ready"); + + } // end RIS text is in the textarea + else // textarea empty, set the read of the import from the file + { + String upload = params.get("risupload"); + logger.debug( "Upload String = " + upload); + + FileItem risImport = params.getFileItem("risupload"); + + if (risImport == null) + { + logger.debug( "risImport is null."); + return; + } + + logger.debug("Filename = " + risImport.getFileName()); + + + InputStream risImportStream = risImport.getInputStream(); + + /* + // Let's try to use UTF-8 encoding + + InputStreamReader isr = null; + + try + { + isr = new InputStreamReader(risImportStream, "UTF-8"); + } + catch(UnsupportedEncodingException e) + { + logger.warn("doImport() - could not set codeset to UTF-8"); + + } + + // For some reason we couldn't create a UTF-8 enabled InputStreamReader. Fall back + // to just a default InputStreamReader + + if (isr == null) + { + isr = new InputStreamReader(risImportStream); + } + + bread = new java.io.BufferedReader(isr); + } // end set the read of the import from the uploaded file. + */ + + // below is needed if UTF-8 above is commented out + InputStreamReader isr = new InputStreamReader(risImportStream); + bread = new java.io.BufferedReader(isr); + } // end set the read of the import from the uploaded file. + + // The below code is a major work in progress. + // This code is for demonstration purposes only. No gambling or production use! + + StringBuilder fileString = new StringBuilder(); + String importLine = null; + java.util.List importList = new java.util.ArrayList(); + + // Read the BufferedReader and populate the importList. Each entry in the list + // is a line in the RIS import "file". + try + { + while ((importLine = bread.readLine()) != null) { - importList.add(importLine); - if(logger.isDebugEnabled()) { - fileString.append("\n"); - fileString.append(importLine); - } - } - - } // end while - } // end try - catch(Exception e) - { - logger.debug("ISR error = " + e); - } // end catch - finally { - if (bread != null) { - try { - bread.close(); - } catch (IOException e) { - // tried - } - } - } - - if(logger.isDebugEnabled()) { - logger.debug("fileString = \n" + fileString.toString()); - } - - - // tempList holds the entries read in to make a citation up to and - // including the ER entry from importList - List tempList = new java.util.ArrayList(); - - Citation importCitation = CitationService.getTemporaryCitation(); - CitationCollection importCollection = CitationService.getTemporaryCollection(); - - int sucessfullyReadCitations = 0; - int totalNumberCitations = 0; - - // Read each entry in the RIS List and build a citation - for(int i=0; i< importList.size(); i++) - { - String importEntryString = (String) importList.get(i); -// logger.debug("Import line (#1) = " + importEntryString); -// logger.debug("Substring is = " + importEntryString.substring(0, 2)); - tempList.add(importEntryString); - - // make sure importEntryString can be tested for "ER" existence. It could - // be a dinky invalid line less than 2 characters. - if (importEntryString != null && importEntryString.length() > 1 && - importEntryString.substring(0, 2).equalsIgnoreCase("ER")) + importLine = importLine.trim(); + + if (importLine != null && importLine.length() > 2) + { + importList.add(importLine); + if(logger.isDebugEnabled()) { + fileString.append("\n"); + fileString.append(importLine); + } + } + + } // end while + } // end try + catch(Exception e) { - // end of citation (signaled by ER). - - totalNumberCitations++; - logger.debug("------> Trying to add citation " + totalNumberCitations); - if (importCitation.importFromRisList(tempList)) // import went well + logger.debug("ISR error = " + e); + } // end catch + finally { + if (bread != null) { + try { + bread.close(); + } catch (IOException e) { + // tried + } + } + } + + if(logger.isDebugEnabled()) { + logger.debug("fileString = \n" + fileString.toString()); + } + + + // tempList holds the entries read in to make a citation up to and + // including the ER entry from importList + List tempList = new java.util.ArrayList(); + + Citation importCitation = getCitationService().getTemporaryCitation(); + CitationCollection importCollection = getCitationService().getTemporaryCollection(); + + int sucessfullyReadCitations = 0; + int totalNumberCitations = 0; + + // Read each entry in the RIS List and build a citation + for(int i=0; i< importList.size(); i++) + { + String importEntryString = (String) importList.get(i); + // logger.debug("Import line (#1) = " + importEntryString); + // logger.debug("Substring is = " + importEntryString.substring(0, 2)); + tempList.add(importEntryString); + + // make sure importEntryString can be tested for "ER" existence. It could + // be a dinky invalid line less than 2 characters. + if (importEntryString != null && importEntryString.length() > 1 && + importEntryString.substring(0, 2).equalsIgnoreCase("ER")) { - importCollection.add(importCitation); - sucessfullyReadCitations++; + // end of citation (signaled by ER). + + totalNumberCitations++; + logger.debug("------> Trying to add citation " + totalNumberCitations); + if (importCitation.importFromRisList(tempList)) // import went well + { + importCollection.add(importCitation); + sucessfullyReadCitations++; + } + tempList.clear(); + importCitation = getCitationService().getTemporaryCitation(); } - tempList.clear(); - importCitation = CitationService.getTemporaryCitation(); - } - } // end for + } // end for + logger.debug("Done reading in " + sucessfullyReadCitations + " / " + totalNumberCitations + " citations."); + collection.addAll(importCollection); + } - logger.debug("Done reading in " + sucessfullyReadCitations + " / " + totalNumberCitations + " citations."); + getCitationService().save(collection); - collection.addAll(importCollection); - CitationService.save(collection); - // remove collection from state - state.removeAttribute(STATE_COLLECTION); + state.removeAttribute(STATE_CITATION_COLLECTION); - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } // end doImport() + + public void doCreateResource(RunData data) + { + // get the state object + SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); + ParameterParser params = data.getParameters(); + int requestStateId = params.getInt("requestStateId", 0); + restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); + + setMode(state, Mode.NEW_RESOURCE); + //state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID); + + } + /** * */ @@ -2146,23 +2956,26 @@ int requestStateId = params.getInt("requestStateId", 0); restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); - Set validPropertyNames = CitationService.getValidPropertyNames(); + Set validPropertyNames = getCitationService().getValidPropertyNames(); String mediatype = params.getString("type"); CitationCollection collection = getCitationCollection(state, true); - - // create a citation - Citation citation = CitationService.addCitation(mediatype); - - updateCitationFromParams(citation, params); - - // add citation to current collection - collection.add(citation); - CitationService.save(collection); - + if(collection == null) { + // error + } else { + // create a citation + Citation citation = getCitationService().addCitation(mediatype); + + updateCitationFromParams(citation, params); + + // add citation to current collection + collection.add(citation); + getCitationService().save(collection); + } // call buildListPanelContext to show updated list //state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID); - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } // doCreateCitation @@ -2306,28 +3119,32 @@ CitationCollection collection = getCitationCollection(state, true); + if(collection == null) { + // error + } else { + + Citation citation = null; + try + { + citation = collection.getCitation(citationId); + } + catch (IdUnusedException e) + { + // add an alert (below) + } + + if(citation == null) + { + addAlert(state, rb.getString("alert.access")); + } + else + { + state.setAttribute(CitationHelper.CITATION_EDIT_ID, citationId); + state.setAttribute(CitationHelper.CITATION_EDIT_ITEM, citation); + setMode(state, Mode.EDIT); + } + } - Citation citation = null; - try - { - citation = collection.getCitation(citationId); - } - catch (IdUnusedException e) - { - // add an alert (below) - } - - if(citation == null) - { - addAlert(state, rb.getString("alert.access")); - } - else - { - state.setAttribute(CitationHelper.CITATION_EDIT_ID, citationId); - state.setAttribute(CitationHelper.CITATION_EDIT_ITEM, citation); - setMode(state, Mode.EDIT); - } - } // doEdit /** @@ -2342,7 +3159,8 @@ int requestStateId = params.getInt("requestStateId", 0); restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } // doList @@ -2363,15 +3181,20 @@ */ public void doAddCitations ( RunData data) { + logger.debug("doAddCitations()"); // get the state object SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters(); int requestStateId = params.getInt("requestStateId", 0); restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); + preserveEntityIds(params, state); + + //setMode(state, Mode.ADD_CITATIONS); + setMode(state, Mode.NEW_RESOURCE); + + logger.debug("doAddCitations()"); - setMode(state, Mode.ADD_CITATIONS); - } // doAddCitations public void doMessageFrame(RunData data) @@ -2433,35 +3256,34 @@ // get CitationCollection using collectionId CitationCollection collection = getCitationCollection(state, false); - if(collection == null) - { + if(collection == null) { logger.warn( "doMessageFrame() unable to access citationCollection " + collectionId ); - } + } else { - // do operation - if(operation.equalsIgnoreCase("add")) - { - logger.debug("adding citation " + citationId + " to " + collectionId); - citation.setAdded( true ); - collection.add( citation ); - CitationService.save(collection); + // do operation + if(operation.equalsIgnoreCase("add")) + { + logger.debug("adding citation " + citationId + " to " + collectionId); + citation.setAdded( true ); + collection.add( citation ); + getCitationService().save(collection); + } + else if(operation.equalsIgnoreCase("remove")) + { + logger.debug("removing citation " + citationId + " from " + collectionId); + collection.remove( citation ); + citation.setAdded( false ); + getCitationService().save(collection); + } + else + { + // do nothing + logger.debug("null operation: " + operation); + } + + // store the citation's new id to send back to UI + state.setAttribute( STATE_CITATION_ID, citation.getId() ); } - else if(operation.equalsIgnoreCase("remove")) - { - logger.debug("removing citation " + citationId + " from " + collectionId); - collection.remove( citation ); - citation.setAdded( false ); - CitationService.save(collection); - } - else - { - // do nothing - logger.debug("null operation: " + operation); - } - - // store the citation's new id to send back to UI - state.setAttribute( STATE_CITATION_ID, citation.getId() ); - setMode(state, Mode.MESSAGE); } @@ -2494,11 +3316,12 @@ { collection.remove( citation ); } - CitationService.save(collection); + getCitationService().save(collection); } } - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } // doRemoveAllCitations @@ -2536,7 +3359,7 @@ Citation citation = collection.getCitation(citationId); collection.remove(citation); } - CitationService.save(collection); + getCitationService().save(collection); } catch( IdUnusedException e ) { @@ -2546,7 +3369,8 @@ } state.setAttribute( STATE_LIST_NO_SCROLL, Boolean.TRUE ); - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } // doRemoveSelectedCitations @@ -2562,7 +3386,7 @@ int requestStateId = params.getInt("requestStateId", 0); restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); - // Set validPropertyNames = CitationService.getValidPropertyNames(); + // Set validPropertyNames = getCitationService().getValidPropertyNames(); // String mediatype = params.getString("type"); CitationCollection collection = getCitationCollection(state, false); @@ -2581,7 +3405,7 @@ Citation citation = collection.getCitation(citationId); String schemaId = params.getString("type"); - Schema schema = CitationService.getSchema(schemaId); + Schema schema = getCitationService().getSchema(schemaId); citation.setSchema(schema); updateCitationFromParams(citation, params); @@ -2594,11 +3418,12 @@ // TODO add alert and log error } - CitationService.save(collection); + getCitationService().save(collection); } } - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } // doReviseCitation @@ -2656,7 +3481,8 @@ int requestStateId = params.getInt("requestStateId", 0); restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); - doSearchCommon(state, Mode.ADD_CITATIONS); + //doSearchCommon(state, Mode.ADD_CITATIONS); + doSearchCommon(state, Mode.NEW_RESOURCE); } /** @@ -2676,7 +3502,7 @@ try { - SearchDatabaseHierarchy hierarchy = SearchManager.getSearchHierarchy(); + SearchDatabaseHierarchy hierarchy = getSearchManager().getSearchHierarchy(); if (hierarchy == null) { addAlert(state, rb.getString("search.problem")); @@ -2717,7 +3543,7 @@ if(search == null) { logger.debug( "doBeginSearch() got null ActiveSearch from state." ); - search = SearchManager.newSearch(); + search = getSearchManager().newSearch(); } // get databases selected @@ -2846,7 +3672,7 @@ setMode( state, (Mode)state.getAttribute(STATE_CANCEL_PAGE) ); } - ActiveSearch newSearch = SearchManager.newSearch(); + ActiveSearch newSearch = getSearchManager().newSearch(); state.setAttribute( STATE_SEARCH_INFO, newSearch ); } // doBeginSearch @@ -2925,10 +3751,14 @@ if(listIterator == null) { CitationCollection collection = getCitationCollection(state, true); - listIterator = collection.iterator(); - state.setAttribute(STATE_LIST_ITERATOR, listIterator); + if(collection == null) { + // error + } else { + listIterator = collection.iterator(); + state.setAttribute(STATE_LIST_ITERATOR, listIterator); + } } - if(listIterator.hasNextPage()) + if(listIterator != null && listIterator.hasNextPage()) { listIterator.nextPage(); } @@ -2951,10 +3781,14 @@ if(listIterator == null) { CitationCollection collection = getCitationCollection(state, true); - listIterator = collection.iterator(); - state.setAttribute(STATE_LIST_ITERATOR, listIterator); + if(collection == null) { + // error + } else { + listIterator = collection.iterator(); + state.setAttribute(STATE_LIST_ITERATOR, listIterator); + } } - if(listIterator.hasPreviousPage()) + if(listIterator != null && listIterator.hasPreviousPage()) { listIterator.previousPage(); } @@ -2974,20 +3808,22 @@ restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId); CitationCollection collection = getCitationCollection(state, true); - + if(collection == null) { CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR); - if(listIterator == null) - { - listIterator = collection.iterator(); - state.setAttribute(STATE_LIST_ITERATOR, listIterator); + if(listIterator == null) + { + listIterator = collection.iterator(); + state.setAttribute(STATE_LIST_ITERATOR, listIterator); + } else { + + int pageSize = listIterator.getPageSize(); + int totalSize = collection.size(); + int lastPage = 0; + + listIterator.setStart(totalSize - pageSize); + } } - int pageSize = listIterator.getPageSize(); - int totalSize = collection.size(); - int lastPage = 0; - - listIterator.setStart(totalSize - pageSize); - } // doSearch /** @@ -3006,13 +3842,17 @@ if(listIterator == null) { CitationCollection collection = getCitationCollection(state, true); - - listIterator = collection.iterator(); - state.setAttribute(STATE_LIST_ITERATOR, listIterator); + if(collection == null) { + // error + } else { + listIterator = collection.iterator(); + state.setAttribute(STATE_LIST_ITERATOR, listIterator); + } } + if(listIterator != null) { + listIterator.setStart(0); + } - listIterator.setStart(0); - } // doSearch /** @@ -3030,7 +3870,7 @@ ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS); if(search == null) { - search = SearchManager.newSearch(); + search = getSearchManager().newSearch(); } // search.prepareForNextPage(); @@ -3074,7 +3914,7 @@ ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS); if(search == null) { - search = SearchManager.newSearch(); + search = getSearchManager().newSearch(); } // search.prepareForNextPage(); try @@ -3117,7 +3957,7 @@ ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS); if(search == null) { - search = SearchManager.newSearch(); + search = getSearchManager().newSearch(); } // search.prepareForNextPage(); @@ -3161,7 +4001,7 @@ ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS); if(search == null) { - search = SearchManager.newSearch(); + search = getSearchManager().newSearch(); state.setAttribute(STATE_SEARCH_RESULTS, search); } // search.prepareForNextPage(); @@ -3335,8 +4175,8 @@ if (mode == null) { - logger.debug("initHelper(): mode is undefined, using " + Mode.SEARCH); - setMode(state, Mode.SEARCH); + logger.debug("initHelper(): mode is undefined, using " + Mode.NEW_RESOURCE); + setMode(state, Mode.NEW_RESOURCE); } if (state.getAttribute(STATE_RESULTS_PAGE_SIZE) == null) @@ -3352,7 +4192,7 @@ /* * Resources Tool support */ - ToolSession toolSession = SessionManager.getCurrentToolSession(); + ToolSession toolSession = getSessionManager().getCurrentToolSession(); ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); // TODO: if not entering as a helper, will we need to create pipe??? @@ -3382,49 +4222,51 @@ // set the Mode according to our action switch(pipe.getAction().getActionType()) { - case CREATE: - ContentResource tempResource = createTemporaryResource(pipe); + //case CREATE: + case CREATE_BY_HELPER: +// ContentResource tempResource = createTemporaryResource(pipe); +// +// // tempResource could be null if exception encountered +// if( tempResource == null ) +// { +// // leave helper +// pipe.setActionCompleted( true ); +// toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); +// toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED); +// cleanup( toolSession, CitationHelper.CITATION_PREFIX, state); +// +// return false; +// } - // tempResource could be null if exception encountered - if( tempResource == null ) - { - // leave helper - pipe.setActionCompleted( true ); - toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); - toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED); - cleanup( toolSession, CitationHelper.CITATION_PREFIX, state); - - return false; - } - - state.setAttribute(CitationHelper.RESOURCE_ID, tempResource.getId()); - - String displayName = tempResource.getProperties().getProperty( org.sakaiproject.entity.api.ResourceProperties.PROP_DISPLAY_NAME ); - state.setAttribute( STATE_COLLECTION_TITLE , displayName ); - - try - { - state.setAttribute(STATE_COLLECTION_ID, new String(tempResource.getContent())); - } - catch (ServerOverloadException e) - { - logger.warn("ServerOverloadException ", e); - } +// state.setAttribute(CitationHelper.RESOURCE_ID, tempResource.getId()); +// +// String displayName = tempResource.getProperties().getProperty( org.sakaiproject.entity.api.ResourceProperties.PROP_DISPLAY_NAME ); +// state.setAttribute( STATE_COLLECTION_TITLE , displayName ); +// +// try +// { +// state.setAttribute(STATE_COLLECTION_ID, new String(tempResource.getContent())); +// } +// catch (ServerOverloadException e) +// { +// logger.warn("ServerOverloadException ", e); +// } state.setAttribute( STATE_RESOURCES_ADD, Boolean.TRUE ); - setMode(state, Mode.ADD_CITATIONS); + //setMode(state, Mode.ADD_CITATIONS); + setMode(state, Mode.NEW_RESOURCE); break; case REVISE_CONTENT: state.setAttribute(CitationHelper.RESOURCE_ID, pipe.getContentEntity().getId()); try { - state.setAttribute(STATE_COLLECTION_ID, new String(((ContentResource) pipe.getContentEntity()).getContent())); + state.setAttribute(STATE_CITATION_COLLECTION_ID, new String(((ContentResource) pipe.getContentEntity()).getContent())); } catch (ServerOverloadException e) { logger.warn("ServerOverloadException ", e); } state.removeAttribute( STATE_RESOURCES_ADD ); - setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); break; default: break; @@ -3446,7 +4288,8 @@ if( mode == null ) { // default to ADD_CITATIONS - setMode( state, Mode.ADD_CITATIONS ); + //setMode( state, Mode.ADD_CITATIONS ); + setMode( state, Mode.NEW_RESOURCE ); } } @@ -3473,24 +4316,23 @@ { try { - ContentHostingService contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); - ContentResourceEdit newItem = contentService.addResource(pipe.getContentEntity().getId(), rb.getString("new.citations.list"), null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); - newItem.setResourceType(CitationService.CITATION_LIST_ID); + ContentResourceEdit newItem = getContentService().addResource(pipe.getContentEntity().getId(), rb.getString("new.citations.list"), null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS); + newItem.setResourceType(getCitationService().CITATION_LIST_ID); newItem.setContentType( ResourceType.MIME_TYPE_HTML ); //newItem.setHidden(); ResourcePropertiesEdit props = newItem.getPropertiesEdit(); // set the alternative_reference to point to reference_root for CitationService - props.addProperty(contentService.PROP_ALTERNATE_REFERENCE, org.sakaiproject.citation.api.CitationService.REFERENCE_ROOT); + props.addProperty(getContentService().PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT); props.addProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML); - props.addProperty(CitationService.PROP_TEMPORARY_CITATION_LIST, Boolean.TRUE.toString()); + props.addProperty(getCitationService().PROP_TEMPORARY_CITATION_LIST, Boolean.TRUE.toString()); - CitationCollection collection = CitationService.addCollection(); + CitationCollection collection = getCitationService().addCollection(); newItem.setContent(collection.getId().getBytes()); newItem.setContentType(ResourceType.MIME_TYPE_HTML); - contentService.commitResource(newItem, NotificationService.NOTI_NONE); + getContentService().commitResource(newItem, NotificationService.NOTI_NONE); return newItem; } @@ -3641,7 +4483,7 @@ */ public static String escapeHtmlAndJsQuoted(String string) { - String escapedText = Validator.escapeJsQuoted(string); + String escapedText = getFormattedText().escapeJsQuoted(string); return escapedText.replaceAll("\"", """); } @@ -3688,7 +4530,7 @@ if(collectionId == null) { - collectionId = (String) state.getAttribute(STATE_COLLECTION_ID); + collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID); } logger.debug("doSortCollection sort type = " + sort); @@ -3737,7 +4579,8 @@ } // end else - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } // doSortCollection @@ -3756,7 +4599,7 @@ if(collectionId == null) { - collectionId = (String) state.getAttribute(STATE_COLLECTION_ID); + collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID); } collection = getCitationCollection(state, false); @@ -3770,14 +4613,15 @@ else { // save the collection (this will persist the sort order to the db) - CitationService.save(collection); + getCitationService().save(collection); String sort = collection.getSort(); if (sort != null) state.setAttribute("sort", sort); - setMode(state, Mode.LIST); + //setMode(state, Mode.LIST); + setMode(state, Mode.NEW_RESOURCE); } } // end doSaveCollection @@ -3838,7 +4682,7 @@ requestState.put(ResourceToolAction.ACTION_PIPE, pipe); } - Tool tool = ToolManager.getCurrentTool(); + Tool tool = getToolManager().getCurrentTool(); Object url = state.getAttribute(tool.getId() + Tool.HELPER_DONE_URL); if( url != null) { @@ -3877,6 +4721,202 @@ } } + + protected Map getProperties(ContentEntity entity, SessionState state) { + Map props = new HashMap(); + + ResourceProperties properties = entity.getProperties(); + Reference ref = getEntityManager().newReference(entity.getReference()); + DateFormat df = DateFormat.getDateTimeInstance(); + + // isHidden + props.put(PROP_IS_HIDDEN, new Boolean(entity.isHidden())); + // releaseDate, useReleaseDate + Date releaseDate = null; + if(entity.getReleaseDate() == null) { + releaseDate = new Date(System.currentTimeMillis()); + props.put(PROP_USE_RELEASE_DATE, Boolean.FALSE); + } else { + releaseDate = new Date(entity.getReleaseDate().getTime()); + props.put(PROP_USE_RELEASE_DATE, Boolean.TRUE); + } + props.put(PROP_RELEASE_DATE_STR, df.format(releaseDate)); + props.put(PROP_RELEASE_DATE, releaseDate); + // retractDate, useRetractDate + Date retractDate = null; + if(entity.getRetractDate() == null) { + retractDate = new Date(System.currentTimeMillis() + ONE_WEEK); + props.put(PROP_USE_RETRACT_DATE, Boolean.FALSE); + } else { + retractDate = new Date(entity.getRetractDate().getTime()); + props.put(PROP_USE_RETRACT_DATE, Boolean.TRUE); + } + props.put(PROP_RETRACT_DATE_STR, df.format(retractDate)); + props.put(PROP_RETRACT_DATE, retractDate); + + // isCollection + props.put(PROP_IS_COLLECTION, entity.isCollection()); + // isDropbox + props.put(PROP_IS_DROPBOX, new Boolean(getContentService().isInDropbox(entity.getId()))); + // isSiteCollection + props.put(PROP_IS_SITE_COLLECTION, new Boolean(ref.getContext() != null && ref.getContext().equals(entity.getId()))); + // isPubview + props.put(PROP_IS_PUBVIEW, getContentService().isPubView(entity.getId())); + // isPubviewInherited + props.put(PROP_IS_PUBVIEW_INHERITED, new Boolean(getContentService().isInheritingPubView(entity.getId()))); + // isPubviewPossible + Boolean preventPublicDisplay = (Boolean) state.getAttribute("resources.request.prevent_public_display"); + if(preventPublicDisplay == null) { + preventPublicDisplay = Boolean.FALSE; + } + props.put(PROP_IS_PUBVIEW_POSSIBLE, new Boolean(! preventPublicDisplay.booleanValue())); + + // accessMode + AccessMode accessMode = entity.getAccess(); + props.put(PROP_ACCESS_MODE, accessMode); + // isGroupInherited + props.put(PROP_IS_GROUP_INHERITED, AccessMode.GROUPED == entity.getInheritedAccess()); + + SiteService siteService = (SiteService) ComponentManager.get(SiteService.class); + + Set currentGroups = new TreeSet(); + if(AccessMode.GROUPED == accessMode) { + for(Group gr : (Collection) entity.getGroupObjects()) { + currentGroups.add(gr.getId()); + } + } + + // possibleGroups + Collection inheritedGroupObjs = null; + if(entity.getInheritedAccess() == AccessMode.GROUPED) { + inheritedGroupObjs = entity.getInheritedGroupObjects(); + } else { + try { + Site site = siteService.getSite(ref.getContext()); + inheritedGroupObjs = site.getGroups(); + } catch (IdUnusedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + List> groups = new ArrayList>(); + if(inheritedGroupObjs != null) { + Collection groupsWithRemovePermission = null; + if(AccessMode.GROUPED == accessMode) + { + groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(entity.getId()); + String container = ref.getContainer(); + if(container != null) + { + Collection more = contentService.getGroupsWithRemovePermission(container); + if(more != null && ! more.isEmpty()) + { + groupsWithRemovePermission.addAll(more); + } + } + } else if(AccessMode.GROUPED == entity.getInheritedAccess()) { + groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(ref.getContainer()); + } + else if(ref.getContext() != null && contentService.getSiteCollection(ref.getContext()) != null) + { + groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(contentService.getSiteCollection(ref.getContext())); + } + + Set idsOfGroupsWithRemovePermission = new TreeSet(); + if(groupsWithRemovePermission != null) { + for(Group gr : groupsWithRemovePermission) { + idsOfGroupsWithRemovePermission.add(gr.getId()); + } + } + + for(Group group : inheritedGroupObjs) { + Map grp = new HashMap(); + grp.put("groupId", group.getId()); + grp.put("title", group.getTitle()); + grp.put("description", group.getDescription()); + grp.put("entityRef", group.getReference()); + if(currentGroups.contains(group.getId())) { + grp.put("isLocal", Boolean.toString(true)); + } + if(idsOfGroupsWithRemovePermission.contains(group.getId())) { + grp.put("allowedRemove", Boolean.toString(true)); + } + groups.add(grp); + } + } + props.put(PROP_POSSIBLE_GROUPS, groups); + // isGroupPossible + props.put(PROP_IS_GROUP_POSSIBLE, new Boolean(groups != null && groups.size() > 0)); + // isSingleGroupInherited + props.put(PROP_IS_SINGLE_GROUP_INHERITED, new Boolean(groups != null && groups.size() == 1)); + // isSiteOnly = ! isPubviewPossible && ! isGroupPossible + props.put(PROP_IS_SITE_ONLY, new Boolean(preventPublicDisplay.booleanValue() && (groups == null || groups.size() < 1))); + // isUserSite + props.put(PROP_IS_USER_SITE, siteService.isUserSite(ref.getContext())); + // getSelectedConditionKey + // getSubmittedResourceFilter + // isUseConditionalRelease + state.setAttribute(STATE_RESOURCE_ENTITY_PROPERTIES, props); + + return props; + } + + protected CitationService getCitationService() { + if(this.citationService == null) { + this.citationService = (CitationService) ComponentManager.get(CitationService.class); + } + return this.citationService; + } + + protected ConfigurationService getConfigurationService() { + if(this.configurationService == null) { + this.configurationService = (ConfigurationService) ComponentManager.get(ConfigurationService.class); + } + return this.configurationService; + } + + protected SearchManager getSearchManager() { + if(this.searchManager == null) { + this.searchManager = (SearchManager) ComponentManager.get(SearchManager.class); + } + return this.searchManager; + } + + protected ContentHostingService getContentService() { + if(this.contentService == null) { + this.contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService"); + } + return this.contentService; + } + + protected EntityManager getEntityManager() { + if(this.entityManager == null) { + this.entityManager = (EntityManager) ComponentManager.get(EntityManager.class); + } + return this.entityManager; + } + + protected SessionManager getSessionManager() { + if(this.sessionManager == null) { + this.sessionManager = (SessionManager) ComponentManager.get(SessionManager.class); + } + return this.sessionManager; + } + + protected static ToolManager getToolManager() { + if(toolManager == null) { + toolManager = (ToolManager) ComponentManager.get(ToolManager.class); + } + return toolManager; + } + + protected static FormattedText getFormattedText() { + if(formattedText == null) { + formattedText = (FormattedText) ComponentManager.get(FormattedText.class); + } + return formattedText; + } + } // class CitationHelperAction Index: citations-tool/tool/src/webapp/vm/citation/new_resource.vm =================================================================== --- citations-tool/tool/src/webapp/vm/citation/new_resource.vm (revision 0) +++ citations-tool/tool/src/webapp/vm/citation/new_resource.vm (revision 109899) @@ -0,0 +1,439 @@ + + + + + + + +
+ + +

+ #if($resourceAdd) + $tlang.getString("resource.new") + #else + $tlang.getString("resource.revise") + #end +

+ #if ($alertMessage)
$tlang.getString("label.alert") $validator.escapeHtml($alertMessage)
#end +

+ $!instruction + $!required +

+ +
+ + + + + + + + +
+

+ * + + +

+
+ + + +

+ + +

+ +
+
+ +

+ + #if( $saveciteClients ) + #foreach($client in $saveciteClients) + + + $client.searchurl_label + + + + + + + #end + #end + + #if( $searchLibrary ) + + + $tlang.getString("resource.library") + + + + + #end + + #if( $googleUrl ) + + + $tlang.getString("resource.google") + + + + + #end + + #if(! $fromListPage) + + + $tlang.getString("resource.editor") + + + #end + + + + $tlang.getString("resource.import") + + + + +

+
+ #if($collectionSize && $collectionSize > 0) + #parse( "vm/citation/_listCitations.vm" ) + #else +

No citations message goes here.

+ #end +
+
+ +
+
+ + +#foreach ($group in $!{contentProperties.possibleGroups}) + +#end + + + + + + + + + + + + + + + +
+
+ + + + + Property changes on: citations-tool/tool/src/webapp/vm/citation/new_resource.vm ___________________________________________________________________ Added: svn:eol-style + native Added: svn:keywords + Date Revision Author HeadURL Id Index: citations-tool/tool/src/webapp/vm/citation/_listCitations.vm =================================================================== --- citations-tool/tool/src/webapp/vm/citation/_listCitations.vm (revision 107777) +++ citations-tool/tool/src/webapp/vm/citation/_listCitations.vm (revision 109899) @@ -10,35 +10,28 @@
+ + #if(! $citations.hasPreviousPage())disabled="disabled" #end /> + - - - + + + +
@@ -50,8 +43,8 @@
$tlang.getString( "actions.list" ) - @@ -66,22 +59,24 @@
$tlang.getString("sort.label"): - - + +
@@ -92,8 +87,10 @@ @@ -102,8 +99,8 @@
$tlang.getString( "actions.list" ) - @@ -118,14 +115,14 @@
$tlang.getString("sort.label"): - - + +
@@ -148,18 +145,16 @@
+ + #if(! $citations.hasPreviousPage())disabled="disabled" #end/> + - #if(!$show_citations)disabled="disabled"#end> @@ -167,16 +162,14 @@ + + #if(! $citations.hasNextPage()) disabled="disabled"#end /> + + #if(! $citations.hasNextPage()) disabled="disabled"#end />
Index: citations-tool/tool/src/webapp/css/citations.css =================================================================== --- citations-tool/tool/src/webapp/css/citations.css (revision 0) +++ citations-tool/tool/src/webapp/css/citations.css (revision 109899) @@ -0,0 +1,46 @@ +#messagePanel,#messageError{ + position:absolute; + top:3px; + left:30%; + right:30%; + width:400px; + margin:auto; + padding:5px 10px; + background:#9cf; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} +#messageError{ + background:#b11; + color:#fff; +} +.toggleAnchor{ + border:1px solid #cef; + background:#cef !important; + padding:5px!important; + cursor:pointer +} +.toggleAnchor:hover, .toggleAnchorOpen:hover{ + border:1px solid #9cf; +} + +.toggleAnchorOpen{ + border:1px solid #cef; + background:#cef !important; + padding:5px!important; + cursor:pointer +} +.toggledContent{ + margin:0; + border:2px solid #cef; + border-top:none; + padding: 1em +} +.toggledContent h4{ + color:#000 !important; + width:40em; + margin:.5em 0 !important; + padding:.3em 0; + border-bottom:2px solid #ccc +} Property changes on: citations-tool/tool/src/webapp/css/citations.css ___________________________________________________________________ Added: svn:eol-style + native Index: citations-tool/tool/src/webapp/js/new_resource.js =================================================================== --- citations-tool/tool/src/webapp/js/new_resource.js (revision 0) +++ citations-tool/tool/src/webapp/js/new_resource.js (revision 109899) @@ -0,0 +1,345 @@ +/******************************************************************* + * Process a click on a link to modify citations in a citation list. + * Links can trigger a search, a citation editor or an import page. + * This function will check whether the context is creating a new + * citation list or revising an existing citation list. If it's + * creating a new citation list, the function checks whether a name + * has been entered and requires an input before proceeding. If a + * name has been entered, the function posts an AJAX request to ensure + * that a ContentResource and CitationCollection has been created. + * If that succeeds, this function makes this function call: + * + * createSuccess.invoke(jsObj) + * + * where jsObj is a Javascript object returned by the successful AJAX + * call. The jsObj object has name-value pairs, including jsObj.message, + * jsObj.collectionId, jsObj.resourceId, and jsObj.citationCollectionId. + * If the AJAX request fails, this function makes this function call: + * + * failureFunction.invoke(jqXHR, textStatus, errorThrown) + * + * where the parameters are the same as those described for the error + * function in jQuery's ajax function (http://api.jquery.com/jQuery.ajax/). + * If the context is revising an existing citation list rather than creating + * a new citation list, this function makes this function call: + * + * modifySuccess.invoke(jsObj) + * + * where jsObj is a Javascript object with name-value pairs, including + * jsObj.collectionId, jsObj.resourceId, and jsObj.citationCollectionId. + *******************************************************************/ + +// assume jquery + +// create citations_new_resource namespace if it doesn't exist +var citations_new_resource = citations_new_resource || {}; + +/* + * used in the json returned by actions that + * need to be notified to the user + */ +var reportSuccess = function(msg){ + $('#messagePanel').html(msg).fadeTo("slow", 1).animate({ + opacity: 1.0 + }, 5000).fadeTo(3000, 0); +}; + +/* + * There has been an error + */ +var reportError = function(msg){ + $('#messageError').html(msg).fadeTo("slow", 1).animate({ + opacity: 1.0 + }, 5000).fadeTo(3000, 0); +}; + +function resizeFrame(updown) { + if (top.location != self.location) { + var frame = parent.document.getElementById(window.name); + } + if( frame ) { + var clientH = document.body.clientHeight; + if(updown != 'shrink') { + clientH += 30; + } + $( frame ).height( clientH ); + } else { +// throw( "resizeFrame did not get the frame (using name=" + window.name + ")" ); + } +} + +citations_new_resource.setupToggleAreas = function(toggler, togglee, openInit, speed){ + // toggler=class of click target + // togglee=class of container to expand + // openInit=true - all togglee open on enter + // speed=speed of expand/collapse animation + if (openInit == true && openInit != null) { + $('.expand').hide(); + } + else { + $('.' + togglee).hide(); + $('.collapse').hide(); + resizeFrame(); + } + $('.' + toggler).click(function(){ + $(this).next('.' + togglee).fadeToggle(speed); + $(this).find('.expand').toggle(); + $(this).find('.collapse').toggle(); + resizeFrame(); + }); +} + + +citations_new_resource.processClick = function(successAction) { + var requestDisplayName = function() { + // TODO: use sakai message in DOM + reportError('Please supply a name for the citation list.'); + return; + }; + var postAjaxRequest = function(params, successAction) { + var actionUrl = $('#newCitationListForm').attr('action'); + $.ajax({ + type : 'POST', + url : actionUrl, + cache : false, + data : params, + dataType : 'json', + success : function(jsObj) { + $.each(jsObj, function(key, value) { + if(key === 'message' && value && 'null' !== value && '' !== $.trim(value)) { + reportSuccess(value); + } else if($.isArray(value)) { + reportError('result for key ' + key + ' is an array: ' + value); + } else { + $('input[name=' + key + ']').val(value); + } + }); + if(successAction && successAction.invoke) { + successAction.invoke(jsObj); + } + }, + error : function(jqXHR, textStatus, errorThrown) { + // TODO: replace with reasonable error handling + reportError("failed: " + textStatus + " :: " + errorThrown); + } + }); + + }; + var handleNewResource = function(successAction) { + $('.citation_action').val('create_resource'); + $('.requested_mimetype').val('application/json'); + $('.ajaxRequest').val('true'); + var params = $('#newCitationListForm').find('input').serializeArray(); + postAjaxRequest(params, successAction); + }; + var handleExistingResource = function(successAction) { + $('.citation_action').val('update_resource'); + $('.requested_mimetype').val('application/json'); + $('.ajaxRequest').val('true'); + var newValues = $('#newCitationListForm').find('input').serializeArray(); + var newValuesObj = {}; + var oldValues = $('#fossils').find('input').serializeArray(); + var oldValuesObj = {}; + $.each(newValues, function(index, obj) { + if(newValuesObj[obj.name]) { + newValuesObj[obj.name].push(obj.value); + } else { + newValuesObj[obj.name] = [ obj.value ]; + } + }); + $.each(oldValues, function(index, obj) { + if(oldValuesObj[obj.name]) { + oldValuesObj[obj.name].push(obj.value); + } else { + oldValuesObj[obj.name] = [ obj.value ]; + } + }); + var changes = false; + $.each(newValuesObj, function(key, value) { + if(! oldValuesObj[key] || oldValuesObj[key].length != value.length) { + newValues.push({ 'name':'resource_changes', 'value':key }); + changes = true; + } else if(value.length > 1) { + var differences = false; + value.sort(); + if(oldValuesObj[key] && oldValuesObj[key].length > 1) { + oldValuesObj[key].sort(); + } + $.each(value,function(i,v){ + if(oldValuesObj[key] && oldValuesObj[key][i] && oldValuesObj[key][i] === v) { + // do nothing + } else { + differences = true; + return; + } + }); + if(differences) { + newValues.push({ 'name':'resource_changes', 'value':key }); + changes = true; + } + } else if(value.length > 0) { + if(value[0] !== oldValuesObj[key][0]) { + newValues.push({ 'name':'resource_changes', 'value':key }); + changes = true; + } + } + //alert('newValuesObj[' + key + '] == ' + value + '\noldValuesObj[' + key + '] == ' + oldValuesObj[key] + '\n' + changes); + }); + if(changes) { + postAjaxRequest(newValues, successAction); + } else { + var jsObj = {}; + if(successAction && successAction.invoke) { + successAction.invoke(jsObj); + } + } + }; + var displayName = $('#displayName').val(); + // TODO: consider chacking for #displayName_fossil and using it? + // var oldDisplayName = $('#displayName_fossil').val(); + if(displayName && '' !== $.trim(displayName)) { + var resourceId = $('#resourceId').val(); + if(resourceId) { + // are there changes? + handleExistingResource(successAction); + } else { + // create a new resource + handleNewResource(successAction); + } + } else { + // demand a displayName and stay on page + requestDisplayName(); + } + +}; + + +citations_new_resource.init = function() { + var DEFAULT_DIALOG_HEIGHT = 610; + var DEFAULT_DIALOG_WIDTH = 850; + var setFrameHeight = function() { + var body_height = $('body').innerHeight() - 100; + if(body_height < DEFAULT_DIALOG_HEIGHT) { + var spacer_height = DEFAULT_DIALOG_HEIGHT - body_height; + $('body').append('
'); + setMainFrameHeight( window.name ); + } + }; + + var childWindow = {}; + + $('.saveciteClient a').click(function(eventObject) { + var successObj = { + linkId : $(eventObject.target).attr('id'), + saveciteClientUrl : $(eventObject.target).siblings('.saveciteClientUrl').text(), + popupTitle : $(eventObject.target).siblings('.popupTitle').text(), + windowHeight : $(eventObject.target).siblings('.windowHeight').text(), + windowWidth : $(eventObject.target).siblings('.windowWidth').text(), + invoke : function(jsObj) { + if(childWindow && childWindow[this.linkId] && childWindow[this.linkId].close) { + childWindow[this.linkId].close(); + } + childWindow[this.linkId] = openWindow(this.saveciteClientUrl,this.popupTitle,'scrollbars=yes,toolbar=yes,resizable=yes,height=' + this.windowHeight + ',width=' + this.windowWidth); + childWindow[this.linkId].focus(); + } + }; + citations_new_resource.processClick(successObj) + }); + $('#Search').click(function(eventObject) { + var successObj = { + linkId : $(eventObject.target).attr('id'), + searchUrl : $(eventObject.target).siblings('.searchUrl').text(), + popupTitle : $(eventObject.target).siblings('.popupTitle').text(), + invoke : function(jsObj) { + try { + if(jsObj && jsObj.resourceId) { + searchUrl += "&resourceId=" + jsObj.resourceId; + } + if(jsObj && jsObj.citationCollectionId) { + searchUrl += "&citationCollectionId=" + jsObj.citationCollectionId; + } + } catch (e) { + reportError(e); + } + if(childWindow && childWindow[this.linkId] && childWindow[this.linkId].close) { + childWindow[this.linkId].close(); + } + childWindow[this.linkId] = openWindow(this.searchUrl,this.popupTitle,'scrollbars=yes,toolbar=yes,resizable=yes,height=' + DEFAULT_DIALOG_HEIGHT + ',width=' + DEFAULT_DIALOG_WIDTH); + childWindow[this.linkId].focus(); + } + }; + citations_new_resource.processClick(successObj) + }); + $('#SearchGoogle').click(function(eventObject) { + var successObj = { + linkId : $(eventObject.target).attr('id'), + googleUrl : $(eventObject.target).siblings('.googleUrl').text(), + popupTitle : $(eventObject.target).siblings('.popupTitle').text(), + invoke : function(jsObj) { + if(childWindow && childWindow[this.linkId] && childWindow[this.linkId].close) { + childWindow[this.linkId].close(); + } + childWindow[this.linkId] = openWindow(this.googleUrl,this.popupTitle,'scrollbars=yes,toolbar=yes,resizable=yes,height=' + DEFAULT_DIALOG_HEIGHT + ',width=' + DEFAULT_DIALOG_WIDTH); + childWindow[this.linkId].focus(); + } + }; + citations_new_resource.processClick(successObj) + }); + $('#CreateCitation').click(function(eventObject) { + var successObj = { + invoke : function(jsObj) { + $('#sakai_action').val('doCreate'); + $('#ajaxRequest').val('false'); + $('#newCitationListForm').submit(); + } + }; + citations_new_resource.processClick(successObj) + }); + $('#ImportCitation').click(function(eventObject) { + var successObj = { + invoke : function(jsObj) { + $('#sakai_action').val('doImportPage'); + $('#ajaxRequest').val('false'); + $('#newCitationListForm').submit(); + } + }; + citations_new_resource.processClick(successObj) + }); + $('#Done').click(function(eventObject) { + var successObj = { + invoke : function(jsObj) { + $('#sakai_action').val('doFinish'); + $('#ajaxRequest').val('false'); + $('#newCitationListForm').attr('method', 'GET'); + $('#newCitationListForm').submit(); + } + }; + citations_new_resource.processClick(successObj) + }); + $('#access_mode_groups').change(function(eventObject) { + $('#groupTable').toggle(); + }); + $(window).unload(function() { + if(childWindow) { + for (key in childWindow) { + if(childWindow[key] && childWindow[key].close) { + childWindow[key].close(); + } + } + } + }); + $('#hideAccess, #showAccess').click(function(eventObject){ + $('#accessShown').toggle(); + $('#accessHidden').toggle(); + setFrameHeight(); + }); + + setFrameHeight(); + +}; + +$(document).ready(function(){ + citations_new_resource.init(); + citations_new_resource.setupToggleAreas('toggleAnchor', 'toggledContent', false, 'fast'); +}); + Property changes on: citations-tool/tool/src/webapp/js/new_resource.js ___________________________________________________________________ Added: svn:eol-style + native Added: svn:keywords + Date Revision Author HeadURL Id Index: citations-tool/tool/pom.xml =================================================================== --- citations-tool/tool/pom.xml (revision 107777) +++ citations-tool/tool/pom.xml (revision 109899) @@ -70,6 +70,13 @@ commons-logging 1.0.4 + + net.sf.json-lib + json-lib + 2.4 + jdk15 + jar + Index: citations-util/util/src/bundle/citations.properties =================================================================== --- citations-util/util/src/bundle/citations.properties (revision 107777) +++ citations-util/util/src/bundle/citations.properties (revision 109899) @@ -5,10 +5,60 @@ cite.title = Citation cite.subtitle = Click \"{0}\" to see if a copy of the citation is available through your library. cite.openUrlLabel = Find in my library -action.create = Add Citation List +action.create = Create Citation List action.create.quota = Adding a Citation List would place this account over quota. To add this resource, some resources may need to be deleted. action.revise = Edit Citation List +resource.new = New Citation List +resource.revise = Revise Citation List +resource.title = Citation List Name: +resource.gen.email1 = Email Notification +resource.gen.email2 = High - All participants +resource.gen.email3 = Low - Only participants who have opted in +resource.gen.email4 = None - No notification +resource.search.target = Add Citations From: +resource.library = Library Resources +resource.library.search = Search Library Resources +resource.google = Google Scholar +resource.google.search = Search Google Scholar +resource.editor = Manually Create +resource.import = Import +resource.import.file = Import From File +resource.new.success = Citation List ({0}) has been created. +resource.null_collectionId.error = Configuration problem. (No CI). +resource.access.groups.choice = Display this file to selected groups only. +resource.access.groups.fldr = Display this folder and its contents to selected groups only. +resource.access.inherit = Leave access settings as for the folder. +resource.access.public.choice = This file is publicly viewable. +resource.access.public.fldr = This folder and its contents are publicly viewable. +resource.access.site.choice = Only members of this site can see this file. +resource.access.site.fldr = Only members of this site can see this folder and its contents. +resource.access.title = Access + +resource.aaa.hide = Hide Access and Availability +resource.aaa.show = Show Access and Availability +resource.aaa.title = Access and Availability + +resource.avail.end1 = Until +resource.avail.hide = Hide +resource.avail.hide10 = Hide this item +resource.avail.hide20 = Hide this folder and its contents +resource.avail.show1 = Show this item +resource.avail.show2 = Show this folder +resource.avail.start1 = From +resource.avail.title = Availability + +resource.edit.access4 = Display to selected groups +resource.edit.group1 = Title +resource.edit.group2 = Description +resource.edit.group3 = Table contains list of groups. First column contains checkboxes, second contains the group name, third the group description. Header links can be used to sort. + +resource.group.select.title = Check All +resource.instr.access = Choose who can see this item. +resource.instr.avail = Resources can be scheduled to be visible between certain dates only. Site administrators will always be able to see hidden items, even when they are hidden from other users. +resource.label.date = Date: +resource.label.time = Time: + # import import.title = Import Citations import.directions = Please select an RIS file to upload or enter the text of an RIS file directly into the text area below. Index: citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseConfigurationService.java =================================================================== --- citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseConfigurationService.java (revision 107777) +++ citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseConfigurationService.java (revision 109899) @@ -21,38 +21,22 @@ package org.sakaiproject.citation.impl; -import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Enumeration; -import java.util.Hashtable; +import java.util.HashMap; import java.util.Iterator; -import java.util.ArrayList; import java.util.List; -import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Observable; import java.util.Observer; -import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; -import java.util.Vector; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSSerializer; - -import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; @@ -63,19 +47,15 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.sakaiproject.authz.api.SecurityAdvisor; -import org.sakaiproject.authz.api.SecurityAdvisor.SecurityAdvice; import org.sakaiproject.authz.cover.SecurityService; -import org.sakaiproject.citation.util.api.OsidConfigurationException; import org.sakaiproject.citation.api.ConfigurationService; import org.sakaiproject.citation.api.SiteOsidConfiguration; - +import org.sakaiproject.citation.util.api.OsidConfigurationException; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentResource; -import org.sakaiproject.entity.api.ContextObserver; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.event.api.Event; @@ -89,13 +69,18 @@ import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.SiteService; -import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.user.api.UserDirectoryService; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; import com.thoughtworks.xstream.XStream; +import edu.indiana.lib.twinpeaks.util.DomException; + /** * */ Index: citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseCitationService.java =================================================================== --- citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseCitationService.java (revision 107777) +++ citations-impl/impl/src/java/org/sakaiproject/citation/impl/BaseCitationService.java (revision 109899) @@ -915,21 +915,26 @@ */ public Object getCitationProperty(String name) { - if (m_citationProperties == null) - { - m_citationProperties = new Hashtable(); - } - Object value = m_citationProperties.get(name); - if (value == null) - { - if (isMultivalued(name)) + Object value = null; + if(name == null) { + value = ""; + } else { + if (m_citationProperties == null) { - value = new Vector(); - ((List) value).add(""); + m_citationProperties = new Hashtable(); } - else + value = m_citationProperties.get(name); + if (value == null) { - value = ""; + if (isMultivalued(name)) + { + value = new Vector(); + ((List) value).add(""); + } + else + { + value = ""; + } } } @@ -1648,7 +1653,7 @@ logger.debug("importFromRisList: Schema Name = " + schemaName); // Lookup the Schema based on the Schema string gotten from the reverse map - schema = org.sakaiproject.citation.cover.CitationService.getSchema(schemaName); + schema = BaseCitationService.this.getSchema(schemaName); logger.debug("importFromRisList: Retrieved Schema Name = " + schema.getIdentifier()); setSchema(schema); } // end else (else processes RIScode == "TY") @@ -4637,7 +4642,7 @@ requiredPropertyKeys.add(ResourceProperties.PROP_CONTENT_TYPE); BaseInteractionAction createAction = new CitationListCreateAction(ResourceToolAction.CREATE, - ResourceToolAction.ActionType.CREATE, + ResourceToolAction.ActionType.CREATE_BY_HELPER, CitationService.CITATION_LIST_ID, CitationService.HELPER_ID, new Vector());