Source Code Cross Referenced for FilePickerAction.java in  » ERP-CRM-Financial » sakai » org » sakaiproject » content » tool » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » ERP CRM Financial » sakai » org.sakaiproject.content.tool 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /**********************************************************************************
0002:         * $URL: https://source.sakaiproject.org/svn/content/tags/sakai_2-4-1/content-tool/tool/src/java/org/sakaiproject/content/tool/FilePickerAction.java $
0003:         * $Id: FilePickerAction.java 30211 2007-05-09 18:12:55Z ajpoland@iupui.edu $
0004:         ***********************************************************************************
0005:         *
0006:         * Copyright (c) 2005, 2006 The Sakai Foundation.
0007:         *
0008:         * Licensed under the Educational Community License, Version 1.0 (the "License");
0009:         * you may not use this file except in compliance with the License.
0010:         * You may obtain a copy of the License at
0011:         *
0012:         *      http://www.opensource.org/licenses/ecl1.php
0013:         *
0014:         * Unless required by applicable law or agreed to in writing, software
0015:         * distributed under the License is distributed on an "AS IS" BASIS,
0016:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0017:         * See the License for the specific language governing permissions and
0018:         * limitations under the License.
0019:         *
0020:         **********************************************************************************/package org.sakaiproject.content.tool;
0021:
0022:        import java.io.IOException;
0023:        import java.io.InputStream;
0024:        import java.net.MalformedURLException;
0025:        import java.net.URL;
0026:        import java.util.Arrays;
0027:        import java.util.Collection;
0028:        import java.util.Comparator;
0029:        import java.util.Enumeration;
0030:        import java.util.Hashtable;
0031:        import java.util.Iterator;
0032:        import java.util.List;
0033:        import java.util.Map;
0034:        import java.util.Set;
0035:        import java.util.SortedSet;
0036:        import java.util.TreeSet;
0037:        import java.util.Vector;
0038:        import java.util.regex.Matcher;
0039:        import java.util.regex.Pattern;
0040:
0041:        import javax.servlet.http.HttpServletRequest;
0042:        import javax.servlet.http.HttpServletResponse;
0043:
0044:        import org.apache.commons.logging.Log;
0045:        import org.apache.commons.logging.LogFactory;
0046:        import org.sakaiproject.cheftool.Context;
0047:        import org.sakaiproject.cheftool.JetspeedRunData;
0048:        import org.sakaiproject.cheftool.PagedResourceHelperAction;
0049:        import org.sakaiproject.cheftool.RunData;
0050:        import org.sakaiproject.cheftool.VelocityPortlet;
0051:        import org.sakaiproject.cheftool.VelocityPortletPaneledAction;
0052:        import org.sakaiproject.component.cover.ComponentManager;
0053:        import org.sakaiproject.component.cover.ServerConfigurationService;
0054:        import org.sakaiproject.content.api.ContentCollection;
0055:        import org.sakaiproject.content.api.ContentCollectionEdit;
0056:        import org.sakaiproject.content.api.ContentEntity;
0057:        import org.sakaiproject.content.api.ContentResource;
0058:        import org.sakaiproject.content.api.ContentResourceEdit;
0059:        import org.sakaiproject.content.api.ContentResourceFilter;
0060:        import org.sakaiproject.content.api.FilePickerHelper;
0061:        import org.sakaiproject.content.api.InteractionAction;
0062:        import org.sakaiproject.content.api.ResourceToolAction;
0063:        import org.sakaiproject.content.api.ResourceToolActionPipe;
0064:        import org.sakaiproject.content.api.ResourceType;
0065:        import org.sakaiproject.content.api.ResourceTypeRegistry;
0066:        import org.sakaiproject.content.api.ContentHostingService;
0067:        import org.sakaiproject.content.api.ContentTypeImageService;
0068:        import org.sakaiproject.content.api.ServiceLevelAction;
0069:        import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
0070:        import org.sakaiproject.entity.api.Reference;
0071:        import org.sakaiproject.entity.api.ResourceProperties;
0072:        import org.sakaiproject.entity.api.ResourcePropertiesEdit;
0073:        import org.sakaiproject.entity.cover.EntityManager;
0074:        import org.sakaiproject.event.api.SessionState;
0075:        import org.sakaiproject.event.cover.NotificationService;
0076:        import org.sakaiproject.exception.IdInvalidException;
0077:        import org.sakaiproject.exception.IdLengthException;
0078:        import org.sakaiproject.exception.IdUniquenessException;
0079:        import org.sakaiproject.exception.IdUnusedException;
0080:        import org.sakaiproject.exception.IdUsedException;
0081:        import org.sakaiproject.exception.InconsistentException;
0082:        import org.sakaiproject.exception.OverQuotaException;
0083:        import org.sakaiproject.exception.PermissionException;
0084:        import org.sakaiproject.exception.ServerOverloadException;
0085:        import org.sakaiproject.exception.TypeException;
0086:        import org.sakaiproject.site.api.Site;
0087:        import org.sakaiproject.site.cover.SiteService;
0088:        import org.sakaiproject.time.api.Time;
0089:        import org.sakaiproject.time.cover.TimeService;
0090:        import org.sakaiproject.tool.api.Tool;
0091:        import org.sakaiproject.tool.api.ToolException;
0092:        import org.sakaiproject.tool.api.ToolSession;
0093:        import org.sakaiproject.tool.cover.SessionManager;
0094:        import org.sakaiproject.tool.cover.ToolManager;
0095:        import org.sakaiproject.user.api.User;
0096:        import org.sakaiproject.user.cover.UserDirectoryService;
0097:        import org.sakaiproject.util.FileItem;
0098:        import org.sakaiproject.util.ParameterParser;
0099:        import org.sakaiproject.util.ResourceLoader;
0100:        import org.sakaiproject.util.StringUtil;
0101:        import org.sakaiproject.util.Validator;
0102:
0103:        /**
0104:         * The FilePickerAction drives the FilePicker helper.<br />
0105:         * This works with the ResourcesTool to show a file picker / attachment editor that can be used by any Sakai tools as a helper.<br />
0106:         * If the user ends without a cancel, the original collection of attachments is replaced with the edited list - otherwise it is left unchanged.
0107:         */
0108:        public class FilePickerAction extends PagedResourceHelperAction {
0109:            /** Resource bundle using current language locale */
0110:            private static ResourceLoader rb = new ResourceLoader("helper");
0111:
0112:            /** Resource bundle using current language locale */
0113:            private static ResourceLoader trb = new ResourceLoader("types");
0114:
0115:            private static final Log logger = LogFactory
0116:                    .getLog(FilePickerAction.class);
0117:
0118:            protected static final String PREFIX = "filepicker.";
0119:
0120:            protected static final String MODE_ADD_METADATA = "mode_add_metadata";
0121:            protected static final String MODE_ATTACHMENT_CREATE = "mode_attachment_create";
0122:            protected static final String MODE_ATTACHMENT_CREATE_INIT = "mode_attachment_create_init";
0123:            protected static final String MODE_ATTACHMENT_DONE = "mode_attachment_done";
0124:            protected static final String MODE_ATTACHMENT_EDIT_ITEM = "mode_attachment_edit_item";
0125:            protected static final String MODE_ATTACHMENT_EDIT_ITEM_INIT = "mode_attachment_edit_item_init";
0126:            protected static final String MODE_ATTACHMENT_NEW_ITEM = "mode_attachment_new_item";
0127:            protected static final String MODE_ATTACHMENT_NEW_ITEM_INIT = "mode_attachment_new_item_init";
0128:            protected static final String MODE_ATTACHMENT_SELECT = "mode_attachment_select";
0129:            protected static final String MODE_ATTACHMENT_SELECT_INIT = "mode_attachment_select_init";
0130:            protected static final String MODE_HELPER = "mode_helper";
0131:
0132:            /** The null/empty string */
0133:            private static final String NULL_STRING = "";
0134:
0135:            protected static final String STATE_ADDED_ITEMS = PREFIX
0136:                    + "added_items";
0137:
0138:            /** The name of the state attribute containing the name of the tool that invoked Resources as attachment helper */
0139:            public static final String STATE_ATTACH_TOOL_NAME = PREFIX
0140:                    + "attach_tool_name";
0141:
0142:            /**
0143:             * The name of the state attribute for the maximum number of items to attach. The attribute value will be an Integer, 
0144:             * usually FilePickerHelper.CARDINALITY_SINGLE or FilePickerHelper.CARDINALITY_MULTIPLE. 
0145:             */
0146:            protected static final String STATE_ATTACH_CARDINALITY = PREFIX
0147:                    + "attach_cardinality";
0148:            protected static final String STATE_ATTACH_INSTRUCTION = PREFIX
0149:                    + "attach_instruction";
0150:
0151:            protected static final String STATE_ATTACH_LINKS = PREFIX
0152:                    + "attach_links";
0153:            protected static final String STATE_ATTACH_SUBTITLE = PREFIX
0154:                    + "attach_subtitle";
0155:            protected static final String STATE_ATTACH_TITLE = PREFIX
0156:                    + "attach_title";
0157:
0158:            protected static final String STATE_ATTACHMENT_FILTER = PREFIX
0159:                    + "attachment_filter";
0160:
0161:            protected static final String STATE_ATTACHMENT_ORIGINAL_LIST = PREFIX
0162:                    + "attachment_original_list";
0163:            protected static final String STATE_CONTENT_SERVICE = PREFIX
0164:                    + "content_service";
0165:
0166:            /** The content type image lookup service in the State. */
0167:            protected static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = PREFIX
0168:                    + "content_type_image_service";
0169:
0170:            protected static final String STATE_DEFAULT_COLLECTION_ID = PREFIX
0171:                    + "default_collection_id";
0172:            protected static final String STATE_DEFAULT_COPYRIGHT = PREFIX
0173:                    + "default_copyright";
0174:            protected static final String STATE_DEFAULT_RETRACT_TIME = PREFIX
0175:                    + "default_retract_time";
0176:            protected static final String STATE_EXPAND_ALL = PREFIX
0177:                    + "expand_all";
0178:            protected static final String STATE_EXPAND_ALL_FLAG = PREFIX
0179:                    + "expand_all_flag";
0180:            protected static final String STATE_EXPANDED_COLLECTIONS = PREFIX
0181:                    + "expanded_collections";
0182:            protected static final String STATE_FILE_UPLOAD_MAX_SIZE = PREFIX
0183:                    + "file_upload_max_size";
0184:            protected static final String STATE_FILEPICKER_MODE = PREFIX
0185:                    + "mode";
0186:            protected static final String STATE_HELPER_CANCELED_BY_USER = PREFIX
0187:                    + "helper_canceled_by_user";
0188:            protected static final String STATE_HELPER_CHANGED = PREFIX
0189:                    + "made_changes";
0190:            protected static final String STATE_HOME_COLLECTION_ID = PREFIX
0191:                    + "home_collection_id";
0192:            protected static final String STATE_LIST_SELECTIONS = PREFIX
0193:                    + "list_selections";
0194:            protected static final String STATE_LIST_VIEW_SORT = PREFIX
0195:                    + "list_view_sort";
0196:            protected static final String STATE_NAVIGATION_ROOT = PREFIX
0197:                    + "navigation_root";
0198:            protected static final String STATE_NEED_TO_EXPAND_ALL = PREFIX
0199:                    + "need_to_expand_all";
0200:            protected static final String STATE_NEW_ATTACHMENT = PREFIX
0201:                    + "new_attachment";
0202:            protected static final String STATE_PREVENT_PUBLIC_DISPLAY = PREFIX
0203:                    + "prevent_public_display";
0204:            protected static final String STATE_REMOVED_ITEMS = PREFIX
0205:                    + "removed_items";
0206:            protected static final String STATE_RESOURCES_TYPE_REGISTRY = PREFIX
0207:                    + "resource_type_registry";
0208:            protected static final String STATE_SESSION_INITIALIZED = PREFIX
0209:                    + "session_initialized";
0210:            protected static final String STATE_SHOW_ALL_SITES = PREFIX
0211:                    + "show_all_sites";
0212:            protected static final String STATE_SHOW_OTHER_SITES = PREFIX
0213:                    + "show_other_sites";
0214:
0215:            /** The sort by */
0216:            private static final String STATE_SORT_BY = PREFIX + "sort_by";
0217:
0218:            protected static final String STATE_TOP_MESSAGE_INDEX = PREFIX
0219:                    + "top_message_index";
0220:
0221:            /** The sort ascending or decending */
0222:            private static final String STATE_SORT_ASC = PREFIX + "sort_asc";
0223:
0224:            private static final String TEMPLATE_ATTACH = "content/sakai_filepicker_attach";
0225:            private static final String TEMPLATE_SELECT = "content/sakai_filepicker_select";
0226:
0227:            private static final int MAXIMUM_ATTEMPTS_FOR_UNIQUENESS = ResourcesAction.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS;
0228:
0229:            /**
0230:             * @param portlet
0231:             * @param context
0232:             * @param data
0233:             * @param state
0234:             * @return
0235:             */
0236:            public String buildMainPanelContext(VelocityPortlet portlet,
0237:                    Context context, RunData data, SessionState state) {
0238:                initState(state, portlet, data);
0239:
0240:                context.put("DOT", ListItem.DOT);
0241:
0242:                // if we are in edit attachments...
0243:                String mode = (String) state
0244:                        .getAttribute(ResourcesAction.STATE_MODE);
0245:                ToolSession toolSession = SessionManager
0246:                        .getCurrentToolSession();
0247:                String helper_mode = (String) toolSession
0248:                        .getAttribute(STATE_FILEPICKER_MODE);
0249:
0250:                if (mode == null
0251:                        || helper_mode == null
0252:                        || toolSession
0253:                                .getAttribute(FilePickerHelper.START_HELPER) != null) {
0254:                    state.removeAttribute(FilePickerHelper.START_HELPER);
0255:                    mode = initHelperAction(state, toolSession);
0256:                    helper_mode = (String) toolSession
0257:                            .getAttribute(STATE_FILEPICKER_MODE);
0258:                }
0259:
0260:                ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession
0261:                        .getAttribute(ResourceToolAction.ACTION_PIPE);
0262:                if (pipe != null) {
0263:                    if (pipe.isActionCanceled()) {
0264:                        toolSession.setAttribute(STATE_FILEPICKER_MODE,
0265:                                MODE_ATTACHMENT_SELECT_INIT);
0266:                    } else if (pipe.isErrorEncountered()) {
0267:                        String msg = pipe.getErrorMessage();
0268:                        if (msg != null && !msg.trim().equals("")) {
0269:                            addAlert(state, msg);
0270:                        }
0271:                        toolSession.setAttribute(STATE_FILEPICKER_MODE,
0272:                                MODE_ATTACHMENT_SELECT_INIT);
0273:                    } else if (pipe.isActionCompleted()) {
0274:                        finishAction(state, toolSession, pipe);
0275:                    }
0276:                    toolSession.removeAttribute(ResourceToolAction.DONE);
0277:                }
0278:                helper_mode = (String) toolSession
0279:                        .getAttribute(STATE_FILEPICKER_MODE);
0280:
0281:                if (MODE_ATTACHMENT_SELECT.equals(helper_mode)) {
0282:                    helper_mode = MODE_ATTACHMENT_SELECT_INIT;
0283:                } else if (MODE_ATTACHMENT_CREATE.equals(helper_mode)) {
0284:                    helper_mode = MODE_ATTACHMENT_CREATE_INIT;
0285:                } else if (MODE_ATTACHMENT_NEW_ITEM.equals(helper_mode)) {
0286:                    helper_mode = MODE_ATTACHMENT_NEW_ITEM_INIT;
0287:                } else if (MODE_ATTACHMENT_EDIT_ITEM.equals(helper_mode)) {
0288:                    helper_mode = MODE_ATTACHMENT_EDIT_ITEM_INIT;
0289:                }
0290:
0291:                String template = null;
0292:                if (MODE_ATTACHMENT_SELECT_INIT.equals(helper_mode)) {
0293:                    template = buildSelectAttachmentContext(portlet, context,
0294:                            data, state);
0295:                } else if (MODE_ADD_METADATA.equals(helper_mode)) {
0296:                    template = buildAddMetadataContext(portlet, context, data,
0297:                            state);
0298:                }
0299:                //		else if(MODE_ATTACHMENT_CREATE_INIT.equals(helper_mode))
0300:                //		{
0301:                //			template = buildCreateContext(portlet, context, data, state);
0302:                //		}
0303:                //		else if(MODE_ATTACHMENT_NEW_ITEM_INIT.equals(helper_mode))
0304:                //		{
0305:                //			template = buildItemTypeContext(portlet, context, data, state);
0306:                //		}
0307:                //		else if(MODE_ATTACHMENT_EDIT_ITEM_INIT.equals(helper_mode))
0308:                //		{
0309:                //			template = buildCreateContext(portlet, context, data, state);
0310:                //		}
0311:
0312:                return template;
0313:
0314:            }
0315:
0316:            /**
0317:             * @param portlet
0318:             * @param context
0319:             * @param data
0320:             * @param state
0321:             * @return
0322:             */
0323:            private String buildAddMetadataContext(VelocityPortlet portlet,
0324:                    Context context, RunData data, SessionState state) {
0325:                context.put("tlang", trb);
0326:
0327:                String template = "content/sakai_resources_cwiz_finish";
0328:                ToolSession toolSession = SessionManager
0329:                        .getCurrentToolSession();
0330:                ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession
0331:                        .getAttribute(ResourceToolAction.ACTION_PIPE);
0332:                if (pipe.isActionCanceled()) {
0333:                    // go back to list view
0334:
0335:                } else if (pipe.isErrorEncountered()) {
0336:                    // report the error?
0337:
0338:                } else {
0339:                    // complete the create wizard
0340:                    String defaultCopyrightStatus = (String) toolSession
0341:                            .getAttribute(STATE_DEFAULT_COPYRIGHT);
0342:                    if (defaultCopyrightStatus == null
0343:                            || defaultCopyrightStatus.trim().equals("")) {
0344:                        defaultCopyrightStatus = ServerConfigurationService
0345:                                .getString("default.copyright");
0346:                        toolSession.setAttribute(STATE_DEFAULT_COPYRIGHT,
0347:                                defaultCopyrightStatus);
0348:                    }
0349:
0350:                    String encoding = data.getRequest().getCharacterEncoding();
0351:
0352:                    Time defaultRetractDate = (Time) toolSession
0353:                            .getAttribute(STATE_DEFAULT_RETRACT_TIME);
0354:                    if (defaultRetractDate == null) {
0355:                        defaultRetractDate = TimeService.newTime();
0356:                        toolSession.setAttribute(STATE_DEFAULT_RETRACT_TIME,
0357:                                defaultRetractDate);
0358:                    }
0359:
0360:                    Boolean preventPublicDisplay = (Boolean) toolSession
0361:                            .getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
0362:                    if (preventPublicDisplay == null) {
0363:                        preventPublicDisplay = Boolean.FALSE;
0364:                        toolSession.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY,
0365:                                preventPublicDisplay);
0366:                    }
0367:
0368:                    ContentEntity collection = pipe.getContentEntity();
0369:
0370:                    ListItem parent = new ListItem(collection);
0371:                    parent.setPubviewPossible(!preventPublicDisplay);
0372:                    ListItem item = new ListItem(pipe, parent,
0373:                            defaultRetractDate);
0374:
0375:                    String typeId = pipe.getAction().getTypeId();
0376:                    //List items = newEditItems(collection.getId(), typeId, encoding, defaultCopyrightStatus, preventPublicDisplay.booleanValue(), defaultRetractDate, new Integer(1));
0377:
0378:                    context.put("item", item);
0379:
0380:                    toolSession.setAttribute(STATE_NEW_ATTACHMENT, item);
0381:
0382:                    ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
0383:                            .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
0384:                    if (registry == null) {
0385:                        registry = (ResourceTypeRegistry) ComponentManager
0386:                                .get("org.sakaiproject.content.api.ResourceTypeRegistry");
0387:                        toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
0388:                                registry);
0389:                    }
0390:                    ResourceType typeDef = registry.getType(typeId);
0391:                    context.put("type", typeDef);
0392:
0393:                    context.put("title", (new ResourceTypeLabeler())
0394:                            .getLabel(pipe.getAction()));
0395:                    context.put("instruction", trb
0396:                            .getFormattedMessage("instr.create",
0397:                                    new String[] { typeDef.getLabel() }));
0398:                    context
0399:                            .put(
0400:                                    "required",
0401:                                    trb
0402:                                            .getFormattedMessage(
0403:                                                    "instr.require",
0404:                                                    new String[] { "<span class=\"reqStarInline\">*</span>" }));
0405:
0406:                    // find the ContentHosting service
0407:                    ContentHostingService contentService = (ContentHostingService) toolSession
0408:                            .getAttribute(STATE_CONTENT_SERVICE);
0409:                    if (contentService.isAvailabilityEnabled()) {
0410:                        context.put("availability_is_enabled", Boolean.TRUE);
0411:                    }
0412:
0413:                    ResourcesAction.copyrightChoicesIntoContext(state, context);
0414:                    ResourcesAction.publicDisplayChoicesIntoContext(state,
0415:                            context);
0416:
0417:                    context.put("SITE_ACCESS", AccessMode.SITE.toString());
0418:                    context.put("GROUP_ACCESS", AccessMode.GROUPED.toString());
0419:                    context.put("INHERITED_ACCESS", AccessMode.INHERITED
0420:                            .toString());
0421:                    context.put("PUBLIC_ACCESS", ResourcesAction.PUBLIC_ACCESS);
0422:                }
0423:                return template;
0424:            }
0425:
0426:            /**
0427:             * @param state
0428:             * @param toolSession
0429:             * @param pipe
0430:             */
0431:            protected void finishAction(SessionState state,
0432:                    ToolSession toolSession, ResourceToolActionPipe pipe) {
0433:                ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
0434:                        .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
0435:                if (registry == null) {
0436:                    registry = (ResourceTypeRegistry) ComponentManager
0437:                            .get("org.sakaiproject.content.api.ResourceTypeRegistry");
0438:                    toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
0439:                            registry);
0440:                }
0441:
0442:                ResourceToolAction action = pipe.getAction();
0443:                // use ActionType for this
0444:                switch (action.getActionType()) {
0445:                case CREATE:
0446:                    toolSession.setAttribute(STATE_FILEPICKER_MODE,
0447:                            MODE_ADD_METADATA);
0448:                    break;
0449:                case NEW_UPLOAD:
0450:                    List<ContentResource> resources = ResourcesAction
0451:                            .createResources(pipe);
0452:                    if (resources != null && !resources.isEmpty()) {
0453:                        // expand folder
0454:                        SortedSet<String> expandedCollections = (SortedSet<String>) toolSession
0455:                                .getAttribute(STATE_EXPANDED_COLLECTIONS);
0456:                        expandedCollections.add(resources.get(0)
0457:                                .getContainingCollection().getId());
0458:
0459:                        List<AttachItem> new_items = (List<AttachItem>) toolSession
0460:                                .getAttribute(STATE_ADDED_ITEMS);
0461:                        if (new_items == null) {
0462:                            new_items = new Vector<AttachItem>();
0463:                            toolSession.setAttribute(STATE_ADDED_ITEMS,
0464:                                    new_items);
0465:                        }
0466:
0467:                        ContentResourceFilter filter = (ContentResourceFilter) state
0468:                                .getAttribute(STATE_ATTACHMENT_FILTER);
0469:
0470:                        for (ContentResource resource : resources) {
0471:                            if (filter != null) {
0472:                                if (!filter.allowSelect(resource)) {
0473:                                    ResourceProperties props = resource
0474:                                            .getProperties();
0475:                                    String displayName = props
0476:                                            .getProperty(ResourceProperties.PROP_DISPLAY_NAME);
0477:                                    addAlert(
0478:                                            state,
0479:                                            (String) rb
0480:                                                    .getFormattedMessage(
0481:                                                            "filter",
0482:                                                            new Object[] { displayName }));
0483:                                    continue;
0484:                                }
0485:                            }
0486:                            AttachItem item = new AttachItem(resource);
0487:                            String typeId = resource.getResourceType();
0488:                            item.setResourceType(typeId);
0489:                            ResourceType typedef = registry.getType(typeId);
0490:                            item.setHoverText(typedef
0491:                                    .getLocalizedHoverText(resource));
0492:                            item.setIconLocation(typedef
0493:                                    .getIconLocation(resource));
0494:                            new_items.add(item);
0495:                        }
0496:                        toolSession.setAttribute(STATE_HELPER_CHANGED,
0497:                                Boolean.TRUE.toString());
0498:                    }
0499:                    toolSession.removeAttribute(ResourceToolAction.ACTION_PIPE);
0500:                    toolSession.setAttribute(STATE_FILEPICKER_MODE,
0501:                            MODE_ATTACHMENT_SELECT_INIT);
0502:                    break;
0503:                case NEW_FOLDER:
0504:                    List<ContentCollection> folders = ResourcesAction
0505:                            .createFolders(state, pipe);
0506:                    if (folders != null && !folders.isEmpty()) {
0507:                        // expand folder
0508:                        SortedSet<String> expandedCollections = (SortedSet<String>) toolSession
0509:                                .getAttribute(STATE_EXPANDED_COLLECTIONS);
0510:                        expandedCollections
0511:                                .add(pipe.getContentEntity().getId());
0512:                    }
0513:                    toolSession.removeAttribute(ResourceToolAction.ACTION_PIPE);
0514:                    break;
0515:                case NEW_URLS:
0516:                    List<ContentResource> urls = ResourcesAction.createUrls(
0517:                            state, pipe);
0518:                    if (urls != null && !urls.isEmpty()) {
0519:                        // expand folder
0520:                        SortedSet<String> expandedCollections = (SortedSet<String>) toolSession
0521:                                .getAttribute(STATE_EXPANDED_COLLECTIONS);
0522:                        expandedCollections
0523:                                .add(pipe.getContentEntity().getId());
0524:                    }
0525:                    toolSession.removeAttribute(ResourceToolAction.ACTION_PIPE);
0526:                    break;
0527:                case REVISE_CONTENT:
0528:                    ResourcesAction.reviseContent(pipe);
0529:                    toolSession.removeAttribute(ResourceToolAction.ACTION_PIPE);
0530:                    toolSession.setAttribute(STATE_FILEPICKER_MODE,
0531:                            MODE_ATTACHMENT_SELECT_INIT);
0532:                    break;
0533:                default:
0534:                    toolSession.setAttribute(STATE_FILEPICKER_MODE,
0535:                            MODE_ATTACHMENT_SELECT_INIT);
0536:                }
0537:            }
0538:
0539:            /**
0540:             * @param portlet
0541:             * @param context
0542:             * @param data
0543:             * @param state
0544:             * @return
0545:             */
0546:            protected String buildSelectAttachmentContext(
0547:                    VelocityPortlet portlet, Context context, RunData data,
0548:                    SessionState state) {
0549:                context.put("tlang", rb);
0550:
0551:                ToolSession toolSession = SessionManager
0552:                        .getCurrentToolSession();
0553:
0554:                // find the ContentHosting service
0555:                org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) toolSession
0556:                        .getAttribute(STATE_CONTENT_SERVICE);
0557:
0558:                context.put("contentTypeImageService", toolSession
0559:                        .getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE));
0560:
0561:                context.put("labeler", new ResourceTypeLabeler());
0562:                context.put("ACTION_DELIMITER",
0563:                        ResourceToolAction.ACTION_DELIMITER);
0564:
0565:                List new_items = (List) toolSession
0566:                        .getAttribute(STATE_ADDED_ITEMS);
0567:                if (new_items == null) {
0568:                    new_items = new Vector();
0569:                    toolSession.setAttribute(STATE_ADDED_ITEMS, new_items);
0570:                }
0571:                context.put("attached", new_items);
0572:                context.put("last", new Integer(new_items.size() - 1));
0573:
0574:                Integer max_cardinality = (Integer) toolSession
0575:                        .getAttribute(STATE_ATTACH_CARDINALITY);
0576:                if (max_cardinality == null) {
0577:                    max_cardinality = FilePickerHelper.CARDINALITY_MULTIPLE;
0578:                    toolSession.setAttribute(STATE_ATTACH_CARDINALITY,
0579:                            max_cardinality);
0580:                }
0581:                context.put("max_cardinality", max_cardinality);
0582:                if (new_items.size() < max_cardinality.intValue()) {
0583:                    context.put("can_attach_more", Boolean.TRUE);
0584:                }
0585:
0586:                if (new_items.size() >= max_cardinality.intValue()) {
0587:                    context
0588:                            .put("disable_attach_links", Boolean.TRUE
0589:                                    .toString());
0590:                }
0591:
0592:                if (toolSession.getAttribute(STATE_HELPER_CHANGED) != null) {
0593:                    context.put("list_has_changed", Boolean.TRUE.toString());
0594:                }
0595:
0596:                boolean inMyWorkspace = SiteService.isUserSite(ToolManager
0597:                        .getCurrentPlacement().getContext());
0598:                // context.put("inMyWorkspace", Boolean.toString(inMyWorkspace));
0599:
0600:                boolean atHome = false;
0601:
0602:                // %%STATE_MODE_RESOURCES%%
0603:                //boolean dropboxMode = RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) toolSession.getAttribute(STATE_MODE_RESOURCES));
0604:
0605:                String homeCollectionId = (String) toolSession
0606:                        .getAttribute(STATE_HOME_COLLECTION_ID);
0607:                if (homeCollectionId == null) {
0608:                    homeCollectionId = contentService
0609:                            .getSiteCollection(ToolManager
0610:                                    .getCurrentPlacement().getContext());
0611:                    toolSession.setAttribute(STATE_HOME_COLLECTION_ID,
0612:                            homeCollectionId);
0613:                }
0614:
0615:                // make sure the collectionId is set
0616:                String collectionId = (String) toolSession
0617:                        .getAttribute(STATE_DEFAULT_COLLECTION_ID);
0618:                if (collectionId == null) {
0619:                    collectionId = homeCollectionId;
0620:                }
0621:
0622:                context.put("collectionId", collectionId);
0623:                String navRoot = (String) toolSession
0624:                        .getAttribute(STATE_NAVIGATION_ROOT);
0625:
0626:                // String siteTitle = (String) toolSession.getAttribute (STATE_SITE_TITLE);
0627:                if (collectionId.equals(homeCollectionId)) {
0628:                    atHome = true;
0629:                    //context.put ("collectionDisplayName", toolSession.getAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME));
0630:                }
0631:
0632:                Comparator userSelectedSort = (Comparator) toolSession
0633:                        .getAttribute(STATE_LIST_VIEW_SORT);
0634:
0635:                // set the sort values
0636:                String sortedBy = (String) toolSession
0637:                        .getAttribute(STATE_SORT_BY);
0638:                String sortedAsc = (String) toolSession
0639:                        .getAttribute(STATE_SORT_ASC);
0640:                context.put("currentSortedBy", sortedBy);
0641:                context.put("currentSortAsc", sortedAsc);
0642:                context.put("TRUE", Boolean.TRUE.toString());
0643:
0644:                try {
0645:                    try {
0646:                        contentService.checkCollection(collectionId);
0647:                        context.put("collectionFlag", Boolean.TRUE.toString());
0648:                    } catch (IdUnusedException ex) {
0649:                        if (logger.isDebugEnabled()) {
0650:                            logger
0651:                                    .debug("ResourcesAction.buildSelectAttachment (static) : IdUnusedException: "
0652:                                            + collectionId);
0653:                        }
0654:                        try {
0655:                            ContentCollectionEdit coll = contentService
0656:                                    .addCollection(collectionId);
0657:                            contentService.commitCollection(coll);
0658:                        } catch (IdUsedException inner) {
0659:                            // how can this happen??
0660:                            logger
0661:                                    .warn("ResourcesAction.buildSelectAttachment (static) : IdUsedException: "
0662:                                            + collectionId);
0663:                            throw ex;
0664:                        } catch (IdInvalidException inner) {
0665:                            logger
0666:                                    .warn("ResourcesAction.buildSelectAttachment (static) : IdInvalidException: "
0667:                                            + collectionId);
0668:                            // what now?
0669:                            throw ex;
0670:                        } catch (InconsistentException inner) {
0671:                            logger
0672:                                    .warn("ResourcesAction.buildSelectAttachment (static) : InconsistentException: "
0673:                                            + collectionId);
0674:                            // what now?
0675:                            throw ex;
0676:                        }
0677:                    } catch (TypeException ex) {
0678:                        logger
0679:                                .warn("ResourcesAction.buildSelectAttachment (static) : TypeException.");
0680:                        throw ex;
0681:                    } catch (PermissionException ex) {
0682:                        logger
0683:                                .warn("ResourcesAction.buildSelectAttachment (static) : PermissionException.");
0684:                        throw ex;
0685:                    }
0686:
0687:                    SortedSet<String> expandedCollections = (SortedSet<String>) toolSession
0688:                            .getAttribute(STATE_EXPANDED_COLLECTIONS);
0689:                    if (expandedCollections == null) {
0690:                        expandedCollections = new TreeSet<String>();
0691:                        toolSession.setAttribute(STATE_EXPANDED_COLLECTIONS,
0692:                                expandedCollections);
0693:                    }
0694:                    expandedCollections.add(collectionId);
0695:
0696:                    ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
0697:                            .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
0698:                    if (registry == null) {
0699:                        registry = (ResourceTypeRegistry) ComponentManager
0700:                                .get("org.sakaiproject.content.api.ResourceTypeRegistry");
0701:                        toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
0702:                                registry);
0703:                    }
0704:
0705:                    boolean expandAll = Boolean.TRUE.toString().equals(
0706:                            toolSession.getAttribute(STATE_NEED_TO_EXPAND_ALL));
0707:
0708:                    //state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
0709:
0710:                    List<ListItem> this _site = new Vector<ListItem>();
0711:
0712:                    if (contentService.isInDropbox(collectionId)) {
0713:                        User[] submitters = (User[]) state
0714:                                .getAttribute(FilePickerHelper.FILE_PICKER_SHOW_DROPBOXES);
0715:                        if (submitters != null) {
0716:                            String dropboxId = contentService
0717:                                    .getDropboxCollection();
0718:                            if (dropboxId == null) {
0719:                                contentService.createDropboxCollection();
0720:                                dropboxId = contentService
0721:                                        .getDropboxCollection();
0722:                            }
0723:
0724:                            if (dropboxId == null) {
0725:                                // do nothing
0726:                            } else if (contentService.isDropboxMaintainer()) {
0727:                                for (int i = 0; i < submitters.length; i++) {
0728:                                    User submitter = submitters[i];
0729:                                    String dbId = dropboxId
0730:                                            + StringUtil.trimToZero(submitter
0731:                                                    .getId()) + "/";
0732:                                    try {
0733:                                        ContentCollection db = contentService
0734:                                                .getCollection(dbId);
0735:                                        expandedCollections.add(dbId);
0736:
0737:                                        ListItem item = ListItem.getListItem(
0738:                                                db, (ListItem) null, registry,
0739:                                                expandAll, expandedCollections,
0740:                                                (List<String>) null,
0741:                                                (List<String>) null, 0,
0742:                                                userSelectedSort, false);
0743:                                        List<ListItem> items = item
0744:                                                .convert2list();
0745:                                        ContentResourceFilter filter = (ContentResourceFilter) toolSession
0746:                                                .getAttribute(STATE_ATTACHMENT_FILTER);
0747:                                        if (filter != null) {
0748:                                            items = filterList(items, filter);
0749:                                        }
0750:                                        this _site.addAll(items);
0751:
0752:                                        //							List dbox = getListView(dbId, highlightedItems, (ResourcesBrowseItem) null, false, state);
0753:                                        //							getBrowseItems(dbId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, false, state);
0754:                                        //							if(dbox != null && dbox.size() > 0)
0755:                                        //							{
0756:                                        //								ResourcesBrowseItem root = (ResourcesBrowseItem) dbox.remove(0);
0757:                                        //								// context.put("site", root);
0758:                                        //								root.setName(submitter.getDisplayName() + " " + rb.getString("gen.drop"));
0759:                                        //								root.addMembers(dbox);
0760:                                        //								this_site.add(root);
0761:                                        //							}
0762:                                    } catch (IdUnusedException e) {
0763:                                        // ignore a user's dropbox if it's not defined
0764:                                    }
0765:                                }
0766:                            } else {
0767:                                try {
0768:                                    ContentCollection db = contentService
0769:                                            .getCollection(dropboxId);
0770:                                    expandedCollections.add(dropboxId);
0771:
0772:                                    ListItem item = ListItem.getListItem(db,
0773:                                            null, registry, expandAll,
0774:                                            expandedCollections, null, null, 0,
0775:                                            null, false);
0776:                                    this _site.addAll(item.convert2list());
0777:
0778:                                    //						List dbox = getListView(dropboxId, highlightedItems, (ResourcesBrowseItem) null, false, state);
0779:                                    //						// List dbox = getBrowseItems(dropboxId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, false, state);
0780:                                    //						if(dbox != null && dbox.size() > 0)
0781:                                    //						{
0782:                                    //							ResourcesBrowseItem root = (ResourcesBrowseItem) dbox.remove(0);
0783:                                    //							// context.put("site", root);
0784:                                    //							root.setName(ContentHostingService.getDropboxDisplayName());
0785:                                    //							root.addMembers(dbox);
0786:                                    //							this_site.add(root);
0787:                                    //						}
0788:                                } catch (IdUnusedException e) {
0789:                                    // if an id is unused, ignore it
0790:                                }
0791:                            }
0792:                        }
0793:                    } else {
0794:                        ContentCollection collection = contentService
0795:                                .getCollection(collectionId);
0796:                        ListItem item = ListItem.getListItem(collection, null,
0797:                                registry, expandAll, expandedCollections, null,
0798:                                null, 0, null, false);
0799:                        List<ListItem> items = item.convert2list();
0800:                        ContentResourceFilter filter = (ContentResourceFilter) toolSession
0801:                                .getAttribute(STATE_ATTACHMENT_FILTER);
0802:                        if (filter != null) {
0803:                            items = filterList(items, filter);
0804:                        }
0805:                        this _site.addAll(items);
0806:
0807:                    }
0808:
0809:                    //			List members = getListView(collectionId, highlightedItems, (ResourcesBrowseItem) null, navRoot.equals(homeCollectionId), state);
0810:                    //			// List members = getBrowseItems(collectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, navRoot.equals(homeCollectionId), state);
0811:                    //			if(members != null && members.size() > 0)
0812:                    //			{
0813:                    //				ResourcesBrowseItem root = (ResourcesBrowseItem) members.remove(0);
0814:                    //				if(atHome && dropboxMode)
0815:                    //				{
0816:                    //					root.setName(siteTitle + " " + rb.getString("gen.drop"));
0817:                    //				}
0818:                    //				else if(atHome)
0819:                    //				{
0820:                    //					root.setName(siteTitle + " " + rb.getString("gen.reso"));
0821:                    //				}
0822:                    //				context.put("site", root);
0823:                    //				root.addMembers(members);
0824:                    //				this_site.add(root);
0825:                    //			}
0826:
0827:                    context.put("this_site", this _site);
0828:
0829:                    List other_sites = new Vector();
0830:                    boolean show_all_sites = false;
0831:
0832:                    String allowed_to_see_other_sites = (String) toolSession
0833:                            .getAttribute(STATE_SHOW_ALL_SITES);
0834:                    String show_other_sites = (String) toolSession
0835:                            .getAttribute(STATE_SHOW_OTHER_SITES);
0836:                    context.put("show_other_sites", show_other_sites);
0837:                    if (Boolean.TRUE.toString().equals(
0838:                            allowed_to_see_other_sites)) {
0839:                        context.put("allowed_to_see_other_sites", Boolean.TRUE
0840:                                .toString());
0841:                        show_all_sites = Boolean.TRUE.toString().equals(
0842:                                show_other_sites);
0843:                    }
0844:
0845:                    if (show_all_sites) {
0846:                        // TODO move this to a separate class used by ResourcesAction and FilePickerAction to support paging
0847:
0848:                        List<ListItem> siteCollections = prepPage(state);
0849:                        List<ListItem> otherSites = new Vector<ListItem>();
0850:                        for (ListItem siteCollection : siteCollections) {
0851:                            otherSites.addAll(siteCollection.convert2list());
0852:                        }
0853:                        context.put("other_sites", otherSites);
0854:
0855:                        if (toolSession.getAttribute(STATE_NUM_MESSAGES) != null) {
0856:                            context.put("allMsgNumber", toolSession
0857:                                    .getAttribute(STATE_NUM_MESSAGES)
0858:                                    .toString());
0859:                            context.put("allMsgNumberInt", toolSession
0860:                                    .getAttribute(STATE_NUM_MESSAGES));
0861:                        }
0862:
0863:                        context.put("pagesize", ((Integer) toolSession
0864:                                .getAttribute(STATE_PAGESIZE)).toString());
0865:
0866:                        // find the position of the message that is the top first on the page
0867:                        if ((toolSession.getAttribute(STATE_TOP_MESSAGE_INDEX) != null)
0868:                                && (toolSession.getAttribute(STATE_PAGESIZE) != null)) {
0869:                            int topMsgPos = ((Integer) toolSession
0870:                                    .getAttribute(STATE_TOP_MESSAGE_INDEX))
0871:                                    .intValue() + 1;
0872:                            context.put("topMsgPos", Integer
0873:                                    .toString(topMsgPos));
0874:                            int btmMsgPos = topMsgPos
0875:                                    + ((Integer) toolSession
0876:                                            .getAttribute(STATE_PAGESIZE))
0877:                                            .intValue() - 1;
0878:                            if (toolSession.getAttribute(STATE_NUM_MESSAGES) != null) {
0879:                                int allMsgNumber = ((Integer) toolSession
0880:                                        .getAttribute(STATE_NUM_MESSAGES))
0881:                                        .intValue();
0882:                                if (btmMsgPos > allMsgNumber)
0883:                                    btmMsgPos = allMsgNumber;
0884:                            }
0885:                            context.put("btmMsgPos", Integer
0886:                                    .toString(btmMsgPos));
0887:                        }
0888:
0889:                        boolean goPPButton = toolSession
0890:                                .getAttribute(STATE_PREV_PAGE_EXISTS) != null;
0891:                        context.put("goPPButton", Boolean.toString(goPPButton));
0892:                        boolean goNPButton = toolSession
0893:                                .getAttribute(STATE_NEXT_PAGE_EXISTS) != null;
0894:                        context.put("goNPButton", Boolean.toString(goNPButton));
0895:
0896:                        /*
0897:                        boolean goFPButton = toolSession.getAttribute(STATE_FIRST_PAGE_EXISTS) != null;
0898:                        context.put("goFPButton", Boolean.toString(goFPButton));
0899:                        boolean goLPButton = toolSession.getAttribute(STATE_LAST_PAGE_EXISTS) != null;
0900:                        context.put("goLPButton", Boolean.toString(goLPButton));
0901:                         */
0902:
0903:                        context.put("pagesize", toolSession
0904:                                .getAttribute(STATE_PAGESIZE));
0905:                        // context.put("pagesizes", PAGESIZES);
0906:
0907:                    }
0908:
0909:                    //context.put("listActions", listActions);
0910:                    context.put("counter", new EntityCounter());
0911:
0912:                    // context.put ("other_sites", other_sites);
0913:                    //toolSession.setAttribute(STATE_COLLECTION_ROOTS, all_roots);
0914:                    // context.put ("root", root);
0915:
0916:                    if (show_all_sites) {
0917:                        List messages = prepPage(state);
0918:                        context.put("other_sites", messages);
0919:
0920:                        if (toolSession.getAttribute(STATE_NUM_MESSAGES) != null) {
0921:                            context.put("allMsgNumber", toolSession
0922:                                    .getAttribute(STATE_NUM_MESSAGES)
0923:                                    .toString());
0924:                            context.put("allMsgNumberInt", toolSession
0925:                                    .getAttribute(STATE_NUM_MESSAGES));
0926:                        }
0927:
0928:                        context.put("pagesize", ((Integer) toolSession
0929:                                .getAttribute(STATE_PAGESIZE)).toString());
0930:
0931:                        // find the position of the message that is the top first on the page
0932:                        if ((toolSession.getAttribute(STATE_TOP_MESSAGE_INDEX) != null)
0933:                                && (toolSession.getAttribute(STATE_PAGESIZE) != null)) {
0934:                            int topMsgPos = ((Integer) toolSession
0935:                                    .getAttribute(STATE_TOP_MESSAGE_INDEX))
0936:                                    .intValue() + 1;
0937:                            context.put("topMsgPos", Integer
0938:                                    .toString(topMsgPos));
0939:                            int btmMsgPos = topMsgPos
0940:                                    + ((Integer) toolSession
0941:                                            .getAttribute(STATE_PAGESIZE))
0942:                                            .intValue() - 1;
0943:                            if (toolSession.getAttribute(STATE_NUM_MESSAGES) != null) {
0944:                                int allMsgNumber = ((Integer) toolSession
0945:                                        .getAttribute(STATE_NUM_MESSAGES))
0946:                                        .intValue();
0947:                                if (btmMsgPos > allMsgNumber)
0948:                                    btmMsgPos = allMsgNumber;
0949:                            }
0950:                            context.put("btmMsgPos", Integer
0951:                                    .toString(btmMsgPos));
0952:                        }
0953:
0954:                        boolean goPPButton = toolSession
0955:                                .getAttribute(STATE_PREV_PAGE_EXISTS) != null;
0956:                        context.put("goPPButton", Boolean.toString(goPPButton));
0957:                        boolean goNPButton = toolSession
0958:                                .getAttribute(STATE_NEXT_PAGE_EXISTS) != null;
0959:                        context.put("goNPButton", Boolean.toString(goNPButton));
0960:
0961:                        /*
0962:                        boolean goFPButton = toolSession.getAttribute(STATE_FIRST_PAGE_EXISTS) != null;
0963:                        context.put("goFPButton", Boolean.toString(goFPButton));
0964:                        boolean goLPButton = toolSession.getAttribute(STATE_LAST_PAGE_EXISTS) != null;
0965:                        context.put("goLPButton", Boolean.toString(goLPButton));
0966:                         */
0967:
0968:                        context.put("pagesize", toolSession
0969:                                .getAttribute(STATE_PAGESIZE));
0970:                        // context.put("pagesizes", PAGESIZES);
0971:                    }
0972:
0973:                    // context.put ("root", root);
0974:                    context.put("expandedCollections", expandedCollections);
0975:                    toolSession.setAttribute(STATE_EXPANDED_COLLECTIONS,
0976:                            expandedCollections);
0977:                } catch (IdUnusedException e) {
0978:                    addAlert(state, rb.getString("cannotfind"));
0979:                    context.put("collectionFlag", Boolean.FALSE.toString());
0980:                } catch (TypeException e) {
0981:                    // logger.warn(this + "TypeException.");
0982:                    context.put("collectionFlag", Boolean.FALSE.toString());
0983:                } catch (PermissionException e) {
0984:                    addAlert(state, rb.getString("notpermis1"));
0985:                    context.put("collectionFlag", Boolean.FALSE.toString());
0986:                }
0987:
0988:                context.put("homeCollection", (String) toolSession
0989:                        .getAttribute(STATE_HOME_COLLECTION_ID));
0990:                //		context.put("siteTitle", toolSession.getAttribute(STATE_SITE_TITLE));
0991:                context.put("resourceProperties", contentService
0992:                        .newResourceProperties());
0993:
0994:                try {
0995:                    // TODO: why 'site' here?
0996:                    Site site = SiteService.getSite(ToolManager
0997:                            .getCurrentPlacement().getContext());
0998:                    context.put("siteTitle", site.getTitle());
0999:                } catch (IdUnusedException e) {
1000:                    // logger.warn(this + e.toString());
1001:                }
1002:
1003:                context.put("expandallflag", toolSession
1004:                        .getAttribute(STATE_EXPAND_ALL_FLAG));
1005:                state.removeAttribute(STATE_NEED_TO_EXPAND_ALL);
1006:
1007:                // inform the observing courier that we just updated the page...
1008:                // if there are pending requests to do so they can be cleared
1009:                // justDelivered(state);
1010:
1011:                // pick the template based on whether client wants links or copies
1012:                String template = TEMPLATE_SELECT;
1013:
1014:                if (state.getAttribute(STATE_ATTACH_LINKS) == null) {
1015:                    // user wants copies in hidden attachments area
1016:                    template = TEMPLATE_ATTACH;
1017:                }
1018:
1019:                return template;
1020:                //return TEMPLATE_SELECT;
1021:            }
1022:
1023:            /**
1024:             * @param filter 
1025:             * @param name
1026:             * @return
1027:             */
1028:            private List<ListItem> filterList(List<ListItem> items,
1029:                    ContentResourceFilter filter) {
1030:
1031:                List<ListItem> rv = new Vector<ListItem>();
1032:                for (ListItem item : items) {
1033:                    ContentEntity entity = item.getEntity();
1034:                    if (entity.isCollection() || filter == null
1035:                            || filter.allowView((ContentResource) entity)) {
1036:                        rv.add(item);
1037:                        item
1038:                                .setCanSelect(entity.isResource()
1039:                                        && (filter == null || filter
1040:                                                .allowSelect((ContentResource) entity)));
1041:                    }
1042:                }
1043:                return rv;
1044:            }
1045:
1046:            /**
1047:             * @param state
1048:             */
1049:            protected void cleanup(SessionState state) {
1050:                ToolSession toolSession = SessionManager
1051:                        .getCurrentToolSession();
1052:
1053:                Enumeration attributeNames = toolSession.getAttributeNames();
1054:                while (attributeNames.hasMoreElements()) {
1055:                    String attributeName = (String) attributeNames
1056:                            .nextElement();
1057:                    if (attributeName.startsWith(PREFIX)) {
1058:                        state.removeAttribute(attributeName);
1059:                    }
1060:                }
1061:
1062:                if (toolSession != null) {
1063:                    state
1064:                            .removeAttribute(FilePickerHelper.FILE_PICKER_MAX_ATTACHMENTS);
1065:                    state
1066:                            .removeAttribute(FilePickerHelper.FILE_PICKER_RESOURCE_FILTER);
1067:                    state
1068:                            .removeAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID);
1069:                }
1070:
1071:            } // cleanup
1072:
1073:            /**
1074:             * @param state
1075:             * @param toolSession
1076:             * @return
1077:             */
1078:            protected String initHelperAction(SessionState state,
1079:                    ToolSession toolSession) {
1080:                toolSession
1081:                        .removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
1082:
1083:                ContentHostingService contentService = (ContentHostingService) ComponentManager
1084:                        .get("org.sakaiproject.content.api.ContentHostingService");
1085:                toolSession.setAttribute(STATE_CONTENT_SERVICE, contentService);
1086:                toolSession
1087:                        .setAttribute(
1088:                                STATE_CONTENT_TYPE_IMAGE_SERVICE,
1089:                                ComponentManager
1090:                                        .get("org.sakaiproject.content.api.ContentTypeImageService"));
1091:                toolSession
1092:                        .setAttribute(
1093:                                STATE_RESOURCES_TYPE_REGISTRY,
1094:                                ComponentManager
1095:                                        .get("org.sakaiproject.content.api.ResourceTypeRegistry"));
1096:
1097:                ResourceTypeRegistry registry = (ResourceTypeRegistry) ComponentManager
1098:                        .get("org.sakaiproject.content.api.ResourceTypeRegistry");
1099:                toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
1100:                        registry);
1101:
1102:                //ResourceType type = registry.getType(typeId); 
1103:                // start with a copy of the original attachment list
1104:                List attachments = (List) toolSession
1105:                        .getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
1106:                if (attachments == null) {
1107:                    attachments = EntityManager.newReferenceList();
1108:                }
1109:                toolSession.setAttribute(STATE_ATTACHMENT_ORIGINAL_LIST,
1110:                        attachments);
1111:
1112:                Object attach_links = state
1113:                        .getAttribute(FilePickerHelper.FILE_PICKER_ATTACH_LINKS);
1114:                if (attach_links == null) {
1115:                    toolSession.removeAttribute(STATE_ATTACH_LINKS);
1116:                } else {
1117:                    toolSession.setAttribute(STATE_ATTACH_LINKS, Boolean.TRUE
1118:                            .toString());
1119:                }
1120:
1121:                List<AttachItem> new_items = new Vector<AttachItem>();
1122:                Iterator attachmentIt = attachments.iterator();
1123:                while (attachmentIt.hasNext()) {
1124:                    Reference ref = (Reference) attachmentIt.next();
1125:                    try {
1126:                        ContentResource res = (ContentResource) ref.getEntity();
1127:                        ResourceProperties props = null;
1128:                        String accessUrl = null;
1129:                        if (res == null) {
1130:                            props = contentService.getProperties(ref.getId());
1131:                            accessUrl = contentService.getUrl(ref.getId());
1132:                        } else {
1133:                            props = res.getProperties();
1134:                            accessUrl = res.getUrl();
1135:                        }
1136:
1137:                        String displayName = props
1138:                                .getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
1139:                        String containerId = contentService
1140:                                .getContainingCollectionId(res.getId());
1141:
1142:                        AttachItem item = new AttachItem(ref.getId(),
1143:                                displayName, containerId, accessUrl);
1144:                        item.setContentType(res.getContentType());
1145:                        String typeId = res.getResourceType();
1146:                        item.setResourceType(typeId);
1147:                        ResourceType typedef = registry.getType(typeId);
1148:                        item.setHoverText(typedef.getLocalizedHoverText(res));
1149:                        item.setIconLocation(typedef.getIconLocation(res));
1150:
1151:                        new_items.add(item);
1152:                    } catch (PermissionException e) {
1153:                        logger
1154:                                .info("PermissionException -- User has permission to revise item but lacks permission to view attachment: "
1155:                                        + ref.getId());
1156:                    } catch (IdUnusedException e) {
1157:                        logger
1158:                                .info("IdUnusedException -- An attachment has been deleted: "
1159:                                        + ref.getId());
1160:                    }
1161:                }
1162:                toolSession.setAttribute(STATE_ADDED_ITEMS, new_items);
1163:
1164:                initMessage(toolSession, state);
1165:
1166:                toolSession
1167:                        .setAttribute(
1168:                                STATE_ATTACHMENT_FILTER,
1169:                                toolSession
1170:                                        .getAttribute(FilePickerHelper.FILE_PICKER_RESOURCE_FILTER));
1171:
1172:                String defaultCollectionId = (String) toolSession
1173:                        .getAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID);
1174:                if (defaultCollectionId == null) {
1175:                    defaultCollectionId = contentService
1176:                            .getSiteCollection(ToolManager
1177:                                    .getCurrentPlacement().getContext());
1178:                }
1179:                toolSession.setAttribute(STATE_DEFAULT_COLLECTION_ID,
1180:                        defaultCollectionId);
1181:
1182:                state.setAttribute(STATE_MODE, MODE_HELPER);
1183:                toolSession.setAttribute(STATE_FILEPICKER_MODE,
1184:                        MODE_ATTACHMENT_SELECT);
1185:
1186:                // TODO: Should check sakai.properties
1187:                toolSession.setAttribute(STATE_SHOW_ALL_SITES, Boolean.TRUE
1188:                        .toString());
1189:
1190:                // state attribute ResourcesAction.STATE_ATTACH_TOOL_NAME should be set with a string to indicate name of tool
1191:                String toolName = ToolManager.getCurrentPlacement().getTitle();
1192:                toolSession.setAttribute(STATE_ATTACH_TOOL_NAME, toolName);
1193:
1194:                Object max_cardinality = toolSession
1195:                        .getAttribute(FilePickerHelper.FILE_PICKER_MAX_ATTACHMENTS);
1196:                if (max_cardinality != null) {
1197:                    toolSession.setAttribute(STATE_ATTACH_CARDINALITY,
1198:                            max_cardinality);
1199:                }
1200:
1201:                if (toolSession.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE) == null) {
1202:                    toolSession.setAttribute(STATE_FILE_UPLOAD_MAX_SIZE,
1203:                            ServerConfigurationService.getString(
1204:                                    "content.upload.max", "1"));
1205:                }
1206:
1207:                return MODE_HELPER;
1208:            }
1209:
1210:            /**
1211:             * @param toolSession
1212:             * @param state
1213:             */
1214:            protected void initMessage(ToolSession toolSession,
1215:                    SessionState state) {
1216:                String title = (String) toolSession
1217:                        .getAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT);
1218:                toolSession
1219:                        .removeAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT);
1220:                if (title == null) {
1221:                    toolSession.removeAttribute(STATE_ATTACH_TITLE);
1222:                } else {
1223:                    toolSession.setAttribute(STATE_ATTACH_TITLE, title);
1224:                }
1225:
1226:                String instruction = (String) toolSession
1227:                        .getAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT);
1228:                toolSession
1229:                        .removeAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT);
1230:                if (instruction == null) {
1231:                    toolSession.removeAttribute(STATE_ATTACH_INSTRUCTION);
1232:                } else {
1233:                    toolSession.setAttribute(STATE_ATTACH_INSTRUCTION,
1234:                            instruction);
1235:                }
1236:
1237:                String subtitle = (String) toolSession
1238:                        .getAttribute(FilePickerHelper.FILE_PICKER_SUBTITLE_TEXT);
1239:                toolSession
1240:                        .removeAttribute(FilePickerHelper.FILE_PICKER_SUBTITLE_TEXT);
1241:                if (subtitle == null) {
1242:                    toolSession.removeAttribute(STATE_ATTACH_SUBTITLE);
1243:                } else {
1244:                    toolSession.setAttribute(STATE_ATTACH_SUBTITLE, subtitle);
1245:                }
1246:
1247:            }
1248:
1249:            /**
1250:             * Populate the state object, if needed - override to do something!
1251:             */
1252:            protected void initState(SessionState state,
1253:                    VelocityPortlet portlet, RunData data) {
1254:                super .initState(state, portlet, (JetspeedRunData) data);
1255:                ToolSession toolSession = SessionManager
1256:                        .getCurrentToolSession();
1257:                if (toolSession.getAttribute(STATE_SESSION_INITIALIZED) == null) {
1258:                    initHelperAction(state, toolSession);
1259:                    toolSession.setAttribute(STATE_SESSION_INITIALIZED,
1260:                            Boolean.TRUE);
1261:                }
1262:
1263:            } // initState
1264:
1265:            /**
1266:             * @param data
1267:             */
1268:            public void doAttachitem(RunData data) {
1269:                SessionState state = ((JetspeedRunData) data)
1270:                        .getPortletSessionState(((JetspeedRunData) data)
1271:                                .getJs_peid());
1272:                ToolSession toolSession = SessionManager
1273:                        .getCurrentToolSession();
1274:                ParameterParser params = data.getParameters();
1275:
1276:                //toolSession.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
1277:
1278:                String itemId = params.getString("itemId");
1279:
1280:                Object attach_links = toolSession
1281:                        .getAttribute(STATE_ATTACH_LINKS);
1282:
1283:                if (attach_links == null) {
1284:                    attachCopy(itemId, state);
1285:                } else {
1286:                    attachLink(itemId, state);
1287:                }
1288:
1289:                List<AttachItem> removed = (List<AttachItem>) toolSession
1290:                        .getAttribute(STATE_REMOVED_ITEMS);
1291:                if (removed == null) {
1292:                    removed = new Vector<AttachItem>();
1293:                    toolSession.setAttribute(STATE_REMOVED_ITEMS, removed);
1294:                }
1295:                Iterator<AttachItem> removeIt = removed.iterator();
1296:                while (removeIt.hasNext()) {
1297:                    AttachItem item = removeIt.next();
1298:                    if (item.getId().equals(itemId)) {
1299:                        removeIt.remove();
1300:                        break;
1301:                    }
1302:                }
1303:
1304:                toolSession.setAttribute(STATE_FILEPICKER_MODE,
1305:                        MODE_ATTACHMENT_SELECT_INIT);
1306:
1307:            } // doAttachitem
1308:
1309:            /**
1310:             * @param data
1311:             */
1312:            public void doAttachupload(RunData data) {
1313:                SessionState state = ((JetspeedRunData) data)
1314:                        .getPortletSessionState(((JetspeedRunData) data)
1315:                                .getJs_peid());
1316:                ToolSession toolSession = SessionManager
1317:                        .getCurrentToolSession();
1318:                ParameterParser params = data.getParameters();
1319:
1320:                ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
1321:                        .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
1322:                if (registry == null) {
1323:                    registry = (ResourceTypeRegistry) ComponentManager
1324:                            .get("org.sakaiproject.content.api.ResourceTypeRegistry");
1325:                    toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
1326:                            registry);
1327:                }
1328:                //ResourceType type = registry.getType(typeId); 
1329:
1330:                String max_file_size_mb = (String) toolSession
1331:                        .getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
1332:                int max_bytes = 1024 * 1024;
1333:                try {
1334:                    max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
1335:                } catch (Exception e) {
1336:                    // if unable to parse an integer from the value
1337:                    // in the properties file, use 1 MB as a default
1338:                    max_file_size_mb = "1";
1339:                    max_bytes = 1024 * 1024;
1340:                }
1341:
1342:                FileItem fileitem = null;
1343:                try {
1344:                    fileitem = params.getFileItem("upload");
1345:                } catch (Exception e) {
1346:
1347:                }
1348:                if (fileitem == null) {
1349:                    // "The user submitted a file to upload but it was too big!"
1350:                    addAlert(state, rb.getString("size") + " "
1351:                            + max_file_size_mb + "MB "
1352:                            + rb.getString("exceeded2"));
1353:                } else if (fileitem.getFileName() == null
1354:                        || fileitem.getFileName().length() == 0) {
1355:                    addAlert(state, rb.getString("choosefile7"));
1356:                } else if (fileitem.getFileName().length() > 0) {
1357:                    String filename = Validator.getFileName(fileitem
1358:                            .getFileName());
1359:                    byte[] bytes = fileitem.get();
1360:                    String contentType = fileitem.getContentType();
1361:
1362:                    if (bytes.length >= max_bytes) {
1363:                        addAlert(state, rb.getString("size") + " "
1364:                                + max_file_size_mb + "MB "
1365:                                + rb.getString("exceeded2"));
1366:                    } else if (bytes.length > 0) {
1367:                        // we just want the file name part - strip off any drive and path stuff
1368:                        String name = Validator.getFileName(filename);
1369:                        String resourceId = Validator.escapeResourceName(name);
1370:
1371:                        ContentHostingService contentService = (ContentHostingService) toolSession
1372:                                .getAttribute(STATE_CONTENT_SERVICE);
1373:
1374:                        // make a set of properties to add for the new resource
1375:                        ResourcePropertiesEdit props = contentService
1376:                                .newResourceProperties();
1377:                        props.addProperty(ResourceProperties.PROP_DISPLAY_NAME,
1378:                                name);
1379:                        props.addProperty(ResourceProperties.PROP_DESCRIPTION,
1380:                                filename);
1381:
1382:                        // make an attachment resource for this URL
1383:                        try {
1384:                            String siteId = ToolManager.getCurrentPlacement()
1385:                                    .getContext();
1386:
1387:                            String toolName = (String) toolSession
1388:                                    .getAttribute(STATE_ATTACH_TOOL_NAME);
1389:                            if (toolName == null) {
1390:                                toolName = ToolManager.getCurrentPlacement()
1391:                                        .getTitle();
1392:                                toolSession.setAttribute(
1393:                                        STATE_ATTACH_TOOL_NAME, toolName);
1394:                            }
1395:
1396:                            ContentResource attachment = contentService
1397:                                    .addAttachmentResource(resourceId, siteId,
1398:                                            toolName, contentType, bytes, props);
1399:
1400:                            ContentResourceFilter filter = (ContentResourceFilter) state
1401:                                    .getAttribute(STATE_ATTACHMENT_FILTER);
1402:                            if (filter == null
1403:                                    || filter.allowSelect(attachment)) {
1404:                                // do nothing
1405:                            } else {
1406:                                addAlert(state, (String) rb
1407:                                        .getFormattedMessage("filter",
1408:                                                new Object[] { name }));
1409:                                return;
1410:                            }
1411:
1412:                            List<AttachItem> new_items = (List<AttachItem>) toolSession
1413:                                    .getAttribute(STATE_ADDED_ITEMS);
1414:                            if (new_items == null) {
1415:                                new_items = new Vector<AttachItem>();
1416:                                toolSession.setAttribute(STATE_ADDED_ITEMS,
1417:                                        new_items);
1418:                            }
1419:
1420:                            String containerId = contentService
1421:                                    .getContainingCollectionId(attachment
1422:                                            .getId());
1423:                            String accessUrl = attachment.getUrl();
1424:
1425:                            AttachItem item = new AttachItem(
1426:                                    attachment.getId(), filename, containerId,
1427:                                    accessUrl);
1428:                            item.setContentType(contentType);
1429:                            String typeId = ResourceType.TYPE_UPLOAD;
1430:                            item.setResourceType(typeId);
1431:                            ResourceType typedef = registry.getType(typeId);
1432:                            item.setHoverText(typedef
1433:                                    .getLocalizedHoverText(attachment));
1434:                            item.setIconLocation(typedef
1435:                                    .getIconLocation(attachment));
1436:                            new_items.add(item);
1437:
1438:                            toolSession.setAttribute(STATE_HELPER_CHANGED,
1439:                                    Boolean.TRUE.toString());
1440:                        } catch (PermissionException e) {
1441:                            addAlert(state, rb.getString("notpermis4"));
1442:                        } catch (OverQuotaException e) {
1443:                            addAlert(state, rb.getString("overquota"));
1444:                        } catch (ServerOverloadException e) {
1445:                            addAlert(state, rb.getString("failed"));
1446:                        } catch (IdInvalidException ignore) {
1447:                            // other exceptions should be caught earlier
1448:                        } catch (InconsistentException ignore) {
1449:                            // other exceptions should be caught earlier
1450:                        } catch (IdUsedException ignore) {
1451:                            // other exceptions should be caught earlier
1452:                        } catch (RuntimeException e) {
1453:                            logger
1454:                                    .debug("ResourcesAction.doAttachupload ***** Unknown Exception ***** "
1455:                                            + e.getMessage());
1456:                            addAlert(state, rb.getString("failed"));
1457:                        }
1458:                    } else {
1459:                        addAlert(state, rb.getString("choosefile7"));
1460:                    }
1461:                }
1462:
1463:                toolSession.setAttribute(STATE_FILEPICKER_MODE,
1464:                        MODE_ATTACHMENT_SELECT_INIT);
1465:
1466:            } // doAttachupload
1467:
1468:            /**
1469:             * @param data
1470:             */
1471:            public void doAttachurl(RunData data) {
1472:                SessionState state = ((JetspeedRunData) data)
1473:                        .getPortletSessionState(((JetspeedRunData) data)
1474:                                .getJs_peid());
1475:                ToolSession toolSession = SessionManager
1476:                        .getCurrentToolSession();
1477:                ParameterParser params = data.getParameters();
1478:
1479:                ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
1480:                        .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
1481:                if (registry == null) {
1482:                    registry = (ResourceTypeRegistry) ComponentManager
1483:                            .get("org.sakaiproject.content.api.ResourceTypeRegistry");
1484:                    toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
1485:                            registry);
1486:                }
1487:                //ResourceType type = registry.getType(typeId); 
1488:
1489:                String url = params.getCleanString("url");
1490:
1491:                ContentHostingService contentService = (ContentHostingService) toolSession
1492:                        .getAttribute(STATE_CONTENT_SERVICE);
1493:
1494:                ResourcePropertiesEdit resourceProperties = contentService
1495:                        .newResourceProperties();
1496:                resourceProperties.addProperty(
1497:                        ResourceProperties.PROP_DISPLAY_NAME, url);
1498:                resourceProperties.addProperty(
1499:                        ResourceProperties.PROP_DESCRIPTION, url);
1500:
1501:                resourceProperties.addProperty(
1502:                        ResourceProperties.PROP_IS_COLLECTION, Boolean.FALSE
1503:                                .toString());
1504:
1505:                try {
1506:                    url = validateURL(url);
1507:
1508:                    byte[] newUrl = url.getBytes();
1509:                    String newResourceId = Validator.escapeResourceName(url);
1510:
1511:                    String siteId = ToolManager.getCurrentPlacement()
1512:                            .getContext();
1513:                    String toolName = (String) (String) toolSession
1514:                            .getAttribute(STATE_ATTACH_TOOL_NAME);
1515:                    if (toolName == null) {
1516:                        toolName = ToolManager.getCurrentPlacement().getTitle();
1517:                        toolSession.setAttribute(STATE_ATTACH_TOOL_NAME,
1518:                                toolName);
1519:                    }
1520:
1521:                    ContentResource attachment = contentService
1522:                            .addAttachmentResource(newResourceId, siteId,
1523:                                    toolName, ResourceProperties.TYPE_URL,
1524:                                    newUrl, resourceProperties);
1525:
1526:                    List<AttachItem> new_items = (List<AttachItem>) toolSession
1527:                            .getAttribute(STATE_ADDED_ITEMS);
1528:                    if (new_items == null) {
1529:                        new_items = new Vector();
1530:                        toolSession.setAttribute(STATE_ADDED_ITEMS, new_items);
1531:                    }
1532:
1533:                    String containerId = contentService
1534:                            .getContainingCollectionId(attachment.getId());
1535:                    String accessUrl = attachment.getUrl();
1536:
1537:                    AttachItem item = new AttachItem(attachment.getId(), url,
1538:                            containerId, accessUrl);
1539:                    item.setContentType(ResourceProperties.TYPE_URL);
1540:                    String typeId = ResourceType.TYPE_URL;
1541:                    item.setResourceType(typeId);
1542:                    ResourceType typedef = registry.getType(typeId);
1543:                    item
1544:                            .setHoverText(typedef
1545:                                    .getLocalizedHoverText(attachment));
1546:                    item.setIconLocation(typedef.getIconLocation(attachment));
1547:                    new_items.add(item);
1548:                    toolSession.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE
1549:                            .toString());
1550:                } catch (MalformedURLException e) {
1551:                    // invalid url
1552:                    addAlert(state, rb.getString("validurl") + " \"" + url
1553:                            + "\" " + rb.getString("invalid"));
1554:                } catch (PermissionException e) {
1555:                    addAlert(state, rb.getString("notpermis4"));
1556:                } catch (OverQuotaException e) {
1557:                    addAlert(state, rb.getString("overquota"));
1558:                } catch (ServerOverloadException e) {
1559:                    addAlert(state, rb.getString("failed"));
1560:                } catch (IdInvalidException ignore) {
1561:                    // other exceptions should be caught earlier
1562:                } catch (IdUsedException ignore) {
1563:                    // other exceptions should be caught earlier
1564:                } catch (InconsistentException ignore) {
1565:                    // other exceptions should be caught earlier
1566:                } catch (RuntimeException e) {
1567:                    logger
1568:                            .debug("ResourcesAction.doAttachurl ***** Unknown Exception ***** "
1569:                                    + e.getMessage());
1570:                    addAlert(state, rb.getString("failed"));
1571:                }
1572:
1573:                toolSession.setAttribute(STATE_FILEPICKER_MODE,
1574:                        MODE_ATTACHMENT_SELECT_INIT);
1575:
1576:            } // doAttachurl
1577:
1578:            /**
1579:             * doCancel to return to the previous state
1580:             */
1581:            public void doCancel(RunData data) {
1582:                SessionState state = ((JetspeedRunData) data)
1583:                        .getPortletSessionState(((JetspeedRunData) data)
1584:                                .getJs_peid());
1585:                ToolSession toolSession = SessionManager
1586:                        .getCurrentToolSession();
1587:
1588:                //cleanup(state);
1589:
1590:                toolSession.setAttribute(STATE_HELPER_CANCELED_BY_USER,
1591:                        Boolean.TRUE.toString());
1592:
1593:                toolSession.setAttribute(STATE_FILEPICKER_MODE,
1594:                        MODE_ATTACHMENT_DONE);
1595:
1596:            } // doCancel
1597:
1598:            public void doRemoveitem(RunData data) {
1599:                SessionState state = ((JetspeedRunData) data)
1600:                        .getPortletSessionState(((JetspeedRunData) data)
1601:                                .getJs_peid());
1602:                ToolSession toolSession = SessionManager
1603:                        .getCurrentToolSession();
1604:                ParameterParser params = data.getParameters();
1605:
1606:                //toolSession.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
1607:
1608:                String itemId = params.getString("itemId");
1609:
1610:                List<AttachItem> new_items = (List<AttachItem>) toolSession
1611:                        .getAttribute(STATE_ADDED_ITEMS);
1612:
1613:                AttachItem item = null;
1614:                boolean found = false;
1615:
1616:                Iterator<AttachItem> it = new_items.iterator();
1617:                while (!found && it.hasNext()) {
1618:                    item = it.next();
1619:                    if (item.getId().equals(itemId)) {
1620:                        found = true;
1621:                    }
1622:                }
1623:
1624:                if (found && item != null) {
1625:                    new_items.remove(item);
1626:                    List<AttachItem> removed = (List<AttachItem>) toolSession
1627:                            .getAttribute(STATE_REMOVED_ITEMS);
1628:                    if (removed == null) {
1629:                        removed = new Vector<AttachItem>();
1630:                        toolSession.setAttribute(STATE_REMOVED_ITEMS, removed);
1631:                    }
1632:                    removed.add(item);
1633:
1634:                    toolSession.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE
1635:                            .toString());
1636:                }
1637:
1638:            } // doRemoveitem
1639:
1640:            public void doAddattachments(RunData data) {
1641:                SessionState state = ((JetspeedRunData) data)
1642:                        .getPortletSessionState(((JetspeedRunData) data)
1643:                                .getJs_peid());
1644:                ToolSession toolSession = SessionManager
1645:                        .getCurrentToolSession();
1646:                ParameterParser params = data.getParameters();
1647:
1648:                ContentHostingService contentService = (ContentHostingService) toolSession
1649:                        .getAttribute(STATE_CONTENT_SERVICE);
1650:
1651:                //		// cancel copy if there is one in progress
1652:                //		if(! Boolean.FALSE.toString().equals(toolSession.getAttribute (STATE_COPY_FLAG)))
1653:                //		{
1654:                //			initCopyContext(state);
1655:                //		}
1656:                //
1657:                //		// cancel move if there is one in progress
1658:                //		if(! Boolean.FALSE.toString().equals(toolSession.getAttribute (STATE_MOVE_FLAG)))
1659:                //		{
1660:                //			initMoveContext(state);
1661:                //		}
1662:
1663:                //		toolSession.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
1664:
1665:                List<AttachItem> new_items = (List<AttachItem>) toolSession
1666:                        .getAttribute(STATE_ADDED_ITEMS);
1667:                if (new_items == null) {
1668:                    new_items = new Vector<AttachItem>();
1669:                    toolSession.setAttribute(STATE_ADDED_ITEMS, new_items);
1670:                }
1671:
1672:                List<AttachItem> removed = (List<AttachItem>) toolSession
1673:                        .getAttribute(STATE_REMOVED_ITEMS);
1674:                if (removed == null) {
1675:                    removed = new Vector<AttachItem>();
1676:                    toolSession.setAttribute(STATE_REMOVED_ITEMS, removed);
1677:                }
1678:
1679:                Iterator<AttachItem> removeIt = removed.iterator();
1680:                while (removeIt.hasNext()) {
1681:                    AttachItem item = removeIt.next();
1682:                    try {
1683:                        if (contentService.isAttachmentResource(item.getId())) {
1684:                            ContentResourceEdit edit = contentService
1685:                                    .editResource(item.getId());
1686:                            contentService.removeResource(edit);
1687:                            ContentCollectionEdit coll = contentService
1688:                                    .editCollection(item.getCollectionId());
1689:                            contentService.removeCollection(coll);
1690:                        }
1691:                    } catch (Exception ignore) {
1692:                        // log failure 
1693:                    }
1694:                }
1695:                state.removeAttribute(STATE_REMOVED_ITEMS);
1696:
1697:                // add to the attachments vector
1698:                List<Reference> original_attachments = (List<Reference>) toolSession
1699:                        .getAttribute(STATE_ATTACHMENT_ORIGINAL_LIST);
1700:
1701:                original_attachments.clear();
1702:
1703:                Iterator<AttachItem> it = new_items.iterator();
1704:                while (it.hasNext()) {
1705:                    AttachItem item = it.next();
1706:
1707:                    try {
1708:                        Reference ref = EntityManager
1709:                                .newReference(contentService.getReference(item
1710:                                        .getId()));
1711:                        original_attachments.add(ref);
1712:                    } catch (Exception e) {
1713:                        logger.warn("doAddattachments " + e);
1714:                    }
1715:                }
1716:
1717:                state.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS,
1718:                        original_attachments);
1719:                // cleanupState(state);
1720:
1721:                // end up in main mode
1722:                //		resetCurrentMode(state);
1723:
1724:                String field = null;
1725:
1726:                // if there is at least one attachment
1727:                if (original_attachments.size() > 0) {
1728:                    //check -- jim
1729:                    toolSession.setAttribute(
1730:                            AttachmentAction.STATE_HAS_ATTACHMENT_BEFORE,
1731:                            Boolean.TRUE);
1732:                }
1733:
1734:                toolSession.setAttribute(STATE_FILEPICKER_MODE,
1735:                        MODE_ATTACHMENT_DONE);
1736:
1737:                //		if(field != null)
1738:                //		{
1739:                //			int index = 0;
1740:                //			String fieldname = field;
1741:                //			Matcher matcher = INDEXED_FORM_FIELD_PATTERN.matcher(field.trim());
1742:                //			if(matcher.matches())
1743:                //			{
1744:                //				fieldname = matcher.group(0);
1745:                //				index = Integer.parseInt(matcher.group(1));
1746:                //			}
1747:                //
1748:                //			// we are trying to attach a link to a form field and there is at least one attachment
1749:                //			if(new_items == null)
1750:                //			{
1751:                //				new_items = (List) current_stack_frame.get(ResourcesAction.STATE_HELPER_NEW_ITEMS);
1752:                //				if(new_items == null)
1753:                //				{
1754:                //					new_items = (List) toolSession.getAttribute(ResourcesAction.STATE_HELPER_NEW_ITEMS);
1755:                //				}
1756:                //			}
1757:                //			ResourcesEditItem edit_item = null;
1758:                //			List edit_items = (List) current_stack_frame.get(ResourcesAction.STATE_STACK_CREATE_ITEMS);
1759:                //			if(edit_items == null)
1760:                //			{
1761:                //				edit_item = (ResourcesEditItem) current_stack_frame.get(ResourcesAction.STATE_STACK_EDIT_ITEM);
1762:                //			}
1763:                //			else
1764:                //			{
1765:                //				edit_item = (ResourcesEditItem) edit_items.get(0);
1766:                //			}
1767:                //			if(edit_item != null)
1768:                //			{
1769:                //				Reference ref = (Reference) attachments.get(0);
1770:                //				edit_item.setPropertyValue(fieldname, index, ref);
1771:                //			}
1772:                //		}
1773:            }
1774:
1775:            /**
1776:             * @param itemId
1777:             * @param state
1778:             */
1779:            public void attachCopy(String itemId, SessionState state) {
1780:                ToolSession toolSession = SessionManager
1781:                        .getCurrentToolSession();
1782:                ContentHostingService contentService = (ContentHostingService) toolSession
1783:                        .getAttribute(STATE_CONTENT_SERVICE);
1784:                ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
1785:                        .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
1786:                if (registry == null) {
1787:                    registry = (ResourceTypeRegistry) ComponentManager
1788:                            .get("org.sakaiproject.content.api.ResourceTypeRegistry");
1789:                    toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
1790:                            registry);
1791:                }
1792:                //ResourceType type = registry.getType(typeId); 
1793:
1794:                List<AttachItem> new_items = (List<AttachItem>) toolSession
1795:                        .getAttribute(STATE_ADDED_ITEMS);
1796:                if (new_items == null) {
1797:                    new_items = new Vector<AttachItem>();
1798:                    toolSession.setAttribute(STATE_ADDED_ITEMS, new_items);
1799:                }
1800:
1801:                boolean found = false;
1802:                Iterator<AttachItem> it = new_items.iterator();
1803:                while (!found && it.hasNext()) {
1804:                    AttachItem item = it.next();
1805:                    if (item.getId().equals(itemId)) {
1806:                        found = true;
1807:                    }
1808:                }
1809:
1810:                if (!found) {
1811:                    ContentResourceFilter filter = (ContentResourceFilter) state
1812:                            .getAttribute(STATE_ATTACHMENT_FILTER);
1813:
1814:                    ContentResource resource = null;
1815:                    ResourceToolAction copyAction = null;
1816:                    ContentResource attachment = null;
1817:                    try {
1818:                        resource = contentService.getResource(itemId);
1819:
1820:                        String typeId = resource.getResourceType();
1821:                        ResourceType typedef = registry.getType(typeId);
1822:                        copyAction = typedef
1823:                                .getAction(ResourceToolAction.PASTE_COPIED);
1824:                        if (copyAction == null) {
1825:                            List<ResourceToolAction> actions = typedef
1826:                                    .getActions(ResourcesAction.PASTE_COPIED_ACTIONS);
1827:                            if (actions != null && actions.size() > 0) {
1828:                                copyAction = actions.get(0);
1829:                            }
1830:                        }
1831:                        if (copyAction == null) {
1832:                            addAlert(state, "TODO: Unable to attach this item");
1833:                            return;
1834:                        } else if (!(copyAction instanceof  ServiceLevelAction)) {
1835:                            addAlert(state, "TODO: Unable to attach this item");
1836:                            return;
1837:                        }
1838:
1839:                        ((ServiceLevelAction) copyAction)
1840:                                .initializeAction(EntityManager
1841:                                        .newReference(resource.getReference()));
1842:
1843:                        ResourceProperties props = resource.getProperties();
1844:                        if (filter != null) {
1845:                            if (!filter.allowSelect(resource)) {
1846:                                String displayName = props
1847:                                        .getProperty(ResourceProperties.PROP_DISPLAY_NAME);
1848:                                addAlert(state, (String) rb
1849:                                        .getFormattedMessage("filter",
1850:                                                new Object[] { displayName }));
1851:                                return;
1852:                            }
1853:                        }
1854:
1855:                        ResourcePropertiesEdit newprops = contentService
1856:                                .newResourceProperties();
1857:                        newprops.set(props);
1858:
1859:                        byte[] bytes = resource.getContent();
1860:                        String contentType = resource.getContentType();
1861:                        String filename = Validator.getFileName(itemId);
1862:                        String resourceId = Validator
1863:                                .escapeResourceName(filename);
1864:
1865:                        String siteId = ToolManager.getCurrentPlacement()
1866:                                .getContext();
1867:                        String toolName = (String) toolSession
1868:                                .getAttribute(STATE_ATTACH_TOOL_NAME);
1869:                        if (toolName == null) {
1870:                            toolName = ToolManager.getCurrentPlacement()
1871:                                    .getTitle();
1872:                        }
1873:
1874:                        // TODO: we're making a copy, so we need to invoke the copy methods related to the resource-type registration 
1875:                        attachment = contentService.addAttachmentResource(
1876:                                resourceId, siteId, toolName, contentType,
1877:                                bytes, props);
1878:
1879:                        String displayName = newprops
1880:                                .getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
1881:                        String containerId = contentService
1882:                                .getContainingCollectionId(attachment.getId());
1883:                        String accessUrl = attachment.getUrl();
1884:
1885:                        AttachItem item = new AttachItem(attachment.getId(),
1886:                                displayName, containerId, accessUrl);
1887:                        item.setContentType(contentType);
1888:                        item.setResourceType(typeId);
1889:                        item.setHoverText(typedef
1890:                                .getLocalizedHoverText(resource));
1891:                        item.setIconLocation(typedef.getIconLocation(resource));
1892:                        new_items.add(item);
1893:                        toolSession.setAttribute(STATE_HELPER_CHANGED,
1894:                                Boolean.TRUE.toString());
1895:                    } catch (PermissionException e) {
1896:                        addAlert(state, rb.getString("notpermis4"));
1897:                    } catch (OverQuotaException e) {
1898:                        addAlert(state, rb.getString("overquota"));
1899:                    } catch (ServerOverloadException e) {
1900:                        addAlert(state, rb.getString("failed"));
1901:                    } catch (IdInvalidException ignore) {
1902:                        // other exceptions should be caught earlier
1903:                    } catch (TypeException ignore) {
1904:                        // other exceptions should be caught earlier
1905:                    } catch (IdUnusedException ignore) {
1906:                        // other exceptions should be caught earlier
1907:                    } catch (IdUsedException ignore) {
1908:                        // other exceptions should be caught earlier
1909:                    } catch (InconsistentException ignore) {
1910:                        // other exceptions should be caught earlier
1911:                    } catch (RuntimeException e) {
1912:                        logger
1913:                                .debug("ResourcesAction.attachItem ***** Unknown Exception ***** "
1914:                                        + e.getMessage());
1915:                        addAlert(state, rb.getString("failed"));
1916:                    } finally {
1917:                        if (copyAction == null) {
1918:                            // do nothing
1919:                        } else if (copyAction instanceof  ServiceLevelAction) {
1920:                            if (attachment == null) {
1921:                                ((ServiceLevelAction) copyAction)
1922:                                        .cancelAction(EntityManager
1923:                                                .newReference(resource
1924:                                                        .getReference()));
1925:                            } else {
1926:                                ((ServiceLevelAction) copyAction)
1927:                                        .finalizeAction(EntityManager
1928:                                                .newReference(attachment
1929:                                                        .getReference()));
1930:                            }
1931:                        }
1932:                    }
1933:                }
1934:                toolSession.setAttribute(STATE_ADDED_ITEMS, new_items);
1935:            }
1936:
1937:            /**
1938:             * @param itemId
1939:             * @param state
1940:             */
1941:            public void attachLink(String itemId, SessionState state) {
1942:                ToolSession toolSession = SessionManager
1943:                        .getCurrentToolSession();
1944:                org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) toolSession
1945:                        .getAttribute(STATE_CONTENT_SERVICE);
1946:                ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
1947:                        .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
1948:                if (registry == null) {
1949:                    registry = (ResourceTypeRegistry) ComponentManager
1950:                            .get("org.sakaiproject.content.api.ResourceTypeRegistry");
1951:                    toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
1952:                            registry);
1953:                }
1954:                //ResourceType type = registry.getType(typeId); 
1955:
1956:                List<AttachItem> new_items = (List<AttachItem>) toolSession
1957:                        .getAttribute(STATE_ADDED_ITEMS);
1958:                if (new_items == null) {
1959:                    new_items = new Vector<AttachItem>();
1960:                    toolSession.setAttribute(STATE_ADDED_ITEMS, new_items);
1961:                }
1962:
1963:                Integer max_cardinality = (Integer) toolSession
1964:                        .getAttribute(STATE_ATTACH_CARDINALITY);
1965:                if (max_cardinality == null) {
1966:                    max_cardinality = FilePickerHelper.CARDINALITY_MULTIPLE;
1967:                    toolSession.setAttribute(STATE_ATTACH_CARDINALITY,
1968:                            max_cardinality);
1969:                }
1970:
1971:                boolean found = false;
1972:                Iterator<AttachItem> it = new_items.iterator();
1973:                while (!found && it.hasNext()) {
1974:                    AttachItem item = it.next();
1975:                    if (item.getId().equals(itemId)) {
1976:                        found = true;
1977:                    }
1978:                }
1979:
1980:                if (!found) {
1981:                    try {
1982:                        String toolName = (String) toolSession
1983:                                .getAttribute(STATE_ATTACH_TOOL_NAME);
1984:                        if (toolName == null) {
1985:                            toolName = ToolManager.getCurrentPlacement()
1986:                                    .getTitle();
1987:                            toolSession.setAttribute(STATE_ATTACH_TOOL_NAME,
1988:                                    toolName);
1989:                        }
1990:                        ContentResource res = contentService
1991:                                .getResource(itemId);
1992:
1993:                        ResourceProperties props = res.getProperties();
1994:
1995:                        ContentResourceFilter filter = (ContentResourceFilter) state
1996:                                .getAttribute(STATE_ATTACHMENT_FILTER);
1997:                        if (filter != null) {
1998:                            if (!filter.allowSelect(res)) {
1999:                                String displayName = props
2000:                                        .getProperty(ResourceProperties.PROP_DISPLAY_NAME);
2001:                                addAlert(state, (String) rb
2002:                                        .getFormattedMessage("filter",
2003:                                                new Object[] { displayName }));
2004:                                return;
2005:                            }
2006:                        }
2007:
2008:                        String displayName = props
2009:                                .getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
2010:                        String containerId = contentService
2011:                                .getContainingCollectionId(itemId);
2012:                        String accessUrl = res.getUrl();
2013:
2014:                        AttachItem item = new AttachItem(itemId, displayName,
2015:                                containerId, accessUrl);
2016:                        item.setContentType(res.getContentType());
2017:                        String typeId = res.getResourceType();
2018:                        item.setResourceType(typeId);
2019:                        ResourceType typedef = registry.getType(typeId);
2020:                        item.setHoverText(typedef.getLocalizedHoverText(res));
2021:                        item.setIconLocation(typedef.getIconLocation(res));
2022:
2023:                        new_items.add(item);
2024:                        toolSession.setAttribute(STATE_HELPER_CHANGED,
2025:                                Boolean.TRUE.toString());
2026:                    } catch (PermissionException e) {
2027:                        addAlert(state, rb.getString("notpermis4"));
2028:                    } catch (TypeException ignore) {
2029:                        // other exceptions should be caught earlier
2030:                    } catch (IdUnusedException ignore) {
2031:                        // other exceptions should be caught earlier
2032:                    } catch (RuntimeException e) {
2033:                        logger
2034:                                .debug("ResourcesAction.attachItem ***** Unknown Exception ***** "
2035:                                        + e.getMessage());
2036:                        addAlert(state, rb.getString("failed"));
2037:                    }
2038:                }
2039:                toolSession.setAttribute(STATE_ADDED_ITEMS, new_items);
2040:            }
2041:
2042:            /**
2043:             * Allow extension classes to control which build method gets called for this pannel
2044:             * @param panel
2045:             * @return
2046:             */
2047:            protected String panelMethodName(String panel) {
2048:                // we are always calling buildMainPanelContext
2049:                return "buildMainPanelContext";
2050:            }
2051:
2052:            /* (non-Javadoc)
2053:             * @see org.sakaiproject.cheftool.VelocityPortletPaneledAction#toolModeDispatch(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
2054:             */
2055:            protected void toolModeDispatch(String methodBase,
2056:                    String methodExt, HttpServletRequest req,
2057:                    HttpServletResponse res) throws ToolException {
2058:                ToolSession toolSession = SessionManager
2059:                        .getCurrentToolSession();
2060:                SessionState state = getState(req);
2061:
2062:                if (MODE_ATTACHMENT_DONE.equals(toolSession
2063:                        .getAttribute(STATE_FILEPICKER_MODE))) {
2064:                    // canceled, so restore the original list 
2065:                    List attachments = (List) toolSession
2066:                            .getAttribute(STATE_ATTACHMENT_ORIGINAL_LIST);
2067:
2068:                    if (attachments == null) {
2069:                        attachments = EntityManager.newReferenceList();
2070:                    }
2071:
2072:                    if (toolSession.getAttribute(STATE_HELPER_CANCELED_BY_USER) == null) {
2073:                        // not canceled.  The attachments should have been added by doAddattachments
2074:                    } else {
2075:                        // canceled, so restore original list
2076:                        toolSession.setAttribute(
2077:                                FilePickerHelper.FILE_PICKER_ATTACHMENTS,
2078:                                attachments);
2079:                        toolSession.setAttribute(
2080:                                FilePickerHelper.FILE_PICKER_CANCEL,
2081:                                Boolean.TRUE.toString());
2082:                    }
2083:
2084:                    cleanup(state);
2085:
2086:                    Tool tool = ToolManager.getCurrentTool();
2087:
2088:                    String url = (String) SessionManager
2089:                            .getCurrentToolSession().getAttribute(
2090:                                    tool.getId() + Tool.HELPER_DONE_URL);
2091:
2092:                    SessionManager.getCurrentToolSession().removeAttribute(
2093:                            tool.getId() + Tool.HELPER_DONE_URL);
2094:
2095:                    try {
2096:                        res.sendRedirect(url);
2097:                    } catch (IOException e) {
2098:                        logger.warn("IOException: ", e);
2099:                    }
2100:                    return;
2101:                } else if (sendToHelper(req, res, req.getPathInfo())) {
2102:                    return;
2103:                } else {
2104:                    super .toolModeDispatch(methodBase, methodExt, req, res);
2105:                }
2106:            }
2107:
2108:            /**
2109:             * @param data
2110:             */
2111:            public void doCompleteCreateWizard(RunData data) {
2112:                ToolSession toolSession = SessionManager
2113:                        .getCurrentToolSession();
2114:                SessionState state = ((JetspeedRunData) data)
2115:                        .getPortletSessionState(((JetspeedRunData) data)
2116:                                .getJs_peid());
2117:
2118:                // find the ContentHosting service
2119:                ContentHostingService contentService = (ContentHostingService) toolSession
2120:                        .getAttribute(STATE_CONTENT_SERVICE);
2121:
2122:                ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
2123:                        .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
2124:                if (registry == null) {
2125:                    registry = (ResourceTypeRegistry) ComponentManager
2126:                            .get("org.sakaiproject.content.api.ResourceTypeRegistry");
2127:                    toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
2128:                            registry);
2129:                }
2130:                //ResourceType type = registry.getType(typeId); 
2131:
2132:                ListItem item = (ListItem) toolSession
2133:                        .getAttribute(STATE_NEW_ATTACHMENT);
2134:
2135:                // get the parameter-parser
2136:                ParameterParser params = data.getParameters();
2137:
2138:                String user_action = params.getString("user_action");
2139:
2140:                String displayName = null;
2141:
2142:                ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession
2143:                        .getAttribute(ResourceToolAction.ACTION_PIPE);
2144:
2145:                if (user_action == null) {
2146:
2147:                } else if (user_action.equals("save")) {
2148:
2149:                    item.captureProperties(params, ListItem.DOT + "0");
2150:                    String collectionId = pipe.getContentEntity().getId();
2151:                    try {
2152:                        // title
2153:                        displayName = item.getName();
2154:
2155:                        //params.getString("name" + ListItem.DOT + "0");
2156:                        String basename = displayName.trim();
2157:                        String extension = "";
2158:                        if (displayName.contains(".")) {
2159:                            String[] parts = displayName.split("\\.");
2160:                            basename = parts[0];
2161:                            if (parts.length > 1) {
2162:                                extension = parts[parts.length - 1];
2163:                            }
2164:
2165:                            for (int i = 1; i < parts.length - 1; i++) {
2166:                                basename += "." + parts[i];
2167:                            }
2168:                        }
2169:
2170:                        // create resource
2171:                        ContentResourceEdit resource = contentService
2172:                                .addResource(collectionId, basename, extension,
2173:                                        MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
2174:
2175:                        item.updateContentResourceEdit(resource);
2176:
2177:                        String resourceType = null;
2178:                        if (pipe != null) {
2179:                            ResourceToolAction action = pipe.getAction();
2180:                            if (action == null) {
2181:
2182:                            } else {
2183:                                if (action instanceof  InteractionAction) {
2184:                                    InteractionAction iAction = (InteractionAction) action;
2185:                                    iAction.finalizeAction(EntityManager
2186:                                            .newReference(resource
2187:                                                    .getReference()), pipe
2188:                                            .getInitializationId());
2189:                                }
2190:                                resourceType = action.getTypeId();
2191:                            }
2192:                        }
2193:
2194:                        resource.setResourceType(resourceType);
2195:
2196:                        byte[] content = pipe.getRevisedContent();
2197:                        if (content == null) {
2198:                            InputStream stream = pipe.getRevisedContentStream();
2199:                            if (stream == null) {
2200:                                logger
2201:                                        .warn("pipe with null content and null stream: "
2202:                                                + pipe.getFileName());
2203:                            } else {
2204:                                resource.setContent(stream);
2205:                            }
2206:                        } else {
2207:                            resource.setContent(content);
2208:                        }
2209:
2210:                        resource.setContentType(pipe.getRevisedMimeType());
2211:
2212:                        ResourcePropertiesEdit resourceProperties = resource
2213:                                .getPropertiesEdit();
2214:                        resourceProperties.addProperty(
2215:                                ResourceProperties.PROP_DISPLAY_NAME,
2216:                                displayName);
2217:
2218:                        Map values = pipe.getRevisedResourceProperties();
2219:                        Iterator valueIt = values.keySet().iterator();
2220:                        while (valueIt.hasNext()) {
2221:                            String pname = (String) valueIt.next();
2222:                            String pvalue = (String) values.get(pname);
2223:                            resourceProperties.addProperty(pname, pvalue);
2224:                        }
2225:
2226:                        // notification
2227:                        int noti = NotificationService.NOTI_NONE;
2228:                        // read the notification options
2229:                        String notification = params.getString("notify");
2230:                        if ("r".equals(notification)) {
2231:                            noti = NotificationService.NOTI_REQUIRED;
2232:                        } else if ("o".equals(notification)) {
2233:                            noti = NotificationService.NOTI_OPTIONAL;
2234:                        }
2235:
2236:                        contentService.commitResource(resource, noti);
2237:
2238:                        toolSession
2239:                                .removeAttribute(ResourceToolAction.ACTION_PIPE);
2240:
2241:                        // show folder if in hierarchy view
2242:                        SortedSet expandedCollections = (SortedSet) toolSession
2243:                                .getAttribute(STATE_EXPANDED_COLLECTIONS);
2244:                        expandedCollections.add(collectionId);
2245:
2246:                        if (checkSelctItemFilter(resource, state)) {
2247:                            AttachItem new_item = new AttachItem(resource
2248:                                    .getId(), displayName, collectionId,
2249:                                    resource.getUrl());
2250:                            new_item.setContentType(resource.getContentType());
2251:                            String typeId = resource.getResourceType();
2252:                            new_item.setResourceType(typeId);
2253:                            ResourceType typedef = registry.getType(typeId);
2254:                            new_item.setHoverText(typedef
2255:                                    .getLocalizedHoverText(resource));
2256:                            new_item.setIconLocation(typedef
2257:                                    .getIconLocation(resource));
2258:
2259:                            List new_items = (List) toolSession
2260:                                    .getAttribute(STATE_ADDED_ITEMS);
2261:                            if (new_items == null) {
2262:                                new_items = new Vector();
2263:                                toolSession.setAttribute(STATE_ADDED_ITEMS,
2264:                                        new_items);
2265:                            }
2266:
2267:                            new_items.add(new_item);
2268:                        } else {
2269:                            addAlert(state, (String) rb.getFormattedMessage(
2270:                                    "filter", new Object[] { displayName }));
2271:                        }
2272:
2273:                        toolSession.setAttribute(STATE_HELPER_CHANGED,
2274:                                Boolean.TRUE.toString());
2275:                        toolSession.setAttribute(STATE_FILEPICKER_MODE,
2276:                                MODE_ATTACHMENT_SELECT_INIT);
2277:                    } catch (IdUnusedException e) {
2278:                        logger.warn("IdUnusedException", e);
2279:                    } catch (PermissionException e) {
2280:                        logger.warn("PermissionException", e);
2281:                    } catch (IdInvalidException e) {
2282:                        logger.warn("IdInvalidException", e);
2283:                    } catch (ServerOverloadException e) {
2284:                        logger.warn("ServerOverloadException", e);
2285:                    } catch (OverQuotaException e) {
2286:                        // TODO Auto-generated catch block
2287:                        logger.warn("OverQuotaException ", e);
2288:                    } catch (IdUniquenessException e) {
2289:                        // TODO Auto-generated catch block
2290:                        logger.warn("IdUniquenessException ", e);
2291:                    } catch (IdLengthException e) {
2292:                        // TODO Auto-generated catch block
2293:                        logger.warn("IdLengthException ", e);
2294:                    }
2295:
2296:                } else if (user_action.equals("cancel")) {
2297:                    if (pipe != null) {
2298:                        ResourceToolAction action = pipe.getAction();
2299:                        if (action == null) {
2300:
2301:                        } else {
2302:                            if (action instanceof  InteractionAction) {
2303:                                InteractionAction iAction = (InteractionAction) action;
2304:                                iAction.cancelAction(null, pipe
2305:                                        .getInitializationId());
2306:                            }
2307:                        }
2308:                    }
2309:                    toolSession.setAttribute(STATE_FILEPICKER_MODE,
2310:                            MODE_ATTACHMENT_SELECT_INIT);
2311:                }
2312:            }
2313:
2314:            /**
2315:             * @param data
2316:             */
2317:            public void doDispatchAction(RunData data) {
2318:                ToolSession toolSession = SessionManager
2319:                        .getCurrentToolSession();
2320:                SessionState state = ((JetspeedRunData) data)
2321:                        .getPortletSessionState(((JetspeedRunData) data)
2322:                                .getJs_peid());
2323:
2324:                // find the ContentHosting service
2325:                ContentHostingService contentService = (ContentHostingService) toolSession
2326:                        .getAttribute(STATE_CONTENT_SERVICE);
2327:
2328:                // get the parameter-parser
2329:                ParameterParser params = data.getParameters();
2330:
2331:                String action_string = params.getString("rt_action");
2332:                String selectedItemId = params.getString("selectedItemId");
2333:
2334:                String[] parts = action_string
2335:                        .split(ResourceToolAction.ACTION_DELIMITER);
2336:                String typeId = parts[0];
2337:                String actionId = parts[1];
2338:
2339:                // ResourceType type = getResourceType(selectedItemId, state);
2340:                ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
2341:                        .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
2342:                if (registry == null) {
2343:                    registry = (ResourceTypeRegistry) ComponentManager
2344:                            .get("org.sakaiproject.content.api.ResourceTypeRegistry");
2345:                    toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
2346:                            registry);
2347:                }
2348:                ResourceType type = registry.getType(typeId);
2349:
2350:                Reference reference = EntityManager.newReference(contentService
2351:                        .getReference(selectedItemId));
2352:
2353:                ResourceToolAction action = type.getAction(actionId);
2354:                if (action == null) {
2355:
2356:                } else if (action instanceof  InteractionAction) {
2357:                    toolSession.setAttribute(
2358:                            ResourcesAction.STATE_CREATE_WIZARD_COLLECTION_ID,
2359:                            selectedItemId);
2360:
2361:                    ContentEntity entity = (ContentEntity) reference
2362:                            .getEntity();
2363:                    InteractionAction iAction = (InteractionAction) action;
2364:                    String intitializationId = iAction
2365:                            .initializeAction(reference);
2366:
2367:                    ResourceToolActionPipe pipe = registry.newPipe(
2368:                            intitializationId, action);
2369:                    pipe.setContentEntity(entity);
2370:                    pipe.setHelperId(iAction.getHelperId());
2371:
2372:                    toolSession.setAttribute(ResourceToolAction.ACTION_PIPE,
2373:                            pipe);
2374:
2375:                    ResourceProperties props = entity.getProperties();
2376:
2377:                    List propKeys = iAction.getRequiredPropertyKeys();
2378:                    if (propKeys != null) {
2379:                        Iterator it = propKeys.iterator();
2380:                        while (it.hasNext()) {
2381:                            String key = (String) it.next();
2382:                            Object value = props.get(key);
2383:                            if (value == null) {
2384:                                // do nothing
2385:                            } else if (value instanceof  String) {
2386:                                pipe.setResourceProperty(key, (String) value);
2387:                            } else if (value instanceof  List) {
2388:                                pipe.setResourceProperty(key, (List) value);
2389:                            }
2390:                        }
2391:                    }
2392:
2393:                    if (entity.isResource()) {
2394:                        try {
2395:                            pipe.setMimeType(((ContentResource) entity)
2396:                                    .getContentType());
2397:                            pipe.setContent(((ContentResource) entity)
2398:                                    .getContent());
2399:                        } catch (ServerOverloadException e) {
2400:                            logger
2401:                                    .warn(
2402:                                            this 
2403:                                                    + ".doDispatchAction ServerOverloadException",
2404:                                            e);
2405:                        }
2406:                    }
2407:
2408:                    startHelper(data.getRequest(), iAction.getHelperId(),
2409:                            MAIN_PANEL);
2410:                } else if (action instanceof  ServiceLevelAction) {
2411:                    ServiceLevelAction sAction = (ServiceLevelAction) action;
2412:                    sAction.initializeAction(reference);
2413:                    switch (sAction.getActionType()) {
2414:                    case COPY:
2415:                        List<String> items_to_be_copied = new Vector<String>();
2416:                        if (selectedItemId != null) {
2417:                            items_to_be_copied.add(selectedItemId);
2418:                        }
2419:                        toolSession.setAttribute(
2420:                                ResourcesAction.STATE_ITEMS_TO_BE_COPIED,
2421:                                items_to_be_copied);
2422:                        break;
2423:                    case DUPLICATE:
2424:                        //duplicateItem(state, selectedItemId, contentService.getContainingCollectionId(selectedItemId));
2425:                        break;
2426:                    case DELETE:
2427:                        //deleteItem(state, selectedItemId);
2428:                        if (toolSession.getAttribute(STATE_MESSAGE) == null) {
2429:                            // need new context
2430:                            //toolSession.setAttribute (STATE_MODE, MODE_DELETE_FINISH);
2431:                        }
2432:                        break;
2433:                    case MOVE:
2434:                        List<String> items_to_be_moved = new Vector<String>();
2435:                        if (selectedItemId != null) {
2436:                            items_to_be_moved.add(selectedItemId);
2437:                        }
2438:                        //toolSession.setAttribute(STATE_ITEMS_TO_BE_MOVED, items_to_be_moved);
2439:                        break;
2440:                    case VIEW_METADATA:
2441:                        break;
2442:                    case REVISE_METADATA:
2443:                        toolSession
2444:                                .setAttribute(
2445:                                        ResourcesAction.STATE_REVISE_PROPERTIES_ENTITY_ID,
2446:                                        selectedItemId);
2447:                        toolSession.setAttribute(
2448:                                ResourcesAction.STATE_REVISE_PROPERTIES_ACTION,
2449:                                action);
2450:                        toolSession.setAttribute(STATE_FILEPICKER_MODE,
2451:                                ResourcesAction.MODE_REVISE_METADATA);
2452:                        break;
2453:                    case CUSTOM_TOOL_ACTION:
2454:                        // do nothing
2455:                        break;
2456:                    case NEW_UPLOAD:
2457:                        break;
2458:                    case NEW_FOLDER:
2459:                        break;
2460:                    case NEW_URLS:
2461:                        break;
2462:                    case CREATE:
2463:                        break;
2464:                    case REVISE_CONTENT:
2465:                        break;
2466:                    case REPLACE_CONTENT:
2467:                        break;
2468:                    case PASTE_MOVED:
2469:                        //pasteItem(state, selectedItemId);
2470:                        break;
2471:                    case PASTE_COPIED:
2472:                        //pasteItem(state, selectedItemId);
2473:                        break;
2474:                    case REVISE_ORDER:
2475:                        //toolSession.setAttribute(STATE_REORDER_FOLDER, selectedItemId);
2476:                        //toolSession.setAttribute(STATE_FILEPICKER_MODE, MODE_REORDER);
2477:                        break;
2478:                    default:
2479:                        break;
2480:                    }
2481:                    // not quite right for actions involving user interaction in Resources tool.
2482:                    // For example, with delete, this should be after the confirmation and actual deletion
2483:                    // Need mechanism to remember to do it later
2484:                    sAction.finalizeAction(reference);
2485:
2486:                }
2487:            }
2488:
2489:            /**
2490:             * Add the collection id into the expanded collection list
2491:             * @throws PermissionException
2492:             * @throws TypeException
2493:             * @throws IdUnusedException
2494:             */
2495:            public void doExpand_collection(RunData data)
2496:                    throws IdUnusedException, TypeException,
2497:                    PermissionException {
2498:                ToolSession toolSession = SessionManager
2499:                        .getCurrentToolSession();
2500:                SessionState state = ((JetspeedRunData) data)
2501:                        .getPortletSessionState(((JetspeedRunData) data)
2502:                                .getJs_peid());
2503:                SortedSet expandedItems = (SortedSet) toolSession
2504:                        .getAttribute(STATE_EXPANDED_COLLECTIONS);
2505:                if (expandedItems == null) {
2506:                    expandedItems = new TreeSet();
2507:                    toolSession.setAttribute(STATE_EXPANDED_COLLECTIONS,
2508:                            expandedItems);
2509:                }
2510:
2511:                //get the ParameterParser from RunData
2512:                ParameterParser params = data.getParameters();
2513:
2514:                String id = params.getString("collectionId");
2515:                expandedItems.add(id);
2516:
2517:            } // doExpand_collection
2518:
2519:            /**
2520:             * Remove the collection id from the expanded collection list
2521:             */
2522:            public void doCollapse_collection(RunData data) {
2523:                ToolSession toolSession = SessionManager
2524:                        .getCurrentToolSession();
2525:                SessionState state = ((JetspeedRunData) data)
2526:                        .getPortletSessionState(((JetspeedRunData) data)
2527:                                .getJs_peid());
2528:                SortedSet expandedItems = (SortedSet) toolSession
2529:                        .getAttribute(STATE_EXPANDED_COLLECTIONS);
2530:                if (expandedItems == null) {
2531:                    expandedItems = new TreeSet();
2532:                }
2533:                //		Map folderSortMap = (Map) toolSession.getAttribute(STATE_EXPANDED_FOLDER_SORT_MAP);
2534:                //		if(folderSortMap == null)
2535:                //		{
2536:                //			folderSortMap = new Hashtable();
2537:                //			toolSession.setAttribute(STATE_EXPANDED_FOLDER_SORT_MAP, folderSortMap);
2538:                //		}
2539:
2540:                //get the ParameterParser from RunData
2541:                ParameterParser params = data.getParameters();
2542:                String collectionId = params.getString("collectionId");
2543:
2544:                SortedSet newSet = new TreeSet();
2545:                Iterator l = expandedItems.iterator();
2546:                while (l.hasNext()) {
2547:                    // remove the collection id and all of the subcollections
2548:                    //		    Resource collection = (Resource) l.next();
2549:                    //			String id = (String) collection.getId();
2550:                    String id = (String) l.next();
2551:
2552:                    if (id.indexOf(collectionId) == -1) {
2553:                        //			newSet.put(id,collection);
2554:                        newSet.add(id);
2555:                    }
2556:                    //			else
2557:                    //			{
2558:                    //				folderSortMap.remove(id);
2559:                    //			}
2560:                }
2561:
2562:                toolSession.setAttribute(STATE_EXPANDED_COLLECTIONS, newSet);
2563:
2564:            } // doCollapse_collection
2565:
2566:            /**
2567:             * Expand all the collection resources.
2568:             */
2569:            public void doExpandall(RunData data) {
2570:                ToolSession toolSession = SessionManager
2571:                        .getCurrentToolSession();
2572:                // get the state object
2573:                SessionState state = ((JetspeedRunData) data)
2574:                        .getPortletSessionState(((JetspeedRunData) data)
2575:                                .getJs_peid());
2576:
2577:                //get the ParameterParser from RunData
2578:                ParameterParser params = data.getParameters();
2579:
2580:                // save the current selections
2581:                Set selectedSet = new TreeSet();
2582:                String[] selectedItems = params.getStrings("selectedMembers");
2583:                if (selectedItems != null) {
2584:                    selectedSet.addAll(Arrays.asList(selectedItems));
2585:                }
2586:                toolSession.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
2587:
2588:                // expansion actually occurs in getBrowseItems method.
2589:                toolSession.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.TRUE
2590:                        .toString());
2591:                toolSession.setAttribute(STATE_NEED_TO_EXPAND_ALL, Boolean.TRUE
2592:                        .toString());
2593:
2594:            } // doExpandall
2595:
2596:            /**
2597:             * Unexpand all the collection resources
2598:             */
2599:            public void doUnexpandall(RunData data) {
2600:                ToolSession toolSession = SessionManager
2601:                        .getCurrentToolSession();
2602:                // get the state object
2603:                SessionState state = ((JetspeedRunData) data)
2604:                        .getPortletSessionState(((JetspeedRunData) data)
2605:                                .getJs_peid());
2606:
2607:                //get the ParameterParser from RunData
2608:                ParameterParser params = data.getParameters();
2609:
2610:                // save the current selections
2611:                Set selectedSet = new TreeSet();
2612:                String[] selectedItems = params.getStrings("selectedMembers");
2613:                if (selectedItems != null) {
2614:                    selectedSet.addAll(Arrays.asList(selectedItems));
2615:                }
2616:                toolSession.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
2617:
2618:                toolSession.setAttribute(STATE_EXPANDED_COLLECTIONS,
2619:                        new TreeSet());
2620:                // toolSession.setAttribute(STATE_EXPANDED_FOLDER_SORT_MAP, new Hashtable());
2621:                toolSession.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.FALSE
2622:                        .toString());
2623:
2624:            } // doUnexpandall
2625:
2626:            /**
2627:             * @param data
2628:             */
2629:            public void doShowOtherSites(RunData data) {
2630:                ToolSession toolSession = SessionManager
2631:                        .getCurrentToolSession();
2632:                SessionState state = ((JetspeedRunData) data)
2633:                        .getPortletSessionState(((JetspeedRunData) data)
2634:                                .getJs_peid());
2635:
2636:                //get the ParameterParser from RunData
2637:                ParameterParser params = data.getParameters();
2638:
2639:                // save the current selections
2640:                Set selectedSet = new TreeSet();
2641:                String[] selectedItems = params.getStrings("selectedMembers");
2642:                if (selectedItems != null) {
2643:                    selectedSet.addAll(Arrays.asList(selectedItems));
2644:                }
2645:                toolSession.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
2646:
2647:                toolSession.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.TRUE
2648:                        .toString());
2649:            }
2650:
2651:            /**
2652:             * @param data
2653:             */
2654:            public void doHideOtherSites(RunData data) {
2655:                ToolSession toolSession = SessionManager
2656:                        .getCurrentToolSession();
2657:                SessionState state = ((JetspeedRunData) data)
2658:                        .getPortletSessionState(((JetspeedRunData) data)
2659:                                .getJs_peid());
2660:
2661:                toolSession.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.FALSE
2662:                        .toString());
2663:
2664:                //get the ParameterParser from RunData
2665:                ParameterParser params = data.getParameters();
2666:
2667:                // save the current selections
2668:                Set selectedSet = new TreeSet();
2669:                String[] selectedItems = params.getStrings("selectedMembers");
2670:                if (selectedItems != null) {
2671:                    selectedSet.addAll(Arrays.asList(selectedItems));
2672:                }
2673:                toolSession.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
2674:
2675:            }
2676:
2677:            /**
2678:             * @param resource
2679:             * @param state
2680:             * @return
2681:             */
2682:            protected boolean checkSelctItemFilter(ContentResource resource,
2683:                    SessionState state) {
2684:                ToolSession toolSession = SessionManager
2685:                        .getCurrentToolSession();
2686:                ContentResourceFilter filter = (ContentResourceFilter) toolSession
2687:                        .getAttribute(STATE_ATTACHMENT_FILTER);
2688:
2689:                if (filter != null) {
2690:                    return filter.allowSelect(resource);
2691:                }
2692:                return true;
2693:            }
2694:
2695:            /**
2696:             * Find the resource name of a given resource id or filepath.
2697:             * 
2698:             * @param id
2699:             *        The resource id.
2700:             * @return the resource name.
2701:             */
2702:            protected static String isolateName(String id) {
2703:                if (id == null)
2704:                    return null;
2705:                if (id.length() == 0)
2706:                    return null;
2707:
2708:                // take after the last resource path separator, not counting one at the very end if there
2709:                boolean lastIsSeparator = id.charAt(id.length() - 1) == '/';
2710:                return id.substring(id.lastIndexOf('/', id.length() - 2) + 1,
2711:                        (lastIsSeparator ? id.length() - 1 : id.length()));
2712:
2713:            } // isolateName
2714:
2715:            /**
2716:             * @param url
2717:             * @return
2718:             * @throws MalformedURLException
2719:             */
2720:            protected static String validateURL(String url)
2721:                    throws MalformedURLException {
2722:                if (url.equals(NULL_STRING)) {
2723:                    // ignore the empty url field
2724:                } else if (url.indexOf("://") == -1) {
2725:                    // if it's missing the transport, add http://
2726:                    url = "http://" + url;
2727:                }
2728:
2729:                if (!url.equals(NULL_STRING)) {
2730:                    // valid protocol?
2731:                    try {
2732:                        // test to see if the input validates as a URL.
2733:                        // Checks string for format only.
2734:                        URL u = new URL(url);
2735:                    } catch (MalformedURLException e1) {
2736:                        try {
2737:                            Pattern pattern = Pattern
2738:                                    .compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
2739:                            Matcher matcher = pattern.matcher(url);
2740:                            if (matcher.matches()) {
2741:                                // if URL has "unknown" protocol, check remaider with
2742:                                // "http" protocol and accept input if that validates.
2743:                                URL test = new URL("http://" + matcher.group(2));
2744:                            } else {
2745:                                throw e1;
2746:                            }
2747:                        } catch (MalformedURLException e2) {
2748:                            throw e1;
2749:                        }
2750:                    }
2751:                }
2752:                return url;
2753:            }
2754:
2755:            /**
2756:             * AttachItem
2757:             *
2758:             */
2759:            public static class AttachItem {
2760:                protected String m_id;
2761:                protected String m_displayName;
2762:                protected String m_accessUrl;
2763:                protected String m_collectionId;
2764:                protected String m_contentType;
2765:                protected String m_resourceType;
2766:                protected String hoverText;
2767:                protected String iconLocation;
2768:
2769:                /**
2770:                 * @param id
2771:                 * @param displayName
2772:                 * @param collectionId
2773:                 * @param accessUrl
2774:                 */
2775:                public AttachItem(String id, String displayName,
2776:                        String collectionId, String accessUrl) {
2777:                    m_id = id;
2778:                    m_displayName = displayName;
2779:                    m_collectionId = collectionId;
2780:                    m_accessUrl = accessUrl;
2781:                }
2782:
2783:                /**
2784:                 * @param resource
2785:                 */
2786:                public AttachItem(ContentEntity entity) {
2787:                    m_id = entity.getId();
2788:                    m_displayName = entity.getProperties().getProperty(
2789:                            ResourceProperties.PROP_DISPLAY_NAME);
2790:                    m_collectionId = entity.getContainingCollection().getId();
2791:                    m_accessUrl = entity.getUrl();
2792:                    if (entity instanceof  ContentResource) {
2793:                        m_contentType = ((ContentResource) entity)
2794:                                .getContentType();
2795:                    }
2796:                    m_resourceType = entity.getResourceType();
2797:
2798:                }
2799:
2800:                /**
2801:                 * @param resourceType
2802:                 */
2803:                public void setResourceType(String resourceType) {
2804:                    this .m_resourceType = resourceType;
2805:                }
2806:
2807:                /**
2808:                 * @return Returns the accessUrl.
2809:                 */
2810:                public String getAccessUrl() {
2811:                    return m_accessUrl;
2812:                }
2813:
2814:                /**
2815:                 * @param accessUrl The accessUrl to set.
2816:                 */
2817:                public void setAccessUrl(String accessUrl) {
2818:                    m_accessUrl = accessUrl;
2819:                }
2820:
2821:                /**
2822:                 * @return Returns the collectionId.
2823:                 */
2824:                public String getCollectionId() {
2825:                    return m_collectionId;
2826:                }
2827:
2828:                /**
2829:                 * @param collectionId The collectionId to set.
2830:                 */
2831:                public void setCollectionId(String collectionId) {
2832:                    m_collectionId = collectionId;
2833:                }
2834:
2835:                /**
2836:                 * @return Returns the id.
2837:                 */
2838:                public String getId() {
2839:                    return m_id;
2840:                }
2841:
2842:                /**
2843:                 * @param id The id to set.
2844:                 */
2845:                public void setId(String id) {
2846:                    m_id = id;
2847:                }
2848:
2849:                /**
2850:                 * @return Returns the name.
2851:                 */
2852:                public String getDisplayName() {
2853:                    String displayName = m_displayName;
2854:                    if (displayName == null || displayName.trim().equals("")) {
2855:                        displayName = isolateName(m_id);
2856:                    }
2857:                    return displayName;
2858:                }
2859:
2860:                /**
2861:                 * @param name The name to set.
2862:                 */
2863:                public void setDisplayName(String name) {
2864:                    m_displayName = name;
2865:                }
2866:
2867:                /**
2868:                 * @return Returns the contentType.
2869:                 */
2870:                public String getContentType() {
2871:                    return m_contentType;
2872:                }
2873:
2874:                /**
2875:                 * @param contentType
2876:                 */
2877:                public void setContentType(String contentType) {
2878:                    this .m_contentType = contentType;
2879:                }
2880:
2881:                /**
2882:                 * @return the resourceType
2883:                 */
2884:                public String getResourceType() {
2885:                    return m_resourceType;
2886:                }
2887:
2888:                public String getHoverText() {
2889:                    return hoverText;
2890:                }
2891:
2892:                public void setHoverText(String hoverText) {
2893:                    this .hoverText = hoverText;
2894:                }
2895:
2896:                public String getIconLocation() {
2897:                    return iconLocation;
2898:                }
2899:
2900:                public void setIconLocation(String iconLocation) {
2901:                    if (iconLocation == null) {
2902:                        ContentTypeImageService imageService = (ContentTypeImageService) ComponentManager
2903:                                .get("org.sakaiproject.content.api.ContentTypeImageService");
2904:                        if (this .m_contentType == null) {
2905:                            iconLocation = imageService
2906:                                    .getContentTypeImage("application/binary");
2907:                        } else {
2908:                            iconLocation = imageService
2909:                                    .getContentTypeImage(this .m_contentType);
2910:                        }
2911:                    }
2912:                    this .iconLocation = iconLocation;
2913:                }
2914:
2915:            } // Inner class AttachItem
2916:
2917:            /**
2918:             * Prepare the current page of site collections to display.
2919:             * @return List of ListItem objects to display on this page.
2920:             */
2921:            protected List<ListItem> prepPage(SessionState state) {
2922:                ToolSession toolSession = SessionManager
2923:                        .getCurrentToolSession();
2924:                List<ListItem> rv = new Vector<ListItem>();
2925:
2926:                // access the page size
2927:                int pageSize = ((Integer) toolSession
2928:                        .getAttribute(STATE_PAGESIZE)).intValue();
2929:
2930:                // cleanup prior prep
2931:                state.removeAttribute(STATE_NUM_MESSAGES);
2932:
2933:                // are we going next or prev, first or last page?
2934:                boolean goNextPage = toolSession
2935:                        .getAttribute(STATE_GO_NEXT_PAGE) != null;
2936:                boolean goPrevPage = toolSession
2937:                        .getAttribute(STATE_GO_PREV_PAGE) != null;
2938:                boolean goFirstPage = toolSession
2939:                        .getAttribute(STATE_GO_FIRST_PAGE) != null;
2940:                boolean goLastPage = toolSession
2941:                        .getAttribute(STATE_GO_LAST_PAGE) != null;
2942:                state.removeAttribute(STATE_GO_NEXT_PAGE);
2943:                state.removeAttribute(STATE_GO_PREV_PAGE);
2944:                state.removeAttribute(STATE_GO_FIRST_PAGE);
2945:                state.removeAttribute(STATE_GO_LAST_PAGE);
2946:
2947:                // are we going next or prev message?
2948:                boolean goNext = toolSession.getAttribute(STATE_GO_NEXT) != null;
2949:                boolean goPrev = toolSession.getAttribute(STATE_GO_PREV) != null;
2950:                state.removeAttribute(STATE_GO_NEXT);
2951:                state.removeAttribute(STATE_GO_PREV);
2952:
2953:                // read all channel messages
2954:                List<ListItem> allMessages = readAllResources(state);
2955:
2956:                if (allMessages == null) {
2957:                    return rv;
2958:                }
2959:
2960:                String messageIdAtTheTopOfThePage = null;
2961:                Object topMsgId = toolSession
2962:                        .getAttribute(STATE_TOP_PAGE_MESSAGE_ID);
2963:                if (topMsgId == null) {
2964:                    // do nothing
2965:                } else if (topMsgId instanceof  Integer) {
2966:                    messageIdAtTheTopOfThePage = ((Integer) topMsgId)
2967:                            .toString();
2968:                } else if (topMsgId instanceof  String) {
2969:                    messageIdAtTheTopOfThePage = (String) topMsgId;
2970:                }
2971:
2972:                // if we have no prev page and do have a top message, then we will stay "pinned" to the top
2973:                boolean pinToTop = ((messageIdAtTheTopOfThePage != null)
2974:                        && (toolSession.getAttribute(STATE_PREV_PAGE_EXISTS) == null)
2975:                        && !goNextPage && !goPrevPage && !goNext && !goPrev
2976:                        && !goFirstPage && !goLastPage);
2977:
2978:                // if we have no next page and do have a top message, then we will stay "pinned" to the bottom
2979:                boolean pinToBottom = ((messageIdAtTheTopOfThePage != null)
2980:                        && (toolSession.getAttribute(STATE_NEXT_PAGE_EXISTS) == null)
2981:                        && !goNextPage && !goPrevPage && !goNext && !goPrev
2982:                        && !goFirstPage && !goLastPage);
2983:
2984:                // how many messages, total
2985:                int numMessages = allMessages.size();
2986:
2987:                if (numMessages == 0) {
2988:                    return rv;
2989:                }
2990:
2991:                // save the number of messges
2992:                toolSession.setAttribute(STATE_NUM_MESSAGES, new Integer(
2993:                        numMessages));
2994:
2995:                // find the position of the message that is the top first on the page
2996:                int posStart = 0;
2997:                if (messageIdAtTheTopOfThePage != null) {
2998:                    // find the next page
2999:                    posStart = findResourceInList(allMessages,
3000:                            messageIdAtTheTopOfThePage);
3001:
3002:                    // if missing, start at the top
3003:                    if (posStart == -1) {
3004:                        posStart = 0;
3005:                    }
3006:                }
3007:
3008:                // if going to the next page, adjust
3009:                if (goNextPage) {
3010:                    posStart += pageSize;
3011:                }
3012:
3013:                // if going to the prev page, adjust
3014:                else if (goPrevPage) {
3015:                    posStart -= pageSize;
3016:                    if (posStart < 0)
3017:                        posStart = 0;
3018:                }
3019:
3020:                // if going to the first page, adjust
3021:                else if (goFirstPage) {
3022:                    posStart = 0;
3023:                }
3024:
3025:                // if going to the last page, adjust
3026:                else if (goLastPage) {
3027:                    posStart = numMessages - pageSize;
3028:                    if (posStart < 0)
3029:                        posStart = 0;
3030:                }
3031:
3032:                // pinning
3033:                if (pinToTop) {
3034:                    posStart = 0;
3035:                } else if (pinToBottom) {
3036:                    posStart = numMessages - pageSize;
3037:                    if (posStart < 0)
3038:                        posStart = 0;
3039:                }
3040:
3041:                // get the last page fully displayed
3042:                if (posStart + pageSize > numMessages) {
3043:                    posStart = numMessages - pageSize;
3044:                    if (posStart < 0)
3045:                        posStart = 0;
3046:                }
3047:
3048:                // compute the end to a page size, adjusted for the number of messages available
3049:                int posEnd = posStart + (pageSize - 1);
3050:                if (posEnd >= numMessages)
3051:                    posEnd = numMessages - 1;
3052:                int numMessagesOnThisPage = (posEnd - posStart) + 1;
3053:
3054:                // select the messages on this page
3055:                for (int i = posStart; i <= posEnd; i++) {
3056:                    rv.add(allMessages.get(i));
3057:                }
3058:
3059:                // save which message is at the top of the page
3060:                ListItem itemAtTheTopOfThePage = (ListItem) allMessages
3061:                        .get(posStart);
3062:                toolSession.setAttribute(STATE_TOP_PAGE_MESSAGE_ID,
3063:                        itemAtTheTopOfThePage.getId());
3064:                toolSession.setAttribute(STATE_TOP_MESSAGE_INDEX, new Integer(
3065:                        posStart));
3066:
3067:                // which message starts the next page (if any)
3068:                int next = posStart + pageSize;
3069:                if (next < numMessages) {
3070:                    toolSession.setAttribute(STATE_NEXT_PAGE_EXISTS, "");
3071:                } else {
3072:                    state.removeAttribute(STATE_NEXT_PAGE_EXISTS);
3073:                }
3074:
3075:                // which message ends the prior page (if any)
3076:                int prev = posStart - 1;
3077:                if (prev >= 0) {
3078:                    toolSession.setAttribute(STATE_PREV_PAGE_EXISTS, "");
3079:                } else {
3080:                    state.removeAttribute(STATE_PREV_PAGE_EXISTS);
3081:                }
3082:
3083:                if (toolSession.getAttribute(STATE_VIEW_ID) != null) {
3084:                    int viewPos = findResourceInList(allMessages,
3085:                            (String) toolSession.getAttribute(STATE_VIEW_ID));
3086:
3087:                    // are we moving to the next message
3088:                    if (goNext) {
3089:                        // advance
3090:                        viewPos++;
3091:                        if (viewPos >= numMessages)
3092:                            viewPos = numMessages - 1;
3093:                    }
3094:
3095:                    // are we moving to the prev message
3096:                    if (goPrev) {
3097:                        // retreat
3098:                        viewPos--;
3099:                        if (viewPos < 0)
3100:                            viewPos = 0;
3101:                    }
3102:
3103:                    // update the view message
3104:                    toolSession.setAttribute(STATE_VIEW_ID,
3105:                            ((ListItem) allMessages.get(viewPos)).getId());
3106:
3107:                    // if the view message is no longer on the current page, adjust the page
3108:                    // Note: next time through this will get processed
3109:                    if (viewPos < posStart) {
3110:                        toolSession.setAttribute(STATE_GO_PREV_PAGE, "");
3111:                    } else if (viewPos > posEnd) {
3112:                        toolSession.setAttribute(STATE_GO_NEXT_PAGE, "");
3113:                    }
3114:
3115:                    if (viewPos > 0) {
3116:                        toolSession.setAttribute(STATE_PREV_EXISTS, "");
3117:                    } else {
3118:                        state.removeAttribute(STATE_PREV_EXISTS);
3119:                    }
3120:
3121:                    if (viewPos < numMessages - 1) {
3122:                        toolSession.setAttribute(STATE_NEXT_EXISTS, "");
3123:                    } else {
3124:                        state.removeAttribute(STATE_NEXT_EXISTS);
3125:                    }
3126:                }
3127:
3128:                return rv;
3129:
3130:            } // prepPage
3131:
3132:            /**
3133:             * Develop a list of all the site collections that there are to page.
3134:             * Sort them as appropriate, and apply search criteria.
3135:             */
3136:            protected List<ListItem> readAllResources(SessionState state) {
3137:                ToolSession toolSession = SessionManager
3138:                        .getCurrentToolSession();
3139:                ContentHostingService contentService = (ContentHostingService) toolSession
3140:                        .getAttribute(STATE_CONTENT_SERVICE);
3141:
3142:                ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
3143:                        .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
3144:                if (registry == null) {
3145:                    registry = (ResourceTypeRegistry) ComponentManager
3146:                            .get("org.sakaiproject.content.api.ResourceTypeRegistry");
3147:                    toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY,
3148:                            registry);
3149:                }
3150:
3151:                List<ListItem> other_sites = new Vector<ListItem>();
3152:
3153:                String homeCollectionId = (String) toolSession
3154:                        .getAttribute(STATE_HOME_COLLECTION_ID);
3155:
3156:                // make sure the collectionId is set
3157:                String collectionId = (String) toolSession
3158:                        .getAttribute(STATE_DEFAULT_COLLECTION_ID);
3159:                if (collectionId == null) {
3160:                    collectionId = homeCollectionId;
3161:                }
3162:
3163:                SortedSet<String> expandedCollections = (SortedSet<String>) toolSession
3164:                        .getAttribute(STATE_EXPANDED_COLLECTIONS);
3165:                if (expandedCollections == null) {
3166:                    expandedCollections = new TreeSet();
3167:                    toolSession.setAttribute(STATE_EXPANDED_COLLECTIONS,
3168:                            expandedCollections);
3169:                }
3170:
3171:                Comparator userSelectedSort = (Comparator) toolSession
3172:                        .getAttribute(STATE_LIST_VIEW_SORT);
3173:
3174:                // set the sort values
3175:                String sortedBy = (String) toolSession
3176:                        .getAttribute(STATE_SORT_BY);
3177:                String sortedAsc = (String) toolSession
3178:                        .getAttribute(STATE_SORT_ASC);
3179:
3180:                // add user's personal workspace
3181:                User user = UserDirectoryService.getCurrentUser();
3182:                String userId = user.getId();
3183:                String userName = user.getDisplayName();
3184:                String wsId = SiteService.getUserSiteId(userId);
3185:                String wsCollectionId = contentService.getSiteCollection(wsId);
3186:
3187:                if (!collectionId.equals(wsCollectionId)) {
3188:                    try {
3189:                        ContentCollection wsCollection = contentService
3190:                                .getCollection(wsCollectionId);
3191:                        ListItem wsRoot = ListItem.getListItem(wsCollection,
3192:                                null, registry, false, expandedCollections,
3193:                                null, null, 0, userSelectedSort, false);
3194:                        other_sites.add(wsRoot);
3195:                    } catch (IdUnusedException e) {
3196:                        // TODO Auto-generated catch block
3197:                        logger.warn("IdUnusedException ", e);
3198:                    } catch (TypeException e) {
3199:                        // TODO Auto-generated catch block
3200:                        logger.warn("TypeException ", e);
3201:                    } catch (PermissionException e) {
3202:                        // TODO Auto-generated catch block
3203:                        logger.warn("PermissionException ", e);
3204:                    }
3205:                }
3206:
3207:                /*
3208:                 * add all other sites user has access to
3209:                 * NOTE: This does not (and should not) get all sites for admin.  
3210:                 *       Getting all sites for admin is too big a request and
3211:                 *       would result in too big a display to render in html.
3212:                 */
3213:                Map othersites = contentService.getCollectionMap();
3214:                Iterator siteIt = othersites.keySet().iterator();
3215:                SortedSet sort = new TreeSet();
3216:                while (siteIt.hasNext()) {
3217:                    String collId = (String) siteIt.next();
3218:                    String displayName = (String) othersites.get(collId);
3219:                    sort.add(displayName + ResourcesAction.DELIM + collId);
3220:                }
3221:
3222:                Iterator sortIt = sort.iterator();
3223:                while (sortIt.hasNext()) {
3224:                    String keyvalue = (String) sortIt.next();
3225:                    String displayName = keyvalue.substring(0, keyvalue
3226:                            .lastIndexOf(ResourcesAction.DELIM));
3227:                    String collId = keyvalue.substring(keyvalue
3228:                            .lastIndexOf(ResourcesAction.DELIM) + 1);
3229:                    if (!collectionId.equals(collId)
3230:                            && !wsCollectionId.equals(collId)) {
3231:                        ContentCollection collection;
3232:                        try {
3233:                            collection = contentService.getCollection(collId);
3234:                            ListItem root = ListItem.getListItem(collection,
3235:                                    null, registry, false, expandedCollections,
3236:                                    null, null, 0, null, false);
3237:                            root.setName(displayName);
3238:                            other_sites.add(root);
3239:                        } catch (IdUnusedException e) {
3240:                            // TODO Auto-generated catch block
3241:                            logger
3242:                                    .warn("IdUnusedException (FilePickerAction.readAllResources()) collId == "
3243:                                            + collId + " --> " + e);
3244:                        } catch (TypeException e) {
3245:                            // TODO Auto-generated catch block
3246:                            logger
3247:                                    .warn("TypeException (FilePickerAction.readAllResources()) collId == "
3248:                                            + collId + " --> " + e);
3249:                        } catch (PermissionException e) {
3250:                            // TODO Auto-generated catch block
3251:                            logger
3252:                                    .warn("PermissionException (FilePickerAction.readAllResources()) collId == "
3253:                                            + collId + " --> " + e);
3254:                        }
3255:                    }
3256:                }
3257:
3258:                return other_sites;
3259:            }
3260:
3261:            /**
3262:             * Find the resource with this id in the list.
3263:             * @param messages The list of messages.
3264:             * @param id The message id.
3265:             * @return The index position in the list of the message with this id, or -1 if not found.
3266:             */
3267:            protected int findResourceInList(List resources, String id) {
3268:                for (int i = 0; i < resources.size(); i++) {
3269:                    // if this is the one, return this index
3270:                    if (((ListItem) (resources.get(i))).getId().equals(id))
3271:                        return i;
3272:                }
3273:
3274:                // not found
3275:                return -1;
3276:
3277:            } // findResourceInList
3278:
3279:            protected static boolean checkItemFilter(ContentResource resource,
3280:                    ListItem newItem, ContentResourceFilter filter) {
3281:                if (filter != null) {
3282:                    if (newItem != null) {
3283:                        newItem.setCanSelect(filter.allowSelect(resource));
3284:                    }
3285:                    return filter.allowView(resource);
3286:                } else if (newItem != null) {
3287:                    newItem.setCanSelect(true);
3288:                }
3289:
3290:                return true;
3291:            }
3292:
3293:            protected static boolean checkSelctItemFilter(
3294:                    ContentResource resource, ContentResourceFilter filter) {
3295:                if (filter != null) {
3296:                    return filter.allowSelect(resource);
3297:                }
3298:                return true;
3299:            }
3300:
3301:        } // class FilePickerAction 
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.