Source Code Cross Referenced for WizardManagerImpl.java in  » ERP-CRM-Financial » sakai » org » theospi » portfolio » wizard » mgt » impl » 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.theospi.portfolio.wizard.mgt.impl 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /**********************************************************************************
0002:         * $URL: https://source.sakaiproject.org/svn/osp/tags/sakai_2-4-1/wizard/api-impl/src/java/org/theospi/portfolio/wizard/mgt/impl/WizardManagerImpl.java $
0003:         * $Id: WizardManagerImpl.java 22533 2007-03-13 14:48:50Z bkirschn@umich.edu $
0004:         ***********************************************************************************
0005:         *
0006:         * Copyright (c) 2005, 2006, 2007 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.theospi.portfolio.wizard.mgt.impl;
0021:
0022:        import java.io.*;
0023:        import java.util.*;
0024:        import java.util.zip.Adler32;
0025:        import java.util.zip.CheckedOutputStream;
0026:        import java.util.zip.ZipEntry;
0027:        import java.util.zip.ZipInputStream;
0028:        import java.util.zip.ZipOutputStream;
0029:        import java.sql.SQLException;
0030:
0031:        import net.sf.ehcache.Cache;
0032:        import net.sf.ehcache.CacheManager;
0033:        import net.sf.ehcache.CacheException;
0034:
0035:        import org.hibernate.Criteria;
0036:        import org.hibernate.FetchMode;
0037:        import org.hibernate.HibernateException;
0038:        import org.hibernate.Session;
0039:        import org.hibernate.Query;
0040:        import org.hibernate.Hibernate;
0041:        import org.hibernate.criterion.Expression;
0042:        import org.hibernate.criterion.Restrictions;
0043:        import org.jdom.CDATA;
0044:        import org.jdom.DataConversionException;
0045:        import org.jdom.Document;
0046:        import org.jdom.Element;
0047:        import org.jdom.input.SAXBuilder;
0048:        import org.jdom.output.XMLOutputter;
0049:        import org.sakaiproject.authz.api.SecurityService;
0050:        import org.sakaiproject.content.api.LockManager;
0051:        import org.sakaiproject.content.api.ContentCollection;
0052:        import org.sakaiproject.content.api.ContentCollectionEdit;
0053:        import org.sakaiproject.content.api.ContentHostingService;
0054:        import org.sakaiproject.content.api.ContentResource;
0055:        import org.sakaiproject.content.api.ContentResourceEdit;
0056:        import org.sakaiproject.entity.api.EntityManager;
0057:        import org.sakaiproject.entity.api.Reference;
0058:        import org.sakaiproject.entity.api.ResourceProperties;
0059:        import org.sakaiproject.entity.api.ResourcePropertiesEdit;
0060:        import org.sakaiproject.exception.IdInvalidException;
0061:        import org.sakaiproject.exception.IdUnusedException;
0062:        import org.sakaiproject.exception.IdUsedException;
0063:        import org.sakaiproject.exception.ImportException;
0064:        import org.sakaiproject.exception.InconsistentException;
0065:        import org.sakaiproject.exception.PermissionException;
0066:        import org.sakaiproject.exception.ServerOverloadException;
0067:        import org.sakaiproject.exception.TypeException;
0068:        import org.sakaiproject.exception.UnsupportedFileTypeException;
0069:        import org.sakaiproject.metaobj.security.AuthenticationManager;
0070:        import org.sakaiproject.metaobj.shared.ArtifactFinder;
0071:        import org.sakaiproject.metaobj.shared.DownloadableManager;
0072:        import org.sakaiproject.metaobj.shared.mgt.AgentManager;
0073:        import org.sakaiproject.metaobj.shared.mgt.ContentEntityUtil;
0074:        import org.sakaiproject.metaobj.shared.mgt.IdManager;
0075:        import org.sakaiproject.metaobj.shared.mgt.PresentableObjectHome;
0076:        import org.sakaiproject.metaobj.shared.mgt.ReadableObjectHome;
0077:        import org.sakaiproject.metaobj.shared.mgt.StructuredArtifactDefinitionManager;
0078:        import org.sakaiproject.metaobj.shared.model.Agent;
0079:        import org.sakaiproject.metaobj.shared.model.Artifact;
0080:        import org.sakaiproject.metaobj.shared.model.FinderException;
0081:        import org.sakaiproject.metaobj.shared.model.Id;
0082:        import org.sakaiproject.metaobj.shared.model.MimeType;
0083:        import org.sakaiproject.metaobj.shared.model.StructuredArtifactDefinitionBean;
0084:        import org.sakaiproject.metaobj.shared.model.Type;
0085:        import org.sakaiproject.service.legacy.resource.DuplicatableToolService;
0086:        import org.sakaiproject.site.api.Site;
0087:        import org.sakaiproject.site.api.SitePage;
0088:        import org.sakaiproject.site.api.ToolConfiguration;
0089:        import org.sakaiproject.site.cover.SiteService;
0090:        import org.sakaiproject.tool.api.Placement;
0091:        import org.sakaiproject.tool.cover.ToolManager;
0092:        import org.sakaiproject.user.api.User;
0093:        import org.sakaiproject.user.cover.UserDirectoryService;
0094:        import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
0095:        import org.springframework.orm.hibernate3.HibernateCallback;
0096:        import org.theospi.portfolio.guidance.mgt.GuidanceManager;
0097:        import org.theospi.portfolio.guidance.model.Guidance;
0098:        import org.theospi.portfolio.matrix.MatrixFunctionConstants;
0099:        import org.theospi.portfolio.matrix.MatrixManager;
0100:        import org.theospi.portfolio.matrix.model.WizardPage;
0101:        import org.theospi.portfolio.matrix.model.WizardPageDefinition;
0102:        import org.theospi.portfolio.matrix.model.Attachment;
0103:        import org.theospi.portfolio.matrix.model.WizardPageForm;
0104:        import org.theospi.portfolio.review.mgt.ReviewManager;
0105:        import org.theospi.portfolio.review.model.Review;
0106:        import org.theospi.portfolio.security.AllowMapSecurityAdvisor;
0107:        import org.theospi.portfolio.security.Authorization;
0108:        import org.theospi.portfolio.security.AuthorizationFacade;
0109:        import org.theospi.portfolio.security.impl.AllowAllSecurityAdvisor;
0110:        import org.theospi.portfolio.shared.model.Node;
0111:        import org.theospi.portfolio.shared.model.ObjectWithWorkflow;
0112:        import org.theospi.portfolio.shared.model.OspException;
0113:        import org.theospi.portfolio.style.StyleConsumer;
0114:        import org.theospi.portfolio.style.mgt.StyleManager;
0115:        import org.theospi.portfolio.style.model.Style;
0116:        import org.theospi.portfolio.wizard.WizardFunctionConstants;
0117:        import org.theospi.portfolio.wizard.impl.WizardEntityProducer;
0118:        import org.theospi.portfolio.wizard.mgt.WizardManager;
0119:        import org.theospi.portfolio.wizard.model.CompletedWizard;
0120:        import org.theospi.portfolio.wizard.model.CompletedWizardCategory;
0121:        import org.theospi.portfolio.wizard.model.CompletedWizardPage;
0122:        import org.theospi.portfolio.wizard.model.Wizard;
0123:        import org.theospi.portfolio.wizard.model.WizardCategory;
0124:        import org.theospi.portfolio.wizard.model.WizardPageSequence;
0125:        import org.theospi.portfolio.workflow.mgt.WorkflowManager;
0126:        import org.theospi.portfolio.workflow.model.Workflow;
0127:        import org.theospi.portfolio.workflow.model.WorkflowItem;
0128:
0129:        public class WizardManagerImpl extends HibernateDaoSupport implements 
0130:                WizardManager, DownloadableManager, ReadableObjectHome,
0131:                ArtifactFinder, PresentableObjectHome, StyleConsumer,
0132:                DuplicatableToolService {
0133:
0134:            static final private String DOWNLOAD_WIZARD_ID_PARAM = "wizardId";
0135:            static final private String IMPORT_BASE_FOLDER_ID = "importedWizards";
0136:
0137:            /**
0138:             * property name for site identifier
0139:             */
0140:            private static final String SITE_ID = "siteId";
0141:
0142:            private AuthorizationFacade authorizationFacade;
0143:            private SecurityService securityService;
0144:            private EntityManager entityManager;
0145:            private IdManager idManager;
0146:            private StructuredArtifactDefinitionManager structuredArtifactDefinitionManager;
0147:            private AgentManager agentManager;
0148:            private AuthenticationManager authManager;
0149:            private GuidanceManager guidanceManager;
0150:            private WorkflowManager workflowManager;
0151:            private ContentHostingService contentHosting;
0152:            private PresentableObjectHome xmlRenderer;
0153:            private ReviewManager reviewManager;
0154:            private StyleManager styleManager;
0155:            private MatrixManager matrixManager;
0156:            private LockManager lockManager;
0157:
0158:            private static String SITE_CACHE_NAME = "wizardSiteCache";
0159:            private Cache siteCache = null;
0160:            private String importFolderName;
0161:
0162:            protected void init() throws Exception {
0163:
0164:                logger.info("init()");
0165:                CacheManager cacheManager = CacheManager.create();
0166:                if (cacheManager.cacheExists(SITE_CACHE_NAME))
0167:                    cacheManager.removeCache(SITE_CACHE_NAME);
0168:                Cache memoryOnlyCache = new Cache(SITE_CACHE_NAME, 500, false,
0169:                        false, 60, 10);
0170:                cacheManager.addCache(memoryOnlyCache);
0171:                siteCache = cacheManager.getCache(SITE_CACHE_NAME);
0172:
0173:            }
0174:
0175:            /**
0176:             * {@inheritDoc}
0177:             */
0178:            public Wizard createNew() {
0179:                Placement placement = ToolManager.getCurrentPlacement();
0180:                String currentSite = placement.getContext();
0181:                Agent agent = getAuthManager().getAgent();
0182:                Wizard wizard = new Wizard(getIdManager().createId(), agent,
0183:                        currentSite);
0184:                return wizard;
0185:            }
0186:
0187:            protected void removeFromSession(Object obj) {
0188:                this .getHibernateTemplate().evict(obj);
0189:                try {
0190:                    getHibernateTemplate().getSessionFactory().evict(
0191:                            obj.getClass());
0192:                } catch (HibernateException e) {
0193:                    logger.error(e);
0194:                }
0195:            }
0196:
0197:            protected void clearSession() {
0198:                this .getHibernateTemplate().clear();
0199:            }
0200:
0201:            /**
0202:             * {@inheritDoc}
0203:             */
0204:            public Wizard getWizard(Id wizardId) {
0205:                return getWizard(wizardId, WIZARD_OPERATE_CHECK);
0206:            }
0207:
0208:            /**
0209:             * {@inheritDoc}
0210:             */
0211:            public Wizard getWizard(Id wizardId, int checkAuthz) {
0212:                Wizard wizard = (Wizard) getHibernateTemplate().get(
0213:                        Wizard.class, wizardId);
0214:
0215:                if (wizard == null) {
0216:                    return null;
0217:                }
0218:
0219:                if (checkAuthz == WIZARD_OPERATE_CHECK)
0220:                    getAuthorizationFacade().checkPermission(
0221:                            WizardFunctionConstants.OPERATE_WIZARD, wizardId);
0222:                if (checkAuthz == WIZARD_VIEW_CHECK)
0223:                    getAuthorizationFacade().checkPermission(
0224:                            WizardFunctionConstants.VIEW_WIZARD,
0225:                            getIdManager().getId(wizard.getSiteId()));
0226:                if (checkAuthz == WIZARD_EDIT_CHECK)
0227:                    getAuthorizationFacade().checkPermission(
0228:                            WizardFunctionConstants.EDIT_WIZARD, wizardId);
0229:                if (checkAuthz == WIZARD_EXPORT_CHECK)
0230:                    getAuthorizationFacade().checkPermission(
0231:                            WizardFunctionConstants.EXPORT_WIZARD,
0232:                            idManager.getId(ToolManager.getCurrentPlacement()
0233:                                    .getContext()));
0234:                if (checkAuthz == WIZARD_DELETE_CHECK)
0235:                    getAuthorizationFacade().checkPermission(
0236:                            WizardFunctionConstants.DELETE_WIZARD, wizardId);
0237:
0238:                // setup access to the files
0239:                List refs = new ArrayList();
0240:
0241:                if (wizard.getStyle() != null) {
0242:                    Node node = getNode(wizard.getStyle().getStyleFile());
0243:                    refs.add(node.getResource().getReference());
0244:                }
0245:
0246:                WizardCategory rootCategory = (WizardCategory) wizard
0247:                        .getRootCategory();
0248:                loadCategory(rootCategory, refs);
0249:
0250:                getSecurityService()
0251:                        .pushAdvisor(
0252:                                new AllowMapSecurityAdvisor(
0253:                                        ContentHostingService.EVENT_RESOURCE_READ,
0254:                                        refs));
0255:
0256:                //removeFromSession(wizard);
0257:                return wizard;
0258:            }
0259:
0260:            /**
0261:             * {@inheritDoc}
0262:             */
0263:            public Wizard getWizard(String id, int checkAuthz) {
0264:                return getWizard(getIdManager().getId(id), checkAuthz);
0265:            }
0266:
0267:            public Wizard getWizard(String id) {
0268:                return getWizard(id, WIZARD_OPERATE_CHECK);
0269:            }
0270:
0271:            public Node getNode(Id artifactId) {
0272:                String id = getContentHosting().resolveUuid(
0273:                        artifactId.getValue());
0274:                if (id == null) {
0275:                    return null;
0276:                }
0277:
0278:                //This needs to be here so that the getResource(id) down in the try{} doesn't bark
0279:                getSecurityService().pushAdvisor(
0280:                        new AllowMapSecurityAdvisor(
0281:                                ContentHostingService.EVENT_RESOURCE_READ,
0282:                                getContentHosting().getReference(id)));
0283:
0284:                try {
0285:                    ContentResource resource = getContentHosting().getResource(
0286:                            id);
0287:                    String ownerId = resource.getProperties().getProperty(
0288:                            resource.getProperties().getNamePropCreator());
0289:                    Agent owner = getAgentManager().getAgent(
0290:                            getIdManager().getId(ownerId));
0291:                    return new Node(artifactId, resource, owner);
0292:                } catch (PermissionException e) {
0293:                    logger.error("", e);
0294:                    throw new RuntimeException(e);
0295:                } catch (IdUnusedException e) {
0296:                    logger.error("", e);
0297:                    throw new RuntimeException(e);
0298:                } catch (TypeException e) {
0299:                    logger.error("", e);
0300:                    throw new RuntimeException(e);
0301:                }
0302:            }
0303:
0304:            protected void loadCategory(WizardCategory category, List refs) {
0305:
0306:                for (Iterator i = category.getChildPages().iterator(); i
0307:                        .hasNext();) {
0308:                    WizardPageSequence page = (WizardPageSequence) i.next();
0309:                    WizardPageDefinition pageDef = page
0310:                            .getWizardPageDefinition(); // make sure this loads
0311:                    pageDef.getTitle();
0312:                }
0313:
0314:                if (category.getChildCategories() != null) {
0315:                    for (Iterator i = category.getChildCategories().iterator(); i
0316:                            .hasNext();) {
0317:                        loadCategory((WizardCategory) i.next(), refs);
0318:                    }
0319:                }
0320:            }
0321:
0322:            /**
0323:             * {@inheritDoc}
0324:             */
0325:            public Wizard saveWizard(Wizard wizard) {
0326:                Date now = new Date(System.currentTimeMillis());
0327:                wizard.setModified(now);
0328:
0329:                if (wizard.getExposeAsTool() != null
0330:                        && wizard.getExposeAsTool().booleanValue()
0331:                        && wizard.getExposedPageId() == null) {
0332:                    addTool(wizard);
0333:                } else if (wizard.getExposeAsTool() != null
0334:                        && !wizard.getExposeAsTool().booleanValue()
0335:                        && wizard.getExposedPageId() != null) {
0336:                    removeTool(wizard);
0337:                }
0338:
0339:                if (wizard.isNewObject()) {
0340:                    // for some reason the save throws a null pointer exception
0341:                    //    if the id isn't set, so generate a new one if need be
0342:                    if (wizard.getId() == null && wizard.getNewId() == null)
0343:                        wizard.setNewId(getIdManager().createId());
0344:                    wizard.setCreated(now);
0345:                    wizard.getRootCategory().setCreated(now);
0346:                    wizard.getRootCategory().setModified(now);
0347:                    wizard.getRootCategory().setWizard(null);
0348:                    getHibernateTemplate().save(wizard);
0349:                    wizard.getRootCategory().setWizard(wizard);
0350:                    wizard.setNewObject(false);
0351:                } else {
0352:                    getHibernateTemplate().saveOrUpdate(wizard);
0353:                }
0354:
0355:                return wizard;
0356:            }
0357:
0358:            private void removeTool(Wizard wizard) {
0359:                String siteId = wizard.getSiteId();
0360:                try {
0361:                    Site siteEdit = SiteService.getSite(siteId);
0362:
0363:                    SitePage page = siteEdit.getPage(wizard.getExposedPageId());
0364:                    siteEdit.removePage(page);
0365:                    SiteService.save(siteEdit);
0366:                    wizard.setExposedPageId(null);
0367:                } catch (IdUnusedException e) {
0368:                    logger.error("", e);
0369:                } catch (PermissionException e) {
0370:                    logger.error("", e);
0371:                }
0372:            }
0373:
0374:            private void addTool(Wizard wizard) {
0375:                String siteId = wizard.getSiteId();
0376:                try {
0377:                    Site siteEdit = SiteService.getSite(siteId);
0378:
0379:                    SitePage page = siteEdit.addPage();
0380:
0381:                    page.setTitle(wizard.getName());
0382:                    page.setLayout(SitePage.LAYOUT_SINGLE_COL);
0383:
0384:                    ToolConfiguration tool = page.addTool();
0385:                    tool.setTool("osp.exposedwizard", ToolManager
0386:                            .getTool("osp.exposedwizard"));
0387:                    tool.setTitle(wizard.getName());
0388:                    tool.setLayoutHints("0,0");
0389:                    tool.getPlacementConfig().setProperty(
0390:                            WizardManager.EXPOSED_WIZARD_KEY,
0391:                            wizard.getId().getValue());
0392:
0393:                    //LOG.info(this+": SiteService.commitEdit():" +siteId);
0394:
0395:                    SiteService.save(siteEdit);
0396:                    wizard.setExposedPageId(page.getId());
0397:
0398:                } catch (IdUnusedException e) {
0399:                    logger.error("", e);
0400:                } catch (PermissionException e) {
0401:                    logger.error("", e);
0402:                }
0403:            }
0404:
0405:            /** 
0406:             * unlock all resources associated with wizard pages (in preparation for delete)
0407:             */
0408:            protected void unlockWizardResources(Wizard wizard) {
0409:                List wpsList = findPagesByWizard(wizard.getId());
0410:                for (Iterator wpsIt = wpsList.iterator(); wpsIt.hasNext();) {
0411:                    WizardPageSequence wps = (WizardPageSequence) wpsIt.next();
0412:
0413:                    Id defId = wps.getWizardPageDefinition().getId();
0414:                    List pageList = matrixManager.getPagesByPageDef(defId);
0415:
0416:                    for (Iterator pageIt = pageList.iterator(); pageIt
0417:                            .hasNext();) {
0418:                        WizardPage page = (WizardPage) pageIt.next();
0419:
0420:                        for (Iterator iter = page.getAttachments().iterator(); iter
0421:                                .hasNext();) {
0422:                            Attachment att = (Attachment) iter.next();
0423:                            getLockManager().removeLock(
0424:                                    att.getArtifactId().getValue(),
0425:                                    page.getId().getValue());
0426:                        }
0427:
0428:                        for (Iterator iter = page.getPageForms().iterator(); iter
0429:                                .hasNext();) {
0430:                            WizardPageForm pageForm = (WizardPageForm) iter
0431:                                    .next();
0432:                            getLockManager().removeLock(
0433:                                    pageForm.getArtifactId().getValue(),
0434:                                    page.getId().getValue());
0435:                        }
0436:
0437:                        List reviews = getReviewManager().getReviewsByParent(
0438:                                page.getId().getValue(),
0439:                                page.getPageDefinition().getSiteId(),
0440:                                WizardEntityProducer.WIZARD_PRODUCER);
0441:                        for (Iterator iter = reviews.iterator(); iter.hasNext();) {
0442:                            Review review = (Review) iter.next();
0443:                            getLockManager().removeLock(
0444:                                    review.getReviewContent().getValue(),
0445:                                    page.getId().getValue());
0446:                        }
0447:                    }
0448:                }
0449:            }
0450:
0451:            /**
0452:             * Unlock resources and delete completed wizards from a preview wizard
0453:             */
0454:            public void deletePreviewWizardData(Wizard wizard) {
0455:
0456:                // Unlock resources associated with wizard pages
0457:                unlockWizardResources(wizard);
0458:
0459:                // Delete completed wizards
0460:                List completedWizards = getCompletedWizards(wizard);
0461:                for (Iterator i = completedWizards.iterator(); i.hasNext();) {
0462:                    CompletedWizard cw = (CompletedWizard) i.next();
0463:                    deleteCompletedWizard(cw);
0464:                }
0465:            }
0466:
0467:            /**
0468:             * {@inheritDoc}
0469:             */
0470:            public void deleteWizard(Wizard wizard) {
0471:
0472:                // Unlock resources associated with wizard pages
0473:                unlockWizardResources(wizard);
0474:
0475:                // Delete completed wizards
0476:                Wizard wiz = this 
0477:                        .getWizard(wizard.getId(), WIZARD_DELETE_CHECK);
0478:                List completedWizards = getCompletedWizards(wiz);
0479:                for (Iterator i = completedWizards.iterator(); i.hasNext();) {
0480:                    CompletedWizard cw = (CompletedWizard) i.next();
0481:                    deleteCompletedWizard(cw);
0482:                }
0483:
0484:                //remove the tool from the menu
0485:                if (wiz.getExposedPageId() != null)
0486:                    removeTool(wiz);
0487:
0488:                getHibernateTemplate().delete(wiz);
0489:            }
0490:
0491:            protected void deleteCompletedWizard(CompletedWizard cw) {
0492:                // Unlock resources associated with this completed wizard
0493:                List reviews = getReviewManager().getReviewsByParent(
0494:                        cw.getId().getValue());
0495:                for (Iterator iter = reviews.iterator(); iter.hasNext();) {
0496:                    Review review = (Review) iter.next();
0497:                    getLockManager().removeLock(
0498:                            review.getReviewContent().getValue(),
0499:                            cw.getId().getValue());
0500:                }
0501:
0502:                getHibernateTemplate().delete(cw);
0503:            }
0504:
0505:            public void publishWizard(Wizard wizard) {
0506:                wizard.setPublished(true);
0507:                wizard.setPreview(false);
0508:                wizard.setModified(new Date(System.currentTimeMillis()));
0509:                this .saveWizard(wizard);
0510:            }
0511:
0512:            public void previewWizard(Wizard wizard) {
0513:                wizard.setPreview(true);
0514:                wizard.setModified(new Date(System.currentTimeMillis()));
0515:                this .saveWizard(wizard);
0516:            }
0517:
0518:            public String getWizardEntityProducer() {
0519:                return WizardEntityProducer.WIZARD_PRODUCER;
0520:            }
0521:
0522:            public Reference decorateReference(Wizard wizard, String reference) {
0523:                String fullRef = ContentEntityUtil.getInstance().buildRef(
0524:                        WizardEntityProducer.WIZARD_PRODUCER,
0525:                        wizard.getSiteId(), wizard.getId().getValue(),
0526:                        reference);
0527:
0528:                return getEntityManager().newReference(fullRef);
0529:            }
0530:
0531:            public List listWizardsByType(String owner, String siteId,
0532:                    String type) {
0533:                Object[] params = new Object[] {
0534:                        getAgentManager().getAgent(owner), new Boolean(true),
0535:                        siteId, type };
0536:                return getHibernateTemplate()
0537:                        .find(
0538:                                "from Wizard w where "
0539:                                        + "(w.owner=? or w.published=?) and w.siteId=? and w.type=? order by seq_num",
0540:                                params);
0541:            }
0542:
0543:            /**
0544:             * Pulls all wizards, deeping loading all parts of each Wizard
0545:             * @return List of Wizard
0546:             */
0547:            public List getWizardsForWarehousing() {
0548:                List wizards = getHibernateTemplate().find("from Wizard w");
0549:
0550:                return wizards;
0551:            }
0552:
0553:            /**
0554:             * @param String the wizard id for the completed wizard classes
0555:             * @return List of CompletedWizard
0556:             */
0557:            public List getCompletedWizardsByWizardId(String wizardId) {
0558:                return getCompletedWizards(getIdManager().getId(wizardId));
0559:            }
0560:
0561:            public List listAllWizardsByOwner(String owner, String siteId) {
0562:                Agent ownerAgent = getAgentManager().getAgent(owner);
0563:                Object[] params = new Object[] { ownerAgent, new Boolean(true),
0564:                        siteId };
0565:                return getHibernateTemplate()
0566:                        .find(
0567:                                "from Wizard w where "
0568:                                        + "(w.owner=? or w.published=?) and w.siteId=? order by seq_num",
0569:                                params);
0570:            }
0571:
0572:            public List findWizardsByOwner(String ownerId, String siteId) {
0573:                Object[] params = new Object[] {
0574:                        getAgentManager().getAgent(ownerId), siteId };
0575:                return getHibernateTemplate()
0576:                        .find(
0577:                                "from Wizard w where w.owner=? and w.siteId=? order by seq_num",
0578:                                params);
0579:            }
0580:
0581:            public List findPublishedWizards(List sites) {
0582:                String[] paramNames = new String[] { "published", "siteIds" };
0583:                Object[] params = new Object[] { new Boolean(true), sites };
0584:                return getHibernateTemplate()
0585:                        .findByNamedParam(
0586:                                "from Wizard w where w.published=:published "
0587:                                        + "and w.siteId in ( :siteIds ) order by seq_num",
0588:                                paramNames, params);
0589:            }
0590:
0591:            /**
0592:             * {@inheritDoc}
0593:             */
0594:            public List findPublishedWizards(List sites, boolean lazy) {
0595:                if (lazy)
0596:                    return findPublishedWizardsLazy(sites);
0597:                else
0598:                    return findPublishedWizards(sites);
0599:            }
0600:
0601:            protected List findPublishedWizardsLazy(List sites) {
0602:                Criteria c = this .getSession().createCriteria(Wizard.class);
0603:                Criteria rootCat = c.createCriteria("rootCategory");
0604:                rootCat.setFetchMode("childPages", FetchMode.SELECT);
0605:                rootCat.setFetchMode("childCategories", FetchMode.SELECT);
0606:                c.add(Expression.eq("published", new Boolean(true)));
0607:                c.add(Expression.in("siteId", sites));
0608:
0609:                return new ArrayList(c.list());
0610:            }
0611:
0612:            public List findPublishedWizards(String siteId) {
0613:                Object[] params = new Object[] { new Boolean(true), siteId };
0614:                return getHibernateTemplate()
0615:                        .find(
0616:                                "from Wizard w where w.published=? and w.siteId=? order by seq_num",
0617:                                params);
0618:            }
0619:
0620:            public List<WizardPageDefinition> findWizardPageDefs(
0621:                    final String siteId) {
0622:                return findWizardPageDefs(siteId, false);
0623:            }
0624:
0625:            public List<WizardPageDefinition> findWizardPageDefs(
0626:                    final String siteId, final boolean deep) {
0627:                return (List) getHibernateTemplate().execute(
0628:                        new HibernateCallback() {
0629:                            public Object doInHibernate(Session session) {
0630:                                List<WizardPageDefinition> defs = (List) session
0631:                                        .createCriteria(
0632:                                                WizardPageDefinition.class)
0633:                                        .add(Restrictions.eq(SITE_ID, siteId))
0634:                                        .list();
0635:                                if (deep) {
0636:                                    for (WizardPageDefinition def : defs) {
0637:                                        Hibernate.initialize(def.getPages());
0638:                                    }
0639:                                }
0640:                                return defs;
0641:                            }
0642:                        });
0643:            }
0644:
0645:            public List<WizardPageSequence> findPagesByWizard(final Id wizardId) {
0646:                HibernateCallback hcb = new HibernateCallback() {
0647:                    public Object doInHibernate(Session session)
0648:                            throws HibernateException, SQLException {
0649:                        String queryString = "select page from WizardPageSequence page, WizardCategory category "
0650:                                + "where page.category = category.id and category.wizard = ?";
0651:
0652:                        Query query = session.createQuery(queryString);
0653:
0654:                        query.setParameter(0, wizardId.getValue(),
0655:                                Hibernate.STRING);
0656:
0657:                        return query.list();
0658:                    }
0659:                };
0660:
0661:                return (List) getHibernateTemplate().execute(hcb);
0662:            }
0663:
0664:            public Collection getAvailableForms(String siteId, String type) {
0665:                return getStructuredArtifactDefinitionManager().findHomes(
0666:                        getIdManager().getId(siteId), true);
0667:            }
0668:
0669:            public void deleteObjects(List deletedItems) {
0670:
0671:                for (Iterator i = deletedItems.iterator(); i.hasNext();) {
0672:                    try {
0673:                        getSession().delete(i.next());
0674:                    } catch (HibernateException e) {
0675:                        throw new OspException(e);
0676:                    }
0677:                }
0678:
0679:            }
0680:
0681:            protected List getCompletedWizards(Wizard wizard) {
0682:                return getCompletedWizards(wizard.getId());
0683:            }
0684:
0685:            private List getCompletedWizards(Id id) {
0686:                List completedWizards = getHibernateTemplate().find(
0687:                        " from CompletedWizard cw where cw.wizard.id=?",
0688:                        new Object[] { id });
0689:                return completedWizards;
0690:            }
0691:
0692:            protected List getCompletedWizards(String owner) {
0693:                List completedWizards = getHibernateTemplate().find(
0694:                        " from CompletedWizard cw where cw.owner=?",
0695:                        new Object[] { getAgentManager().getAgent(owner) });
0696:                return completedWizards;
0697:            }
0698:
0699:            public CompletedWizard getCompletedWizard(Id completedWizardId) {
0700:                CompletedWizard wizard = (CompletedWizard) getHibernateTemplate()
0701:                        .get(CompletedWizard.class, completedWizardId);
0702:                return wizard;
0703:            }
0704:
0705:            public CompletedWizard getCompletedWizard(Wizard wizard) {
0706:                Agent agent = getAuthManager().getAgent();
0707:
0708:                return getUsersWizard(wizard, agent);
0709:            }
0710:
0711:            public CompletedWizard getCompletedWizard(Wizard wizard,
0712:                    String userId) {
0713:                return getCompletedWizard(wizard, userId, true);
0714:            }
0715:
0716:            public CompletedWizard getCompletedWizard(Wizard wizard,
0717:                    String userId, boolean create) {
0718:                Agent agent = getAgentManager().getAgent(userId);
0719:
0720:                return getUsersWizard(wizard, agent, create);
0721:            }
0722:
0723:            public CompletedWizard getCompletedWizardByPage(Id pageId) {
0724:                CompletedWizard cw = null;
0725:                Object[] params = new Object[] { pageId };
0726:                List list = getHibernateTemplate().find(
0727:                        "select w.category.wizard from CompletedWizardPage w "
0728:                                + "where w.wizardPage.id=?", params);
0729:
0730:                if (list.size() == 1) {
0731:                    cw = (CompletedWizard) list.get(0);
0732:                }
0733:
0734:                return cw;
0735:            }
0736:
0737:            /**
0738:             * {@inheritDoc}
0739:             */
0740:            public CompletedWizard saveWizard(CompletedWizard wizard) {
0741:                getHibernateTemplate().saveOrUpdate(wizard);
0742:                return wizard;
0743:            }
0744:
0745:            public CompletedWizard getUsersWizard(Wizard wizard, Agent agent) {
0746:                return getUsersWizard(wizard, agent, true);
0747:            }
0748:
0749:            public CompletedWizard getUsersWizard(Wizard wizard, Agent agent,
0750:                    boolean create) {
0751:                List completedWizards = getHibernateTemplate()
0752:                        .find(
0753:                                " from CompletedWizard cw where cw.wizard.id=? and cw.owner=?",
0754:                                new Object[] { wizard.getId(), agent });
0755:
0756:                CompletedWizard returned;
0757:                if (completedWizards.size() != 0) {
0758:                    returned = (CompletedWizard) completedWizards.get(0);
0759:                } else if (create) {
0760:                    returned = new CompletedWizard(wizard, agent);
0761:                } else {
0762:                    return null;
0763:                }
0764:
0765:                if (create) {
0766:                    returned.setLastVisited(new Date());
0767:                    getHibernateTemplate().save(returned);
0768:                }
0769:
0770:                return returned;
0771:            }
0772:
0773:            public void processWorkflow(int workflowOption, Id id) {
0774:                //TODO Unimplemented
0775:            }
0776:
0777:            public void processWorkflow(Id workflowId, Id completedWizardId) {
0778:                Workflow workflow = getWorkflowManager()
0779:                        .getWorkflow(workflowId);
0780:                CompletedWizard compWizard = this 
0781:                        .getCompletedWizard(completedWizardId);
0782:
0783:                Collection items = workflow.getItems();
0784:                for (Iterator i = items.iterator(); i.hasNext();) {
0785:                    WorkflowItem wi = (WorkflowItem) i.next();
0786:                    //Cell actionCell = this.getMatrixCellByScaffoldingCell(cell.getMatrix(),
0787:                    //      wi.getActionObjectId());
0788:                    switch (wi.getActionType()) {
0789:                    case (WorkflowItem.STATUS_CHANGE_WORKFLOW):
0790:                        processStatusChangeWorkflow(wi, compWizard);
0791:                        break;
0792:                    case (WorkflowItem.NOTIFICATION_WORKFLOW):
0793:                        processNotificationWorkflow(wi);
0794:                        break;
0795:                    case (WorkflowItem.CONTENT_LOCKING_WORKFLOW):
0796:                        processContentLockingWorkflow(wi, compWizard);
0797:                        break;
0798:                    }
0799:                }
0800:            }
0801:
0802:            private void processStatusChangeWorkflow(String status,
0803:                    CompletedWizard actionWizard) {
0804:                actionWizard.setStatus(status);
0805:            }
0806:
0807:            private void processStatusChangeWorkflow(WorkflowItem wi,
0808:                    CompletedWizard actionWizard) {
0809:                processStatusChangeWorkflow(wi.getActionValue(), actionWizard);
0810:            }
0811:
0812:            private void processContentLockingWorkflow(String lockAction,
0813:                    CompletedWizard actionWizard) {
0814:                //TODO implement
0815:            }
0816:
0817:            private void processContentLockingWorkflow(WorkflowItem wi,
0818:                    CompletedWizard actionWizard) {
0819:                processContentLockingWorkflow(wi.getActionValue(), actionWizard);
0820:            }
0821:
0822:            private void processNotificationWorkflow(WorkflowItem wi) {
0823:                // TODO implement
0824:
0825:            }
0826:
0827:            /**
0828:             * {@inheritDoc}
0829:             */
0830:            public void checkWizardAccess(Id id) {
0831:                CompletedWizard cw = getCompletedWizard(id);
0832:
0833:                if (cw == null) {
0834:                    logger.error("checkWizardAccess: No such wizard "
0835:                            + id.toString());
0836:                    return;
0837:                }
0838:
0839:                boolean canEval = getAuthorizationFacade().isAuthorized(
0840:                        WizardFunctionConstants.EVALUATE_WIZARD,
0841:                        cw.getWizard().getId());
0842:                boolean canReview = getAuthorizationFacade().isAuthorized(
0843:                        WizardFunctionConstants.REVIEW_WIZARD,
0844:                        getIdManager().getId(cw.getWizard().getSiteId()));
0845:                boolean canReflect = canEval || canReview;
0846:
0847:                boolean owns = cw.getOwner().getId().equals(
0848:                        getAuthManager().getAgent().getId());
0849:
0850:                if (canEval || owns) {
0851:                    //can I look at reviews/evals/reflections? - own or eval
0852:                    getReviewManager().getReviewsByParentAndType(id.getValue(),
0853:                            Review.EVALUATION_TYPE, cw.getWizard().getSiteId(),
0854:                            WizardEntityProducer.WIZARD_PRODUCER);
0855:                }
0856:
0857:                if (canReview || owns) {
0858:                    //can I look at reviews/evals/reflections? - own or review
0859:                    getReviewManager().getReviewsByParentAndType(id.getValue(),
0860:                            Review.FEEDBACK_TYPE, cw.getWizard().getSiteId(),
0861:                            WizardEntityProducer.WIZARD_PRODUCER);
0862:                }
0863:
0864:                if (canReflect || owns) {
0865:                    //can I look at reviews/evals/reflections? - own or reflect
0866:                    getReviewManager().getReviewsByParentAndType(id.getValue(),
0867:                            Review.REFLECTION_TYPE, cw.getWizard().getSiteId(),
0868:                            WizardEntityProducer.WIZARD_PRODUCER);
0869:                }
0870:            }
0871:
0872:            /**
0873:             * {@inheritDoc}
0874:             */
0875:            public int getTotalPageCount(final Wizard wizard) {
0876:                HibernateCallback hcb = new HibernateCallback() {
0877:                    public Object doInHibernate(Session session)
0878:                            throws HibernateException, SQLException {
0879:                        String queryString = "select count(page) from WizardPageSequence page, WizardCategory category "
0880:                                + "where page.category = category.id and category.wizard = ?";
0881:
0882:                        Query query = session.createQuery(queryString);
0883:
0884:                        query.setParameter(0, wizard.getId().getValue(),
0885:                                Hibernate.STRING);
0886:
0887:                        Integer results = (Integer) query.uniqueResult();
0888:                        return results;
0889:                    }
0890:                };
0891:
0892:                return ((Integer) getHibernateTemplate().execute(hcb))
0893:                        .intValue();
0894:            }
0895:
0896:            /**
0897:             * {@inheritDoc}
0898:             */
0899:            public String getWizardIdSiteId(final Id wizardId) {
0900:
0901:                try {
0902:                    net.sf.ehcache.Element elem = null;
0903:                    if (wizardId != null)
0904:                        elem = siteCache.get(wizardId.getValue());
0905:                    if (siteCache != null && elem != null) {
0906:                        if (elem.getValue() == null)
0907:                            return null;
0908:                        return elem.getValue().toString();
0909:                    }
0910:                } catch (CacheException e) {
0911:                    logger.warn("the wizard ehcache had an exception", e);
0912:                }
0913:                String siteId;
0914:
0915:                HibernateCallback hcb = new HibernateCallback() {
0916:                    public Object doInHibernate(Session session)
0917:                            throws HibernateException, SQLException {
0918:                        String queryString = "select wizard.siteId from Wizard wizard where wizard.id = ?";
0919:
0920:                        Query query = session.createQuery(queryString);
0921:
0922:                        query.setParameter(0, wizardId.getValue(),
0923:                                Hibernate.STRING);
0924:
0925:                        String results = (String) query.uniqueResult();
0926:
0927:                        /*
0928:                        	//CWM just testing out some different hibernate options...
0929:                        Criteria c = session.createCriteria(Wizard.class);
0930:                        Criteria rootCat = c.createCriteria("rootCategory");
0931:                        rootCat.setFetchMode("childPages", FetchMode.SELECT);
0932:                        rootCat.setFetchMode("childCategories", FetchMode.SELECT);
0933:                        c.add(Expression.eq("id", wizardId));
0934:                        Wizard wiz = (Wizard) c.uniqueResult();
0935:                        if (wiz == null) return null;
0936:                        String results = wiz.getSiteId();
0937:                         */
0938:
0939:                        return results;
0940:                    }
0941:                };
0942:                siteId = ((String) getHibernateTemplate().execute(hcb));
0943:                if (siteCache != null)
0944:                    siteCache.put(new net.sf.ehcache.Element(wizardId
0945:                            .getValue(), siteId));
0946:
0947:                return siteId;
0948:            }
0949:
0950:            /**
0951:             * {@inheritDoc}
0952:             */
0953:            public Agent getWizardIdOwner(final Id wizardId) {
0954:                HibernateCallback hcb = new HibernateCallback() {
0955:                    public Object doInHibernate(Session session)
0956:                            throws HibernateException, SQLException {
0957:                        String queryString = "select wizard.owner from Wizard wizard where wizard.id = ?";
0958:
0959:                        Query query = session.createQuery(queryString);
0960:
0961:                        query.setParameter(0, wizardId.getValue(),
0962:                                Hibernate.STRING);
0963:
0964:                        Agent results = (Agent) query.uniqueResult();
0965:                        return results;
0966:                    }
0967:                };
0968:
0969:                return ((Agent) getHibernateTemplate().execute(hcb));
0970:            }
0971:
0972:            /**
0973:             * {@inheritDoc}
0974:             */
0975:            public int getSubmittedPageCount(final CompletedWizard wizard) {
0976:                HibernateCallback hcb = new HibernateCallback() {
0977:                    public Object doInHibernate(Session session)
0978:                            throws HibernateException, SQLException {
0979:                        String queryString = "select count(page) "
0980:                                + "from WizardPage page, CompletedWizardPage completedPage, CompletedWizardCategory category "
0981:                                + "where page.id = completedPage.wizardPage and "
0982:                                + "      completedPage.category = category.id and "
0983:                                + "      category.wizard = ? and "
0984:                                + "      page.status != ?";
0985:
0986:                        Query query = session.createQuery(queryString);
0987:
0988:                        query.setParameter(0, wizard.getId().getValue(),
0989:                                Hibernate.STRING);
0990:                        query.setParameter(1,
0991:                                MatrixFunctionConstants.READY_STATUS,
0992:                                Hibernate.STRING);
0993:
0994:                        Integer results = (Integer) query.uniqueResult();
0995:                        return results;
0996:                    }
0997:                };
0998:
0999:                return ((Integer) getHibernateTemplate().execute(hcb))
1000:                        .intValue();
1001:            }
1002:
1003:            public AuthorizationFacade getAuthorizationFacade() {
1004:                return authorizationFacade;
1005:            }
1006:
1007:            public void setAuthorizationFacade(
1008:                    AuthorizationFacade authorizationFacade) {
1009:                this .authorizationFacade = authorizationFacade;
1010:            }
1011:
1012:            public EntityManager getEntityManager() {
1013:                return entityManager;
1014:            }
1015:
1016:            public void setEntityManager(EntityManager entityManager) {
1017:                this .entityManager = entityManager;
1018:            }
1019:
1020:            public IdManager getIdManager() {
1021:                return idManager;
1022:            }
1023:
1024:            public void setIdManager(IdManager idManager) {
1025:                this .idManager = idManager;
1026:            }
1027:
1028:            public SecurityService getSecurityService() {
1029:                return securityService;
1030:            }
1031:
1032:            public void setSecurityService(SecurityService securityService) {
1033:                this .securityService = securityService;
1034:            }
1035:
1036:            public StructuredArtifactDefinitionManager getStructuredArtifactDefinitionManager() {
1037:                return structuredArtifactDefinitionManager;
1038:            }
1039:
1040:            public void setStructuredArtifactDefinitionManager(
1041:                    StructuredArtifactDefinitionManager structuredArtifactDefinitionManager) {
1042:                this .structuredArtifactDefinitionManager = structuredArtifactDefinitionManager;
1043:            }
1044:
1045:            public AgentManager getAgentManager() {
1046:                return agentManager;
1047:            }
1048:
1049:            public void setAgentManager(AgentManager agentManager) {
1050:                this .agentManager = agentManager;
1051:            }
1052:
1053:            public AuthenticationManager getAuthManager() {
1054:                return authManager;
1055:            }
1056:
1057:            public void setAuthManager(AuthenticationManager authManager) {
1058:                this .authManager = authManager;
1059:            }
1060:
1061:            public GuidanceManager getGuidanceManager() {
1062:                return guidanceManager;
1063:            }
1064:
1065:            public void setGuidanceManager(GuidanceManager guidanceManager) {
1066:                this .guidanceManager = guidanceManager;
1067:            }
1068:
1069:            /**
1070:             * @return Returns the workflowManager.
1071:             */
1072:            public WorkflowManager getWorkflowManager() {
1073:                return workflowManager;
1074:            }
1075:
1076:            /**
1077:             * @param workflowManager The workflowManager to set.
1078:             */
1079:            public void setWorkflowManager(WorkflowManager workflowManager) {
1080:                this .workflowManager = workflowManager;
1081:            }
1082:
1083:            public ContentHostingService getContentHosting() {
1084:                return contentHosting;
1085:            }
1086:
1087:            public void setContentHosting(ContentHostingService contentHosting) {
1088:                this .contentHosting = contentHosting;
1089:            }
1090:
1091:            public boolean importResource(Id worksiteId, String nodeId)
1092:                    throws UnsupportedFileTypeException, ImportException {
1093:
1094:                String id = getContentHosting().resolveUuid(nodeId);
1095:                try {
1096:                    ContentResource resource = getContentHosting().getResource(
1097:                            id);
1098:                    MimeType mimeType = new MimeType(resource.getContentType());
1099:
1100:                    if (mimeType.equals(new MimeType("application/zip"))
1101:                            || mimeType.equals(new MimeType(
1102:                                    "application/x-zip-compressed"))) {
1103:                        InputStream zipContent = resource.streamContent();
1104:                        Wizard bean = importWizard(worksiteId, zipContent);
1105:
1106:                        return bean != null;
1107:                    } else {
1108:                        throw new UnsupportedFileTypeException(
1109:                                "Unsupported file type");
1110:                    }
1111:                } catch (ServerOverloadException soe) {
1112:                    logger.warn(soe);
1113:                } catch (IOException ioe) {
1114:                    logger.warn(ioe);
1115:                } catch (PermissionException pe) {
1116:                    logger
1117:                            .warn(
1118:                                    "Failed loading content: no permission to view file",
1119:                                    pe);
1120:                } catch (TypeException te) {
1121:                    logger.warn("Wrong type", te);
1122:                } catch (IdUnusedException iue) {
1123:                    logger.warn("UnusedId: ", iue);
1124:                }
1125:                return false;
1126:            }
1127:
1128:            private Wizard importWizard(Id worksiteId, InputStream in)
1129:                    throws IOException, ImportException {
1130:                ZipInputStream zis = new ZipInputStream(in);
1131:
1132:                Wizard bean = readWizardFromZip(zis, worksiteId.getValue());
1133:                return bean;
1134:            }
1135:
1136:            private static final String IMPORT_CREATE_DATE_KEY = "createDate";
1137:            private static final String IMPORT_EVALUATORS_KEY = "evaluators";
1138:
1139:            //private static final String IMPORT_STYLES_KEY = "style";
1140:            private Wizard readWizardFromZip(ZipInputStream zis,
1141:                    String worksiteId) throws IOException, ImportException {
1142:                ZipEntry currentEntry = zis.getNextEntry();
1143:
1144:                if (currentEntry == null)
1145:                    return null;
1146:
1147:                Map importData = new HashMap();
1148:                Wizard wizard = new Wizard(null, getAuthManager().getAgent(),
1149:                        worksiteId);
1150:                String tempDirName = getIdManager().createId().getValue();
1151:
1152:                // set values not coming from the zip
1153:                wizard.setCreated(new Date(System.currentTimeMillis()));
1154:                wizard.setModified(wizard.getCreated());
1155:                wizard.setNewId(getIdManager().createId());
1156:
1157:                importData.put(IMPORT_CREATE_DATE_KEY, wizard.getCreated());
1158:                importData.put(IMPORT_EVALUATORS_KEY, new HashMap()); // key: userid  value: isRole
1159:                //importData.put(IMPORT_STYLES_KEY, new HashMap());
1160:
1161:                Map formsMap = new Hashtable();
1162:                Map guidanceMap = null;
1163:                Map styleMap = null;
1164:                Map resourceMap = new Hashtable();
1165:                try {
1166:                    boolean gotFile = false;
1167:
1168:                    // read the wizard
1169:                    readWizardXML(wizard, zis, importData);
1170:                    // presentationmanagerimpl: 2642
1171:                    ContentCollectionEdit fileParent = getFileDir(tempDirName);
1172:
1173:                    currentEntry = zis.getNextEntry();
1174:                    while (currentEntry != null) {
1175:                        if (!currentEntry.isDirectory()) {
1176:                            if (currentEntry.getName().startsWith("forms/")) {
1177:                                processMatrixForm(currentEntry, zis, formsMap,
1178:                                        getIdManager().getId(worksiteId));
1179:                            } else if (currentEntry.getName().startsWith(
1180:                                    "guidance/")) {
1181:                                guidanceMap = processMatrixGuidance(fileParent,
1182:                                        worksiteId, zis);
1183:
1184:                                for (Iterator i = guidanceMap.values()
1185:                                        .iterator(); i.hasNext();) {
1186:                                    Guidance g = (Guidance) i.next();
1187:
1188:                                    // hack for:  
1189:                                    //    This will only be for wizards exported before r13782
1190:                                    if (g
1191:                                            .getSecurityViewFunction()
1192:                                            .equals(
1193:                                                    WizardFunctionConstants.VIEW_WIZARD))
1194:                                        g
1195:                                                .setSecurityViewFunction(WizardFunctionConstants.OPERATE_WIZARD);
1196:                                }
1197:
1198:                                gotFile = true;
1199:                            } else if (currentEntry.getName().startsWith(
1200:                                    "style/")) {
1201:                                styleMap = processMatrixStyle(fileParent,
1202:                                        worksiteId, zis);
1203:                                gotFile = true;
1204:                            } else {
1205:                                importAttachmentRef(fileParent, currentEntry,
1206:                                        worksiteId, zis, resourceMap);
1207:                                gotFile = true;
1208:                            }
1209:                        }
1210:                        zis.closeEntry();
1211:                        currentEntry = zis.getNextEntry();
1212:                    }
1213:
1214:                    if (gotFile) {
1215:                        fileParent.getPropertiesEdit().addProperty(
1216:                                ResourceProperties.PROP_DISPLAY_NAME,
1217:                                wizard.getName());
1218:                        getContentHosting().commitCollection(fileParent);
1219:                    } else {
1220:                        getContentHosting().cancelCollection(fileParent);
1221:                    }
1222:                    // the wizard needs to be saved so it has an id
1223:                    // the id is needed because guidance needs the security qualifier
1224:                    replaceIds(wizard, guidanceMap, formsMap, styleMap);
1225:                    wizard = saveWizard(wizard);
1226:
1227:                    // set the wizard evaluators
1228:                    Map wizardEvaluators = (Map) importData
1229:                            .get(IMPORT_EVALUATORS_KEY);
1230:                    for (Iterator i = wizardEvaluators.keySet().iterator(); i
1231:                            .hasNext();) {
1232:                        String userId = (String) i.next();
1233:
1234:                        if (userId.startsWith("/site/")) {
1235:                            // it's a role
1236:                            String[] agentValues = userId.split("/");
1237:
1238:                            userId = userId.replaceAll(agentValues[2],
1239:                                    worksiteId);
1240:                        }
1241:                        Agent agent = agentManager.getAgent(idManager
1242:                                .getId(userId));
1243:                        if (agent != null && agent.getId() != null)
1244:                            authorizationFacade.createAuthorization(agent,
1245:                                    WizardFunctionConstants.EVALUATE_WIZARD,
1246:                                    wizard.getId());
1247:                    }
1248:
1249:                    //set the authorization for the pages
1250:                    setAuthnCat(wizard.getRootCategory(), worksiteId);
1251:
1252:                } catch (ImportException ie) {
1253:                    throw new ImportException(ie);
1254:                } catch (Exception e) {
1255:                    throw new RuntimeException(e);
1256:                } finally {
1257:                    try {
1258:                        zis.closeEntry();
1259:                    } catch (IOException e) {
1260:                        logger.error("", e);
1261:                    }
1262:                }
1263:                return wizard;
1264:            }
1265:
1266:            private void setAuthnCat(WizardCategory cat, String worksite) {
1267:
1268:                List pages = cat.getChildPages();
1269:                for (Iterator i = pages.iterator(); i.hasNext();) {
1270:                    WizardPageSequence sequence = (WizardPageSequence) i.next();
1271:                    WizardPageDefinition pageDef = sequence
1272:                            .getWizardPageDefinition();
1273:
1274:                    for (Iterator ii = pageDef.getEvaluators().iterator(); ii
1275:                            .hasNext();) {
1276:                        String strId = (String) ii.next();
1277:
1278:                        if (strId.startsWith("/site/")) {
1279:                            // it's a role
1280:                            String[] agentValues = strId.split("/");
1281:
1282:                            strId = strId.replaceAll(agentValues[2], worksite);
1283:                        }
1284:                        Agent agent = agentManager.getAgent(idManager
1285:                                .getId(strId));
1286:
1287:                        if (agent != null && agent.getId() != null)
1288:                            authorizationFacade.createAuthorization(agent,
1289:                                    MatrixFunctionConstants.EVALUATE_MATRIX,
1290:                                    pageDef.getId());
1291:                    }
1292:                }
1293:            }
1294:
1295:            /**
1296:             * gets the current user's resource collection
1297:             * 
1298:             * @return ContentCollection
1299:             * @throws TypeException
1300:             * @throws IdUnusedException
1301:             * @throws PermissionException
1302:             */
1303:            protected ContentCollection getUserCollection()
1304:                    throws TypeException, IdUnusedException,
1305:                    PermissionException {
1306:                User user = UserDirectoryService.getCurrentUser();
1307:                String userId = user.getId();
1308:                String wsId = SiteService.getUserSiteId(userId);
1309:                String wsCollectionId = getContentHosting().getSiteCollection(
1310:                        wsId);
1311:                ContentCollection collection = getContentHosting()
1312:                        .getCollection(wsCollectionId);
1313:                return collection;
1314:            }
1315:
1316:            protected Map processMatrixGuidance(ContentCollection parent,
1317:                    String siteId, ZipInputStream zis) throws IOException {
1318:                return getGuidanceManager().importGuidanceList(parent, siteId,
1319:                        zis);
1320:            }
1321:
1322:            protected Map processMatrixStyle(ContentCollection parent,
1323:                    String siteId, ZipInputStream zis) throws IOException {
1324:                return getStyleManager().importStyleList(parent, siteId, zis);
1325:            }
1326:
1327:            /**
1328:             * This gets the directory in which the import places files into.
1329:             * 
1330:             * This method gets the current users base collection, creates an imported directory,
1331:             * then uses the param to create a new directory.
1332:             * 
1333:             * this uses the bean property importFolderName to name the
1334:             * 
1335:             * @param origName String
1336:             * @return ContentCollectionEdit
1337:             * @throws InconsistentException
1338:             * @throws PermissionException
1339:             * @throws IdUsedException
1340:             * @throws IdInvalidException
1341:             * @throws IdUnusedException
1342:             * @throws TypeException
1343:             */
1344:            protected ContentCollectionEdit getFileDir(String origName)
1345:                    throws InconsistentException, PermissionException,
1346:                    IdUsedException, IdInvalidException, IdUnusedException,
1347:                    TypeException {
1348:                ContentCollection userCollection = getUserCollection();
1349:
1350:                try {
1351:                    //TODO use the bean org.theospi.portfolio.admin.model.IntegrationOption.siteOption 
1352:                    // in common/components to get the name and id for this site.
1353:
1354:                    ContentCollectionEdit groupCollection = getContentHosting()
1355:                            .addCollection(
1356:                                    userCollection.getId()
1357:                                            + IMPORT_BASE_FOLDER_ID);
1358:                    groupCollection.getPropertiesEdit().addProperty(
1359:                            ResourceProperties.PROP_DISPLAY_NAME,
1360:                            getImportFolderName());
1361:                    getContentHosting().commitCollection(groupCollection);
1362:                } catch (IdUsedException e) {
1363:                    // ignore... it is already there.
1364:                    if (logger.isDebugEnabled()) {
1365:                        logger.debug(e);
1366:                    }
1367:                } catch (Exception e) {
1368:                    throw new RuntimeException(e);
1369:                }
1370:
1371:                ContentCollection collection = getContentHosting()
1372:                        .getCollection(
1373:                                userCollection.getId() + IMPORT_BASE_FOLDER_ID
1374:                                        + "/");
1375:
1376:                String childId = collection.getId() + origName;
1377:                return getContentHosting().addCollection(childId);
1378:            }
1379:
1380:            protected void processMatrixForm(ZipEntry currentEntry,
1381:                    ZipInputStream zis, Map formMap, Id worksite)
1382:                    throws IOException {
1383:                File file = new File(currentEntry.getName());
1384:                String fileName = file.getName();
1385:                String oldId = fileName.substring(0, fileName.indexOf(".form"));
1386:
1387:                StructuredArtifactDefinitionBean bean;
1388:                try {
1389:                    //we want the bean even if it exists already
1390:                    bean = getStructuredArtifactDefinitionManager().importSad(
1391:                            worksite, zis, true, false, false);
1392:                } catch (ImportException ie) {
1393:                    throw new RuntimeException(
1394:                            "the structured artifact failed to import", ie);
1395:                }
1396:
1397:                formMap.put(oldId, bean.getId().getValue());
1398:            }
1399:
1400:            protected void importAttachmentRef(ContentCollection fileParent,
1401:                    ZipEntry currentEntry, String siteId, ZipInputStream zis,
1402:                    Map resourceMap) {
1403:                File file = new File(currentEntry.getName());
1404:
1405:                MimeType mimeType = new MimeType(file.getParentFile()
1406:                        .getParentFile().getParentFile().getName(), file
1407:                        .getParentFile().getParentFile().getName());
1408:
1409:                String contentType = mimeType.getValue();
1410:
1411:                String oldId = file.getParentFile().getName();
1412:
1413:                try {
1414:                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
1415:                    int c = zis.read();
1416:
1417:                    while (c != -1) {
1418:                        bos.write(c);
1419:                        c = zis.read();
1420:                    }
1421:
1422:                    String fileId = ((fileParent != null) ? fileParent.getId()
1423:                            : "")
1424:                            + file.getName();
1425:                    ContentResourceEdit resource = getContentHosting()
1426:                            .addResource(fileId);
1427:                    ResourcePropertiesEdit resourceProperties = resource
1428:                            .getPropertiesEdit();
1429:                    resourceProperties.addProperty(
1430:                            ResourceProperties.PROP_DISPLAY_NAME, file
1431:                                    .getName());
1432:                    resource.setContent(bos.toByteArray());
1433:                    resource.setContentType(contentType);
1434:                    getContentHosting().commitResource(resource);
1435:                    resourceMap.put(oldId, resource.getReference());
1436:                } catch (Exception exp) {
1437:                    throw new RuntimeException(exp);
1438:                }
1439:            }
1440:
1441:            private boolean readWizardXML(Wizard wizard, InputStream inStream,
1442:                    Map importData) throws ImportException {
1443:                SAXBuilder builder = new SAXBuilder();
1444:                Map evaluatorsMap = (Map) importData.get(IMPORT_EVALUATORS_KEY);
1445:                //Map stylesMap = (Map)importData.get(IMPORT_STYLES_KEY);
1446:
1447:                try {
1448:                    byte[] bytes = readStreamToBytes(inStream);
1449:                    Document document = builder.build(new ByteArrayInputStream(
1450:                            bytes));
1451:
1452:                    Element topNode = document.getRootElement();
1453:
1454:                    wizard.setName(topNode.getChildTextTrim("name"));
1455:                    wizard.setDescription(topNode
1456:                            .getChildTextTrim("description"));
1457:                    wizard.setKeywords(topNode.getChildTextTrim("keywords"));
1458:                    wizard.setType(topNode.getChildTextTrim("type"));
1459:                    wizard.setSequence(Integer.parseInt(topNode
1460:                            .getChildTextTrim("sequence")));
1461:
1462:                    // Read the evaluators
1463:                    List evaluators = topNode.getChild("evaluators")
1464:                            .getChildren("evaluator");
1465:                    for (Iterator i = evaluators.iterator(); i.hasNext();) {
1466:                        Element evaluator = (Element) i.next();
1467:
1468:                        String userId = evaluator.getTextTrim();
1469:                        boolean isRole = evaluator.getAttribute("isRole")
1470:                                .getBooleanValue();
1471:
1472:                        evaluatorsMap.put(userId, new Boolean(isRole));
1473:                    }
1474:
1475:                    // read the evaluation, review, reflection
1476:                    Element workflow = topNode.getChild("workflow");
1477:
1478:                    String wfType, wfId;
1479:
1480:                    wfType = workflow.getChildTextTrim("evaluationDeviceType");
1481:                    wfId = workflow.getChildTextTrim("evaluationDevice");
1482:                    wizard.setEvaluationDeviceType(wfType);
1483:                    wizard.setEvaluationDevice(idManager.getId(wfId));
1484:
1485:                    wfType = workflow.getChildTextTrim("reflectionDeviceType");
1486:                    wfId = workflow.getChildTextTrim("reflectionDevice");
1487:                    wizard.setReflectionDeviceType(wfType);
1488:                    wizard.setReflectionDevice(idManager.getId(wfId));
1489:
1490:                    wfType = workflow.getChildTextTrim("reviewDeviceType");
1491:                    wfId = workflow.getChildTextTrim("reviewDevice");
1492:                    wizard.setReviewDeviceType(wfType);
1493:                    wizard.setReviewDevice(idManager.getId(wfId));
1494:
1495:                    // read the wizard guidance to the list
1496:                    String guidanceIdStr = topNode.getChildTextTrim("guidance");
1497:                    wizard.setGuidanceId(idManager.getId(guidanceIdStr));
1498:
1499:                    // read the categories/pages
1500:                    readCategoriesAndPages(wizard, wizard.getRootCategory(),
1501:                            topNode.getChild("category"), importData);
1502:
1503:                    //   pull the styles from the xml
1504:                    //    WizardStyleItem only works with Resources not IDs
1505:
1506:                    String styleIdStr = topNode.getChildTextTrim("style");
1507:                    wizard.setStyleId(getIdManager().getId(styleIdStr));
1508:                    //stylesMap.put(styleId, null);
1509:
1510:                } catch (Exception jdome) {
1511:                    throw new ImportException(jdome);
1512:                }
1513:                return true;
1514:            }
1515:
1516:            private void readCategoriesAndPages(Wizard wizard,
1517:                    WizardCategory category, Element categoryNode,
1518:                    Map importData) throws DataConversionException {
1519:                category.setCreated((Date) importData
1520:                        .get(IMPORT_CREATE_DATE_KEY));
1521:                category.setModified((Date) importData
1522:                        .get(IMPORT_CREATE_DATE_KEY));
1523:
1524:                category.setTitle(categoryNode.getChildTextTrim("title"));
1525:                category.setDescription(categoryNode
1526:                        .getChildTextTrim("description"));
1527:                category.setKeywords(categoryNode.getChildTextTrim("keywords"));
1528:                category.setSequence(Integer.parseInt(categoryNode
1529:                        .getChildTextTrim("sequence")));
1530:                category.setWizard(wizard);
1531:
1532:                List pageSequences = categoryNode.getChild("pages")
1533:                        .getChildren("pageSequence");
1534:                List pages = new ArrayList();
1535:                for (Iterator i = pageSequences.iterator(); i.hasNext();) {
1536:                    Element pageSequenceNode = (Element) i.next();
1537:                    WizardPageSequence pageSequence = new WizardPageSequence();
1538:
1539:                    pageSequence.setCategory(category);
1540:                    pageSequence.setTitle(pageSequenceNode
1541:                            .getChildTextTrim("title"));
1542:                    pageSequence.setSequence(Integer.parseInt(pageSequenceNode
1543:                            .getChildTextTrim("sequence")));
1544:
1545:                    Element pageDefNode = pageSequenceNode.getChild("pageDef");
1546:                    WizardPageDefinition wizardPageDefinition = new WizardPageDefinition();
1547:
1548:                    wizardPageDefinition.setNewId(getIdManager().createId());
1549:
1550:                    wizardPageDefinition.setTitle(pageDefNode
1551:                            .getChildTextTrim("title"));
1552:                    wizardPageDefinition.setDescription(pageDefNode
1553:                            .getChildTextTrim("description"));
1554:                    wizardPageDefinition.setInitialStatus(pageDefNode
1555:                            .getChildTextTrim("initialStatus"));
1556:
1557:                    // read the page workflow
1558:                    String wfType, wfId;
1559:                    Element workflow = pageDefNode.getChild("workflow");
1560:
1561:                    wfType = workflow.getChildTextTrim("evaluationDeviceType");
1562:                    wfId = workflow.getChildTextTrim("evaluationDevice");
1563:                    wizardPageDefinition.setEvaluationDeviceType(wfType);
1564:                    wizardPageDefinition.setEvaluationDevice(idManager
1565:                            .getId(wfId));
1566:
1567:                    wfType = workflow.getChildTextTrim("reflectionDeviceType");
1568:                    wfId = workflow.getChildTextTrim("reflectionDevice");
1569:                    wizardPageDefinition.setReflectionDeviceType(wfType);
1570:                    wizardPageDefinition.setReflectionDevice(idManager
1571:                            .getId(wfId));
1572:
1573:                    wfType = workflow.getChildTextTrim("reviewDeviceType");
1574:                    wfId = workflow.getChildTextTrim("reviewDevice");
1575:                    wizardPageDefinition.setReviewDeviceType(wfType);
1576:                    wizardPageDefinition.setReviewDevice(idManager.getId(wfId));
1577:
1578:                    // read the page guidance
1579:                    String guidanceIdStr = pageDefNode
1580:                            .getChildTextTrim("guidance");
1581:                    wizardPageDefinition.setGuidanceId(idManager
1582:                            .getId(guidanceIdStr));
1583:
1584:                    // read the page style
1585:                    String styleIdStr = pageDefNode.getChildTextTrim("style");
1586:                    wizardPageDefinition.setStyleId(getIdManager().getId(
1587:                            styleIdStr));
1588:
1589:                    // read the into about additional forms
1590:                    if (pageDefNode.getChild("additionalForms") != null) {
1591:                        List forms = pageDefNode.getChild("additionalForms")
1592:                                .getChildren("form");
1593:                        List formsList = new ArrayList();
1594:                        for (Iterator ii = forms.iterator(); ii.hasNext();) {
1595:                            Element form = (Element) ii.next();
1596:
1597:                            String formId = form.getTextTrim();
1598:                            formsList.add(formId);
1599:                        }
1600:                        wizardPageDefinition.setAdditionalForms(formsList);
1601:                    }
1602:
1603:                    // read the evaluators of the page, they are external to the wizard, store
1604:                    if (pageDefNode.getChild("evaluators") != null) {
1605:                        List evaluators = pageDefNode.getChild("evaluators")
1606:                                .getChildren("evaluator");
1607:                        List evaluatorsList = new ArrayList();
1608:                        for (Iterator ii = evaluators.iterator(); ii.hasNext();) {
1609:                            Element evaluator = (Element) ii.next();
1610:
1611:                            String evaluatorId = evaluator.getTextTrim();
1612:                            boolean isRole = false;
1613:                            if (evaluator.getAttribute("isRole") != null)
1614:                                isRole = evaluator.getAttribute("isRole")
1615:                                        .getBooleanValue();
1616:                            evaluatorsList.add(evaluatorId);
1617:                        }
1618:                        wizardPageDefinition.setEvaluators(evaluatorsList);
1619:                    }
1620:
1621:                    pageSequence.setWizardPageDefinition(wizardPageDefinition);
1622:                    pages.add(pageSequence);
1623:                }
1624:                category.setChildPages(pages);
1625:
1626:                List categoryNodes = categoryNode.getChild("childCategories")
1627:                        .getChildren("category");
1628:                List categories = new ArrayList();
1629:                for (Iterator i = categoryNodes.iterator(); i.hasNext();) {
1630:                    Element pageSequenceNode = (Element) i.next();
1631:                    WizardCategory childCategory = new WizardCategory();
1632:                    childCategory.setParentCategory(category);
1633:                    readCategoriesAndPages(wizard, childCategory,
1634:                            pageSequenceNode, importData);
1635:                    categories.add(childCategory);
1636:                }
1637:                category.setChildCategories(categories);
1638:            }
1639:
1640:            protected void replaceIds(Wizard wizard, Map guidanceMap,
1641:                    Map formsMap, Map styleMap) {
1642:                wizard.setEvalWorkflows(getWorkflowManager()
1643:                        .createEvalWorkflows(wizard));
1644:
1645:                replaceCatIds(wizard.getRootCategory(), guidanceMap, formsMap,
1646:                        styleMap);
1647:
1648:                if (wizard.getEvaluationDevice() != null
1649:                        && wizard.getEvaluationDevice().getValue() != null)
1650:                    wizard.setEvaluationDevice(idManager
1651:                            .getId((String) formsMap.get(wizard
1652:                                    .getEvaluationDevice().getValue())));
1653:
1654:                if (wizard.getReflectionDevice() != null
1655:                        && wizard.getReflectionDevice().getValue() != null)
1656:                    wizard.setReflectionDevice(idManager
1657:                            .getId((String) formsMap.get(wizard
1658:                                    .getReflectionDevice().getValue())));
1659:
1660:                if (wizard.getReviewDevice() != null
1661:                        && wizard.getReviewDevice().getValue() != null)
1662:                    wizard.setReviewDevice(idManager.getId((String) formsMap
1663:                            .get(wizard.getReviewDevice().getValue())));
1664:
1665:                if (wizard.getGuidanceId() != null
1666:                        && wizard.getGuidanceId().getValue() != null
1667:                        && wizard.getGuidanceId().getValue().length() > 0) {
1668:                    Guidance wizardGuidance = (Guidance) guidanceMap.get(wizard
1669:                            .getGuidanceId().getValue());
1670:                    if (wizardGuidance == null)
1671:                        throw new NullPointerException(
1672:                                "Guidance for Wizard was not found");
1673:
1674:                    wizardGuidance.setSecurityQualifier(wizard.getNewId());
1675:                    getGuidanceManager().saveGuidance(wizardGuidance);
1676:                    wizard.setGuidanceId(wizardGuidance.getId());
1677:                }
1678:                if (wizard.getStyleId() != null
1679:                        && wizard.getStyleId().getValue() != null
1680:                        && wizard.getStyleId().getValue().length() > 0) {
1681:                    Style wizardStyle = (Style) styleMap.get(wizard
1682:                            .getStyleId().getValue());
1683:                    if (wizardStyle == null)
1684:                        throw new NullPointerException(
1685:                                "Style for Wizard was not found");
1686:                    getStyleManager().storeStyle(wizardStyle, false);
1687:                    wizard.setStyle(wizardStyle);
1688:                }
1689:            }
1690:
1691:            /**
1692:             * runs through each of the pages in the category and maps the guidance and 
1693:             * additional forms from the old ids to the new ids.  It saves and sets the
1694:             * guidance and page style as well.  Lastly, it loops into the sub categories.
1695:             * @param cat  WizardCategory
1696:             * @param guidanceMap Map
1697:             * @param formsMap Map
1698:             * @param styleMap Map
1699:             */
1700:            protected void replaceCatIds(WizardCategory cat, Map guidanceMap,
1701:                    Map formsMap, Map styleMap) {
1702:                for (Iterator i = cat.getChildPages().iterator(); i.hasNext();) {
1703:                    WizardPageSequence sequence = (WizardPageSequence) i.next();
1704:                    WizardPageDefinition definition = (WizardPageDefinition) sequence
1705:                            .getWizardPageDefinition();
1706:                    definition.setSiteId(cat.getWizard().getSiteId());
1707:
1708:                    if (definition.getEvaluationDevice() != null
1709:                            && definition.getEvaluationDevice().getValue() != null)
1710:                        definition.setEvaluationDevice(idManager
1711:                                .getId((String) formsMap.get(definition
1712:                                        .getEvaluationDevice().getValue())));
1713:
1714:                    if (definition.getReflectionDevice() != null
1715:                            && definition.getReflectionDevice().getValue() != null)
1716:                        definition.setReflectionDevice(idManager
1717:                                .getId((String) formsMap.get(definition
1718:                                        .getReflectionDevice().getValue())));
1719:
1720:                    if (definition.getReviewDevice() != null
1721:                            && definition.getReviewDevice().getValue() != null)
1722:                        definition.setReviewDevice(idManager
1723:                                .getId((String) formsMap.get(definition
1724:                                        .getReviewDevice().getValue())));
1725:
1726:                    definition.setEvalWorkflows(new HashSet(
1727:                            getWorkflowManager()
1728:                                    .createEvalWorkflows(definition)));
1729:
1730:                    List newAddForms = new ArrayList();
1731:                    for (Iterator ii = definition.getAdditionalForms()
1732:                            .iterator(); ii.hasNext();) {
1733:                        String addForm = (String) ii.next();
1734:                        if (addForm != null)
1735:                            newAddForms.add(formsMap.get(addForm));
1736:                    }
1737:                    definition.setAdditionalForms(newAddForms);
1738:
1739:                    if (definition.getGuidanceId() != null
1740:                            && definition.getGuidanceId().getValue() != null
1741:                            && definition.getGuidanceId().getValue().length() > 0) {
1742:                        Guidance pageDefGuidance = (Guidance) guidanceMap
1743:                                .get(definition.getGuidanceId().getValue());
1744:
1745:                        if (pageDefGuidance == null)
1746:                            throw new NullPointerException(
1747:                                    "Guidance for Wizard Page was not found");
1748:
1749:                        pageDefGuidance.setSecurityQualifier(definition
1750:                                .getVirtualId());
1751:                        getGuidanceManager().saveGuidance(pageDefGuidance);
1752:                        definition.setGuidanceId(pageDefGuidance.getId());
1753:
1754:                        definition.setGuidance(pageDefGuidance);
1755:                    }
1756:
1757:                    if (definition.getStyleId() != null
1758:                            && definition.getStyleId().getValue() != null
1759:                            && definition.getStyleId().getValue().length() > 0) {
1760:                        Style pageDefStyle = (Style) styleMap.get(definition
1761:                                .getStyleId().getValue());
1762:
1763:                        if (pageDefStyle == null)
1764:                            throw new NullPointerException(
1765:                                    "Style for Wizard Page was not found");
1766:
1767:                        getStyleManager().storeStyle(pageDefStyle, false);
1768:                        definition.setStyle(pageDefStyle);
1769:                    }
1770:                }
1771:                for (Iterator i = cat.getChildCategories().iterator(); i
1772:                        .hasNext();) {
1773:                    WizardCategory childCat = (WizardCategory) i.next();
1774:
1775:                    replaceCatIds(childCat, guidanceMap, formsMap, styleMap);
1776:                }
1777:            }
1778:
1779:            public String packageForDownload(Map params, OutputStream out)
1780:                    throws IOException {
1781:
1782:                String[] formIdObj = (String[]) params
1783:                        .get(DOWNLOAD_WIZARD_ID_PARAM);
1784:                packageWizardForExport(formIdObj[0], out);
1785:
1786:                //Blank filename for now -- no more dangerous, since the request is in the form of a filename
1787:                return "";
1788:            }
1789:
1790:            protected void packageWizardForExport(String wizardId,
1791:                    OutputStream os, int checkAuthz) throws IOException {
1792:                if (checkAuthz == WIZARD_EXPORT_CHECK)
1793:                    getAuthorizationFacade().checkPermission(
1794:                            WizardFunctionConstants.EXPORT_WIZARD,
1795:                            idManager.getId(ToolManager.getCurrentPlacement()
1796:                                    .getContext()));
1797:
1798:                CheckedOutputStream checksum = new CheckedOutputStream(os,
1799:                        new Adler32());
1800:
1801:                ZipOutputStream zos = new ZipOutputStream(
1802:                        new BufferedOutputStream(checksum));
1803:                try {
1804:                    putWizardIntoZip(wizardId, zos, checkAuthz);
1805:                } catch (ServerOverloadException soe) {
1806:                    logger.warn(soe);
1807:                }
1808:
1809:                zos.finish();
1810:                zos.flush();
1811:            }
1812:
1813:            public void packageWizardForExport(String wizardId, OutputStream os)
1814:                    throws IOException {
1815:                packageWizardForExport(wizardId, os, WIZARD_EXPORT_CHECK);
1816:            }
1817:
1818:            /**
1819:             * Puts the wizard definition xml into the zip, then places all the forms
1820:             * into the stream, then
1821:             * @param wizardId String the wizard to export
1822:             * @param zos ZipOutputStream the place to export the wizard too
1823:             * @throws IOException
1824:             * @throws ServerOverloadException
1825:             */
1826:            public void putWizardIntoZip(String wizardId, ZipOutputStream zos)
1827:                    throws IOException, ServerOverloadException {
1828:                putWizardIntoZip(wizardId, zos, WIZARD_EXPORT_CHECK);
1829:            }
1830:
1831:            protected void putWizardIntoZip(String wizardId,
1832:                    ZipOutputStream zos, int checkAuthz) throws IOException,
1833:                    ServerOverloadException {
1834:
1835:                Map exportForms = new HashMap(); /* key: form id   value: not needed */
1836:                Map exportFiles = new HashMap(); /* key: uuid   value: ContentResource  */
1837:                List exportGuidanceIds = new ArrayList(); /* List of guidance id */
1838:                Set exportStyleIds = new HashSet(); /* Set of style id */
1839:
1840:                Wizard wiz = getWizard(wizardId, checkAuthz);
1841:                Document document = new Document(wizardToXML(wiz, exportForms,
1842:                        exportFiles, exportGuidanceIds, exportStyleIds));
1843:                ZipEntry newfileEntry = null;
1844:
1845:                storeStringInZip(zos, (new XMLOutputter())
1846:                        .outputString(document), "wizardDefinition.xml");
1847:
1848:                // Allow access to the various files for export
1849:                getSecurityService().pushAdvisor(new AllowAllSecurityAdvisor());
1850:
1851:                // put the forms into the zip
1852:                for (Iterator i = exportForms.keySet().iterator(); i.hasNext();) {
1853:                    String id = (String) i.next();
1854:
1855:                    if (id != null && id.length() > 0) {
1856:                        newfileEntry = new ZipEntry("forms/" + id + ".form");
1857:
1858:                        zos.putNextEntry(newfileEntry);
1859:                        // Put the file into the zip entry without permissions
1860:                        structuredArtifactDefinitionManager
1861:                                .packageFormForExport(id, zos, false);
1862:                        zos.closeEntry();
1863:                    }
1864:                }
1865:
1866:                // put the resources into the zip
1867:                for (Iterator i = exportFiles.keySet().iterator(); i.hasNext();) {
1868:                    String id = (String) i.next();
1869:
1870:                    if (id != null && id.length() > 0) {
1871:                        ContentResource resource = (ContentResource) exportFiles
1872:                                .get(id);
1873:                        storeFileInZip(zos, resource.streamContent(),
1874:                                exportPathFromResource(resource, id));
1875:                    }
1876:                }
1877:
1878:                // put the guidance into the stream
1879:                //  Guidance doesn't have permissions but the attached files could
1880:                if (exportGuidanceIds.size() > 0) {
1881:                    newfileEntry = new ZipEntry("guidance/guidanceList");
1882:                    zos.putNextEntry(newfileEntry);
1883:                    getGuidanceManager().packageGuidanceForExport(
1884:                            exportGuidanceIds, zos);
1885:                    zos.closeEntry();
1886:                }
1887:                // put the guidance into the stream
1888:                // Style doesn't have permissions but attached files could
1889:                if (exportStyleIds.size() > 0) {
1890:                    newfileEntry = new ZipEntry("style/styleList");
1891:                    zos.putNextEntry(newfileEntry);
1892:                    getStyleManager()
1893:                            .packageStyleForExport(exportStyleIds, zos);
1894:                    zos.closeEntry();
1895:                }
1896:
1897:                exportForms.clear();
1898:                exportFiles.clear();
1899:                exportGuidanceIds.clear();
1900:                exportStyleIds.clear();
1901:            }
1902:
1903:            private String exportPathFromResource(ContentResource resource,
1904:                    String id) {
1905:                String fileName = resource.getProperties().getProperty(
1906:                        resource.getProperties().getNamePropDisplayName());
1907:                return resource.getContentType() + "/" + id + "/"
1908:                        + fileName.substring(fileName.lastIndexOf('\\') + 1);
1909:            }
1910:
1911:            private Element wizardToXML(Wizard wiz, Map exportForms,
1912:                    Map exportFiles, List exportGuidanceIds, Set exportStyleIds) {
1913:                Element rootNode = new Element("ospiWizard");
1914:
1915:                if (wiz == null)
1916:                    return rootNode;
1917:
1918:                rootNode.setAttribute("formatVersion", "2.1");
1919:
1920:                Element attrNode = new Element("name");
1921:                attrNode.addContent(new CDATA(wiz.getName()));
1922:                rootNode.addContent(attrNode);
1923:
1924:                attrNode = new Element("description");
1925:                attrNode.addContent(new CDATA(wiz.getDescription()));
1926:                rootNode.addContent(attrNode);
1927:
1928:                attrNode = new Element("keywords");
1929:                attrNode.addContent(new CDATA(wiz.getKeywords()));
1930:                rootNode.addContent(attrNode);
1931:
1932:                attrNode = new Element("type");
1933:                attrNode.addContent(new CDATA(wiz.getType()));
1934:                rootNode.addContent(attrNode);
1935:
1936:                attrNode = new Element("sequence");
1937:                attrNode.addContent(new CDATA(wiz.getSequence() + ""));
1938:                rootNode.addContent(attrNode);
1939:
1940:                //   put the wizard evaluators into the xml
1941:                Element evaluatorsNode = new Element("evaluators");
1942:                Collection evaluators = getWizardEvaluators(wiz.getId(), true);
1943:                for (Iterator i = evaluators.iterator(); i.hasNext();) {
1944:                    Agent agent = (Agent) i.next();
1945:                    attrNode = new Element("evaluator");
1946:                    attrNode.setAttribute("isRole", Boolean.toString(agent
1947:                            .isRole()));
1948:                    attrNode.addContent(new CDATA(agent.getId().getValue()));
1949:                    evaluatorsNode.addContent(attrNode);
1950:                }
1951:                rootNode.addContent(evaluatorsNode);
1952:
1953:                // put the evaluation, review, reflection
1954:                rootNode.addContent(putWorkflowObjectToXml(wiz, exportForms));
1955:
1956:                //   add the wizard guidance to the list
1957:                attrNode = new Element("guidance");
1958:                if (wiz.getGuidanceId() != null
1959:                        && !wiz.getGuidanceId().getValue().equals("")) {
1960:                    exportGuidanceIds.add(wiz.getGuidanceId().getValue());
1961:                    attrNode.addContent(new CDATA(wiz.getGuidanceId()
1962:                            .getValue()));
1963:                }
1964:                rootNode.addContent(attrNode);
1965:
1966:                //   put the categories/pages into the xml
1967:                rootNode.addContent(putCategoryToXml(wiz.getRootCategory(),
1968:                        exportForms, exportGuidanceIds, exportStyleIds));
1969:
1970:                //  add the wizard style to the list
1971:                attrNode = new Element("style");
1972:                if (wiz.getStyle() != null) {
1973:                    exportStyleIds.add(wiz.getStyle().getId().getValue());
1974:                    attrNode.addContent(new CDATA(wiz.getStyle().getId()
1975:                            .getValue()));
1976:                }
1977:                rootNode.addContent(attrNode);
1978:
1979:                /*
1980:                //   put the styles into the xml
1981:                
1982:                //for(Iterator i = wiz.getStyle().iterator(); i.hasNext(); ) {
1983:                    Style style = wiz.getStyle();
1984:                    String          resId = style.getStyleFile().getValue();
1985:                    String nodeId = getContentHosting().resolveUuid(resId);
1986:
1987:                   //Element       styleNode = new Element("style");
1988:                    //attrNode.addContent(new CDATA(nodeId));
1989:                    attrNode.addContent(new CDATA(style.getId().getValue()));
1990:                   //attrNode.addContent(styleNode);
1991:
1992:                  //String id = getContentHosting().resolveUuid(nodeId);
1993:                   ContentResource resource = null;
1994:                     try {
1995:                        resource = getContentHosting().getResource(nodeId);
1996:                     } catch(PermissionException pe) {
1997:                       logger.warn("Failed loading content: no permission to view file", pe);
1998:                     } catch(TypeException pe) {
1999:                       logger.warn("Wrong type", pe);
2000:                   } catch(IdUnusedException pe) {
2001:                       logger.warn("UnusedId: ", pe);
2002:                   }
2003:
2004:                   exportFiles.put(nodeId, resource);
2005:                //}
2006:                rootNode.addContent(attrNode);
2007:                 */
2008:                return rootNode;
2009:            }
2010:
2011:            private Element putCategoryToXml(WizardCategory cat,
2012:                    Map exportForms, List exportGuidanceIds, Set exportStyleIds) {
2013:                Element categoryNode = new Element("category");
2014:
2015:                if (cat == null)
2016:                    return categoryNode;
2017:
2018:                Element attrNode = new Element("title");
2019:                attrNode.addContent(new CDATA(cat.getTitle()));
2020:                categoryNode.addContent(attrNode);
2021:
2022:                attrNode = new Element("description");
2023:                attrNode.addContent(new CDATA(cat.getDescription()));
2024:                categoryNode.addContent(attrNode);
2025:
2026:                attrNode = new Element("keywords");
2027:                attrNode.addContent(new CDATA(cat.getKeywords()));
2028:                categoryNode.addContent(attrNode);
2029:
2030:                attrNode = new Element("sequence");
2031:                attrNode.addContent(new CDATA(cat.getSequence() + ""));
2032:                categoryNode.addContent(attrNode);
2033:
2034:                Element pagesNode = new Element("pages");
2035:                for (Iterator i = cat.getChildPages().iterator(); i.hasNext();) {
2036:                    WizardPageSequence pageSequence = (WizardPageSequence) i
2037:                            .next();
2038:                    pagesNode.addContent(putPageSequenceToXml(pageSequence,
2039:                            exportForms, exportGuidanceIds, exportStyleIds));
2040:                }
2041:                categoryNode.addContent(pagesNode);
2042:
2043:                Element childCategoriesNode = new Element("childCategories");
2044:                for (Iterator i = cat.getChildCategories().iterator(); i
2045:                        .hasNext();) {
2046:                    WizardCategory childCat = (WizardCategory) i.next();
2047:                    childCategoriesNode.addContent(putCategoryToXml(childCat,
2048:                            exportForms, exportGuidanceIds, exportStyleIds));
2049:                }
2050:                categoryNode.addContent(childCategoriesNode);
2051:
2052:                return categoryNode;
2053:            }
2054:
2055:            private Element putPageSequenceToXml(
2056:                    WizardPageSequence pageSequence, Map exportForms,
2057:                    List exportGuidanceIds, Set exportStyleIds) {
2058:                Element pageSequenceNode = new Element("pageSequence");
2059:
2060:                if (pageSequence == null)
2061:                    return pageSequenceNode;
2062:
2063:                Element attrNode = new Element("title");
2064:                attrNode.addContent(new CDATA(pageSequence.getTitle()));
2065:                pageSequenceNode.addContent(attrNode);
2066:
2067:                attrNode = new Element("sequence");
2068:                attrNode.addContent(new CDATA(pageSequence.getSequence() + ""));
2069:                pageSequenceNode.addContent(attrNode);
2070:
2071:                pageSequenceNode.addContent(putPageDefinitionToXml(pageSequence
2072:                        .getWizardPageDefinition(), exportForms,
2073:                        exportGuidanceIds, exportStyleIds));
2074:
2075:                return pageSequenceNode;
2076:            }
2077:
2078:            private Element putPageDefinitionToXml(
2079:                    WizardPageDefinition pageDef, Map exportForms,
2080:                    List exportGuidanceIds, Set exportStyleIds) {
2081:                Element pageDefNode = new Element("pageDef");
2082:
2083:                if (pageDef == null)
2084:                    return pageDefNode;
2085:
2086:                pageDefNode.addContent(putWorkflowObjectToXml(pageDef,
2087:                        exportForms));
2088:
2089:                Element attrNode = new Element("title");
2090:                attrNode.addContent(new CDATA(pageDef.getTitle()));
2091:                pageDefNode.addContent(attrNode);
2092:
2093:                attrNode = new Element("description");
2094:                attrNode.addContent(new CDATA(pageDef.getDescription()));
2095:                pageDefNode.addContent(attrNode);
2096:
2097:                attrNode = new Element("initialStatus");
2098:                attrNode.addContent(new CDATA(pageDef.getInitialStatus()));
2099:                pageDefNode.addContent(attrNode);
2100:
2101:                Element additionalFormsNode = new Element("additionalForms");
2102:                for (Iterator i = pageDef.getAdditionalForms().iterator(); i
2103:                        .hasNext();) {
2104:                    String additionalForm = (String) i.next();
2105:
2106:                    attrNode = new Element("form");
2107:                    attrNode.addContent(new CDATA(additionalForm));
2108:                    additionalFormsNode.addContent(attrNode);
2109:
2110:                    exportForms.put(additionalForm, new Integer(0));
2111:                }
2112:                pageDefNode.addContent(additionalFormsNode);
2113:
2114:                attrNode = new Element("guidance");
2115:                if (pageDef.getGuidance() != null
2116:                        && pageDef.getGuidance().getId() != null) {
2117:                    exportGuidanceIds.add(pageDef.getGuidance().getId()
2118:                            .getValue());
2119:                    attrNode.addContent(new CDATA(pageDef.getGuidance().getId()
2120:                            .getValue()));
2121:                }
2122:                pageDefNode.addContent(attrNode);
2123:
2124:                attrNode = new Element("style");
2125:                if (pageDef.getStyle() != null
2126:                        && pageDef.getStyle().getId() != null) {
2127:                    exportStyleIds.add(pageDef.getStyle().getId().getValue());
2128:                    attrNode.addContent(new CDATA(pageDef.getStyle().getId()
2129:                            .getValue()));
2130:                }
2131:                pageDefNode.addContent(attrNode);
2132:
2133:                Element evaluatorsNode = new Element("evaluators");
2134:                Collection evaluators = getWizardPageDefEvaluators(pageDef
2135:                        .getId(), true);
2136:                for (Iterator i = evaluators.iterator(); i.hasNext();) {
2137:                    Agent agent = (Agent) i.next();
2138:                    attrNode = new Element("evaluator");
2139:                    attrNode.setAttribute("isRole", Boolean.toString(agent
2140:                            .isRole()));
2141:                    attrNode.addContent(new CDATA(agent.getId().getValue()));
2142:                    evaluatorsNode.addContent(attrNode);
2143:                }
2144:                pageDefNode.addContent(evaluatorsNode);
2145:
2146:                return pageDefNode;
2147:            }
2148:
2149:            protected Collection getWizardPageDefEvaluators(Id wizardPageDefId,
2150:                    boolean useAgentId) {
2151:                Collection evaluators = new HashSet();
2152:                Collection viewerAuthzs = authorizationFacade
2153:                        .getAuthorizations(null,
2154:                                MatrixFunctionConstants.EVALUATE_MATRIX,
2155:                                wizardPageDefId);
2156:                for (Iterator i = viewerAuthzs.iterator(); i.hasNext();) {
2157:                    Authorization evaluator = (Authorization) i.next();
2158:                    if (useAgentId)
2159:                        evaluators.add(evaluator.getAgent());
2160:                    else
2161:                        evaluators.add(evaluator.getAgent().getId());
2162:                }
2163:                return evaluators;
2164:            }
2165:
2166:            public WizardPageSequence getWizardPageSeqByDef(Id id) {
2167:                WizardPageSequence wps = null;
2168:                Object[] params = new Object[] { id };
2169:                List seqs = getHibernateTemplate()
2170:                        .find(
2171:                                "from WizardPageSequence w where w.wizardPageDefinition.id=?",
2172:                                params);
2173:                if (seqs.size() > 0) {
2174:                    wps = (WizardPageSequence) seqs.get(0);
2175:                }
2176:
2177:                return wps;
2178:            }
2179:
2180:            public WizardPageDefinition getWizardPageDefinition(Id id) {
2181:                return getWizardPageDefinition(id, false);
2182:            }
2183:
2184:            public WizardPageDefinition getWizardPageDefinition(final Id id,
2185:                    final boolean deep) {
2186:                return (WizardPageDefinition) getHibernateTemplate().execute(
2187:                        new HibernateCallback() {
2188:                            public Object doInHibernate(Session session) {
2189:                                WizardPageDefinition def = (WizardPageDefinition) session
2190:                                        .get(WizardPageDefinition.class, id);
2191:                                if (deep) {
2192:                                    Hibernate.initialize(def.getPages());
2193:                                }
2194:                                return def;
2195:                            }
2196:                        });
2197:            }
2198:
2199:            public List getCompletedWizardPagesByPageDef(Id id) {
2200:                Object[] params = new Object[] { id };
2201:                return getHibernateTemplate()
2202:                        .find(
2203:                                "from CompletedWizardPage w where w.wizardPageDefinition.wizardPageDefinition.id=?",
2204:                                params);
2205:            }
2206:
2207:            protected Collection getWizardEvaluators(Id wizardId,
2208:                    boolean useAgentId) {
2209:                Collection evaluators = new HashSet();
2210:                Collection viewerAuthzs = authorizationFacade
2211:                        .getAuthorizations(null,
2212:                                WizardFunctionConstants.EVALUATE_WIZARD,
2213:                                wizardId);
2214:                for (Iterator i = viewerAuthzs.iterator(); i.hasNext();) {
2215:                    Authorization evaluator = (Authorization) i.next();
2216:                    if (useAgentId)
2217:                        evaluators.add(evaluator.getAgent());
2218:                    else
2219:                        evaluators.add(evaluator.getAgent().getId());
2220:                }
2221:                return evaluators;
2222:            }
2223:
2224:            /**
2225:             * 2.1 - only does type="form".
2226:             * @param objWorkflow
2227:             * @return Element
2228:             */
2229:            private Element putWorkflowObjectToXml(
2230:                    ObjectWithWorkflow objWorkflow, Map exportForms) {
2231:                Element workflowObjNode = new Element("workflow");
2232:
2233:                Element attrNode = new Element("evaluationDevice");
2234:                if (objWorkflow.getEvaluationDevice() != null)
2235:                    attrNode.addContent(new CDATA(objWorkflow
2236:                            .getEvaluationDevice().getValue()));
2237:                workflowObjNode.addContent(attrNode);
2238:
2239:                if (objWorkflow.getEvaluationDevice() != null)
2240:                    exportForms.put(objWorkflow.getEvaluationDevice()
2241:                            .getValue(), new Integer(0));
2242:
2243:                attrNode = new Element("evaluationDeviceType");
2244:                attrNode.addContent(new CDATA(objWorkflow
2245:                        .getEvaluationDeviceType()));
2246:                workflowObjNode.addContent(attrNode);
2247:
2248:                attrNode = new Element("reflectionDevice");
2249:                if (objWorkflow.getReflectionDevice() != null)
2250:                    attrNode.addContent(new CDATA(objWorkflow
2251:                            .getReflectionDevice().getValue()));
2252:                workflowObjNode.addContent(attrNode);
2253:
2254:                if (objWorkflow.getReflectionDevice() != null)
2255:                    exportForms.put(objWorkflow.getReflectionDevice()
2256:                            .getValue(), new Integer(0));
2257:
2258:                attrNode = new Element("reflectionDeviceType");
2259:                attrNode.addContent(new CDATA(objWorkflow
2260:                        .getReflectionDeviceType()));
2261:                workflowObjNode.addContent(attrNode);
2262:
2263:                attrNode = new Element("reviewDevice");
2264:                if (objWorkflow.getReviewDevice() != null)
2265:                    attrNode.addContent(new CDATA(objWorkflow.getReviewDevice()
2266:                            .getValue()));
2267:                workflowObjNode.addContent(attrNode);
2268:
2269:                if (objWorkflow.getReviewDevice() != null)
2270:                    exportForms.put(objWorkflow.getReviewDevice().getValue(),
2271:                            new Integer(0));
2272:
2273:                attrNode = new Element("reviewDeviceType");
2274:                attrNode
2275:                        .addContent(new CDATA(objWorkflow.getReviewDeviceType()));
2276:                workflowObjNode.addContent(attrNode);
2277:
2278:                return workflowObjNode;
2279:            }
2280:
2281:            protected void storeStringInZip(ZipOutputStream zos, String in,
2282:                    String entryName) throws IOException {
2283:
2284:                ZipEntry newfileEntry = new ZipEntry(entryName);
2285:
2286:                zos.putNextEntry(newfileEntry);
2287:                zos.write(in.getBytes("UTF-8"));
2288:                zos.closeEntry();
2289:            }
2290:
2291:            protected void storeFileInZip(ZipOutputStream zos, Reader in,
2292:                    String entryName) throws IOException {
2293:
2294:                char data[] = new char[1024 * 10];
2295:
2296:                if (File.separatorChar == '\\') {
2297:                    entryName = entryName.replace('\\', '/');
2298:                }
2299:
2300:                ZipEntry newfileEntry = new ZipEntry(entryName);
2301:
2302:                zos.putNextEntry(newfileEntry);
2303:
2304:                BufferedReader origin = new BufferedReader(in, data.length);
2305:                OutputStreamWriter osw = new OutputStreamWriter(zos);
2306:                int count;
2307:                while ((count = origin.read(data, 0, data.length)) != -1) {
2308:                    osw.write(data, 0, count);
2309:                }
2310:                origin.close();
2311:                osw.flush();
2312:                zos.closeEntry();
2313:                in.close();
2314:            }
2315:
2316:            protected void storeFileInZip(ZipOutputStream zos, InputStream in,
2317:                    String entryName) throws IOException {
2318:
2319:                byte data[] = new byte[1024 * 10];
2320:
2321:                if (File.separatorChar == '\\') {
2322:                    entryName = entryName.replace('\\', '/');
2323:                }
2324:
2325:                ZipEntry newfileEntry = new ZipEntry(entryName);
2326:
2327:                zos.putNextEntry(newfileEntry);
2328:
2329:                BufferedInputStream origin = new BufferedInputStream(in,
2330:                        data.length);
2331:                int count;
2332:                while ((count = origin.read(data, 0, data.length)) != -1) {
2333:                    zos.write(data, 0, count);
2334:                }
2335:                origin.close();
2336:                zos.closeEntry();
2337:                in.close();
2338:            }
2339:
2340:            private byte[] readStreamToBytes(InputStream inStream)
2341:                    throws IOException {
2342:                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
2343:                byte data[] = new byte[10 * 1024];
2344:
2345:                int count;
2346:                while ((count = inStream.read(data, 0, 10 * 1024)) != -1) {
2347:                    bytes.write(data, 0, count);
2348:                }
2349:                byte[] tmp = bytes.toByteArray();
2350:                bytes.close();
2351:                return tmp;
2352:            }
2353:
2354:            public PresentableObjectHome getXmlRenderer() {
2355:                return xmlRenderer;
2356:            }
2357:
2358:            public void setXmlRenderer(PresentableObjectHome xmlRenderer) {
2359:                this .xmlRenderer = xmlRenderer;
2360:            }
2361:
2362:            public Element getArtifactAsXml(Artifact art) {
2363:                return getXmlRenderer().getArtifactAsXml(art);
2364:            }
2365:
2366:            public Collection findByOwnerAndType(Id owner, String type) {
2367:                return findByOwner(owner);
2368:            }
2369:
2370:            public Collection findByOwnerAndType(Id owner, String type,
2371:                    MimeType mimeType) {
2372:                // TODO Auto-generated method stub
2373:                return null;
2374:            }
2375:
2376:            public Collection findByOwner(Id owner) {
2377:                return getCompletedWizards(owner.getValue());
2378:            }
2379:
2380:            public Collection findByWorksiteAndType(Id worksiteId, String type) {
2381:                // TODO Auto-generated method stub
2382:                return null;
2383:            }
2384:
2385:            public Collection findByWorksite(Id worksiteId) {
2386:                // TODO Auto-generated method stub
2387:                return null;
2388:            }
2389:
2390:            public Artifact load(Id id) {
2391:                CompletedWizard cw = this .getCompletedWizard(id);
2392:
2393:                List reflections = getReviewManager()
2394:                        .getReviewsByParentAndType(cw.getId().getValue(),
2395:                                Review.REFLECTION_TYPE,
2396:                                cw.getWizard().getSiteId(),
2397:                                WizardEntityProducer.WIZARD_PRODUCER);
2398:                List evaluations = getReviewManager()
2399:                        .getReviewsByParentAndType(cw.getId().getValue(),
2400:                                Review.EVALUATION_TYPE,
2401:                                cw.getWizard().getSiteId(),
2402:                                WizardEntityProducer.WIZARD_PRODUCER);
2403:                List feedback = getReviewManager().getReviewsByParentAndType(
2404:                        cw.getId().getValue(), Review.FEEDBACK_TYPE,
2405:                        cw.getWizard().getSiteId(),
2406:                        WizardEntityProducer.WIZARD_PRODUCER);
2407:                cw.setReflections(reflections);
2408:                cw.setEvaluations(evaluations);
2409:                cw.setFeedback(feedback);
2410:
2411:                loadWizardPageReviews(cw.getRootCategory());
2412:                //cw.get
2413:                cw.setHome(this );
2414:                return cw;
2415:            }
2416:
2417:            private void loadWizardPageReviews(CompletedWizardCategory category) {
2418:                for (Iterator pages = category.getChildPages().iterator(); pages
2419:                        .hasNext();) {
2420:                    CompletedWizardPage cPage = (CompletedWizardPage) pages
2421:                            .next();
2422:                    WizardPage page = cPage.getWizardPage();
2423:
2424:                    List reflections = getReviewManager()
2425:                            .getReviewsByParentAndType(page.getId().getValue(),
2426:                                    Review.REFLECTION_TYPE,
2427:                                    page.getPageDefinition().getSiteId(),
2428:                                    WizardEntityProducer.WIZARD_PRODUCER);
2429:                    List evaluations = getReviewManager()
2430:                            .getReviewsByParentAndType(page.getId().getValue(),
2431:                                    Review.EVALUATION_TYPE,
2432:                                    page.getPageDefinition().getSiteId(),
2433:                                    WizardEntityProducer.WIZARD_PRODUCER);
2434:                    List feedback = getReviewManager()
2435:                            .getReviewsByParentAndType(page.getId().getValue(),
2436:                                    Review.FEEDBACK_TYPE,
2437:                                    page.getPageDefinition().getSiteId(),
2438:                                    WizardEntityProducer.WIZARD_PRODUCER);
2439:                    page.setReflections(reflections);
2440:                    page.setEvaluations(evaluations);
2441:                    page.setFeedback(feedback);
2442:
2443:                    page.getAttachments().size();
2444:                    page.getPageForms().size();
2445:
2446:                    //Make sure that the attachments and forms have been added to the security advisor
2447:                    getMatrixManager().getPageContents(page);
2448:                    getMatrixManager().getPageForms(page);
2449:
2450:                }
2451:
2452:                for (Iterator i = category.getChildCategories().iterator(); i
2453:                        .hasNext();) {
2454:                    CompletedWizardCategory cat = (CompletedWizardCategory) i
2455:                            .next();
2456:                    loadWizardPageReviews(cat);
2457:                }
2458:            }
2459:
2460:            public Collection findByType(String type) {
2461:                // TODO Auto-generated method stub
2462:                return null;
2463:            }
2464:
2465:            public boolean getLoadArtifacts() {
2466:                // TODO Auto-generated method stub
2467:                return false;
2468:            }
2469:
2470:            public void setLoadArtifacts(boolean loadArtifacts) {
2471:                // TODO Auto-generated method stub
2472:
2473:            }
2474:
2475:            public Type getType() {
2476:                return new org.sakaiproject.metaobj.shared.model.Type(idManager
2477:                        .getId("completedWizard"), "Completed Wizard");
2478:            }
2479:
2480:            public String getExternalType() {
2481:                return getType().getId().getValue();
2482:            }
2483:
2484:            public Artifact createInstance() {
2485:                Artifact instance = new CompletedWizard();
2486:                prepareInstance(instance);
2487:                return instance;
2488:            }
2489:
2490:            public void prepareInstance(Artifact object) {
2491:                object.setHome(this );
2492:            }
2493:
2494:            public Artifact createSample() {
2495:                // TODO Auto-generated method stub
2496:                return null;
2497:            }
2498:
2499:            public Collection findByOwner(Agent owner) throws FinderException {
2500:                // TODO Auto-generated method stub
2501:                return null;
2502:            }
2503:
2504:            public boolean isInstance(Artifact testObject) {
2505:                // TODO Auto-generated method stub
2506:                return false;
2507:            }
2508:
2509:            public void refresh() {
2510:                // TODO Auto-generated method stub
2511:
2512:            }
2513:
2514:            public String getExternalUri(Id artifactId, String name) {
2515:                // TODO Auto-generated method stub
2516:                return null;
2517:            }
2518:
2519:            public InputStream getStream(Id artifactId) {
2520:                // TODO Auto-generated method stub
2521:                return null;
2522:            }
2523:
2524:            public boolean isSystemOnly() {
2525:                // TODO Auto-generated method stub
2526:                return false;
2527:            }
2528:
2529:            public Class getInterface() {
2530:                // TODO Auto-generated method stub
2531:                return null;
2532:            }
2533:
2534:            public ReviewManager getReviewManager() {
2535:                return reviewManager;
2536:            }
2537:
2538:            public void setReviewManager(ReviewManager reviewManager) {
2539:                this .reviewManager = reviewManager;
2540:            }
2541:
2542:            public StyleManager getStyleManager() {
2543:                return styleManager;
2544:            }
2545:
2546:            public void setStyleManager(StyleManager styleManager) {
2547:                this .styleManager = styleManager;
2548:            }
2549:
2550:            protected List getWizardsByStyle(Id styleId) {
2551:                Object[] params = new Object[] { styleId };
2552:                return getHibernateTemplate().find(
2553:                        "from Wizard w where w.style.id=? ", params);
2554:            }
2555:
2556:            public boolean checkStyleConsumption(Id styleId) {
2557:                List wizards = getWizardsByStyle(styleId);
2558:                if (wizards != null && !wizards.isEmpty() && wizards.size() > 0)
2559:                    return true;
2560:
2561:                return false;
2562:            }
2563:
2564:            public void importResources(String fromContext, String toContext,
2565:                    List resourceIds) {
2566:                try {
2567:                    List wizards = this .findPublishedWizards(fromContext);
2568:                    if (wizards == null) {
2569:                        return;
2570:                    }
2571:
2572:                    for (Iterator iter = wizards.iterator(); iter.hasNext();) {
2573:                        Wizard wizard = (Wizard) iter.next();
2574:                        Id id = wizard.getId();
2575:
2576:                        getHibernateTemplate().evict(wizard);
2577:
2578:                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
2579:                        //TODO think it's okay to not check permissions here?
2580:                        packageWizardForExport(id.getValue(), bos,
2581:                                WIZARD_NO_CHECK);
2582:                        ByteArrayInputStream bis = new ByteArrayInputStream(bos
2583:                                .toByteArray());
2584:
2585:                        importWizard(getIdManager().getId(toContext), bis);
2586:                        bos.close();
2587:                        bis.close();
2588:                    }
2589:                } catch (IOException e) {
2590:                    logger.error("", e);
2591:                    throw new OspException(e);
2592:                } catch (ImportException e) {
2593:                    logger.error("", e);
2594:                    throw new OspException(e);
2595:                }
2596:
2597:            }
2598:
2599:            public String getImportFolderName() {
2600:                return importFolderName;
2601:            }
2602:
2603:            public void setImportFolderName(String importFolderName) {
2604:                this .importFolderName = importFolderName;
2605:            }
2606:
2607:            /**
2608:             * @return the matrixManager
2609:             */
2610:            public MatrixManager getMatrixManager() {
2611:                return matrixManager;
2612:            }
2613:
2614:            /**
2615:             * @param matrixManager the matrixManager to set
2616:             */
2617:            public void setMatrixManager(MatrixManager matrixManager) {
2618:                this .matrixManager = matrixManager;
2619:            }
2620:
2621:            public LockManager getLockManager() {
2622:                return lockManager;
2623:            }
2624:
2625:            public void setLockManager(LockManager lockManager) {
2626:                this.lockManager = lockManager;
2627:            }
2628:
2629:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.