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


0001:        /**********************************************************************************
0002:         * $URL: https://source.sakaiproject.org/svn/osp/tags/sakai_2-4-1/presentation/api-impl/src/java/org/theospi/portfolio/presentation/model/impl/PresentationManagerImpl.java $
0003:         * $Id: PresentationManagerImpl.java 29136 2007-04-18 23:23:19Z ajpoland@iupui.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.presentation.model.impl;
0021:
0022:        import org.hibernate.HibernateException;
0023:        import org.hibernate.Query;
0024:        import org.hibernate.SQLQuery;
0025:        import org.hibernate.Session;
0026:        import org.jdom.CDATA;
0027:        import org.jdom.Document;
0028:        import org.jdom.Element;
0029:        import org.jdom.JDOMException;
0030:        import org.jdom.input.SAXBuilder;
0031:        import org.jdom.output.XMLOutputter;
0032:        import org.sakaiproject.authz.api.SecurityService;
0033:        import org.sakaiproject.content.api.*;
0034:        import org.sakaiproject.entity.api.Reference;
0035:        import org.sakaiproject.entity.api.ResourceProperties;
0036:        import org.sakaiproject.entity.api.ResourcePropertiesEdit;
0037:        import org.sakaiproject.event.cover.NotificationService;
0038:        import org.sakaiproject.exception.*;
0039:        import org.sakaiproject.metaobj.security.AuthenticationManager;
0040:        import org.sakaiproject.metaobj.shared.ArtifactFinder;
0041:        import org.sakaiproject.metaobj.shared.ArtifactFinderManager;
0042:        import org.sakaiproject.metaobj.shared.DownloadableManager;
0043:        import org.sakaiproject.metaobj.shared.mgt.*;
0044:        import org.sakaiproject.metaobj.shared.mgt.home.StructuredArtifactHomeInterface;
0045:        import org.sakaiproject.metaobj.shared.model.*;
0046:        import org.sakaiproject.metaobj.worksite.mgt.WorksiteManager;
0047:        import org.sakaiproject.service.legacy.resource.DuplicatableToolService;
0048:        import org.sakaiproject.site.api.Site;
0049:        import org.sakaiproject.site.cover.SiteService;
0050:        import org.sakaiproject.tool.cover.SessionManager;
0051:        import org.sakaiproject.tool.cover.ToolManager;
0052:        import org.sakaiproject.tool.api.Tool;
0053:        import org.sakaiproject.user.api.User;
0054:        import org.sakaiproject.user.cover.UserDirectoryService;
0055:        import org.springframework.orm.hibernate3.HibernateCallback;
0056:        import org.springframework.orm.hibernate3.HibernateObjectRetrievalFailureException;
0057:        import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
0058:        import org.theospi.portfolio.presentation.CommentSortBy;
0059:        import org.theospi.portfolio.presentation.PresentationFunctionConstants;
0060:        import org.theospi.portfolio.presentation.PresentationManager;
0061:        import org.theospi.portfolio.presentation.export.PresentationExport;
0062:        import org.theospi.portfolio.presentation.model.*;
0063:        import org.theospi.portfolio.security.AllowMapSecurityAdvisor;
0064:        import org.theospi.portfolio.security.Authorization;
0065:        import org.theospi.portfolio.security.AuthorizationFacade;
0066:        import org.theospi.portfolio.security.AuthorizationFailedException;
0067:        import org.theospi.portfolio.security.impl.AllowAllSecurityAdvisor;
0068:        import org.theospi.portfolio.shared.intf.EntityContextFinder;
0069:        import org.theospi.portfolio.shared.model.ItemDefinitionMimeType;
0070:        import org.theospi.portfolio.shared.model.Node;
0071:        import org.theospi.portfolio.shared.model.OspException;
0072:        import org.theospi.portfolio.style.StyleConsumer;
0073:        import org.theospi.portfolio.style.model.Style;
0074:        import org.theospi.utils.zip.UncloseableZipInputStream;
0075:
0076:        import java.io.*;
0077:        import java.sql.Connection;
0078:        import java.sql.PreparedStatement;
0079:        import java.sql.SQLException;
0080:        import java.util.*;
0081:        import java.util.zip.*;
0082:
0083:        public class PresentationManagerImpl extends HibernateDaoSupport
0084:                implements  PresentationManager, DuplicatableToolService,
0085:                DownloadableManager, StyleConsumer, FormConsumer {
0086:
0087:            private List definedLayouts;
0088:            private AgentManager agentManager;
0089:            private AuthorizationFacade authzManager = null;
0090:            private AuthenticationManager authnManager = null;
0091:            private IdManager idManager = null;
0092:            private WritableObjectHome fileHome;
0093:            private HomeFactory homeFactory = null;
0094:            private WorksiteManager worksiteManager;
0095:            private LockManager lockManager;
0096:            private ArtifactFinderManager artifactFinderManager;
0097:            private ContentHostingService contentHosting = null;
0098:            private SecurityService securityService = null;
0099:            private Map secretExportKeys = new Hashtable();
0100:            private String tempPresDownloadDir;
0101:            private StructuredArtifactDefinitionManager structuredArtifactDefinitionManager;
0102:            private List globalSites;
0103:            private List globalSiteTypes;
0104:            private List initializedServices;
0105:            private boolean autoDdl = true;
0106:            private boolean portfolioPropertyFormConversion = true;
0107:
0108:            static final private String IMPORT_BASE_FOLDER_ID = "importedPresentations";
0109:            private String importFolderName;
0110:
0111:            private static final String TEMPLATE_ID_TAG = "templateId";
0112:            private static final String PRESENTATION_ID_TAG = "presentationId";
0113:            private static final String SYSTEM_COLLECTION_ID = "/system/";
0114:
0115:            public PresentationTemplate storeTemplate(
0116:                    final PresentationTemplate template) {
0117:                return storeTemplate(template, true, true);
0118:            }
0119:
0120:            protected PresentationTemplate storeTemplate(
0121:                    final PresentationTemplate template, boolean checkAuthz) {
0122:                return storeTemplate(template, checkAuthz, true);
0123:            }
0124:
0125:            public PresentationTemplate storeTemplate(
0126:                    final PresentationTemplate template, boolean checkAuthz,
0127:                    boolean updateDates) {
0128:                if (updateDates || template.getModified() == null) {
0129:                    template.setModified(new Date(System.currentTimeMillis()));
0130:                }
0131:
0132:                boolean newTemplate = (template.getId() == null);
0133:
0134:                if (newTemplate || template.isNewObject()) {
0135:                    if (updateDates || template.getCreated() == null) {
0136:                        template
0137:                                .setCreated(new Date(System.currentTimeMillis()));
0138:                    }
0139:
0140:                    if (checkAuthz) {
0141:                        getAuthzManager().checkPermission(
0142:                                PresentationFunctionConstants.CREATE_TEMPLATE,
0143:                                getIdManager().getId(template.getSiteId()));
0144:                    }
0145:                } else {
0146:                    deleteUnusedItemDefinition(template);
0147:                    if (checkAuthz) {
0148:                        getAuthzManager().checkPermission(
0149:                                PresentationFunctionConstants.EDIT_TEMPLATE,
0150:                                template.getId());
0151:                    }
0152:                }
0153:
0154:                if (template.isNewObject() || newTemplate) {
0155:                    if (template.getId() != null) {
0156:                        template.setNewId(template.getId());
0157:                        template.setId(null);
0158:                    }
0159:                    getHibernateTemplate().save(template);
0160:                    template.setNewObject(false);
0161:                } else {
0162:                    getHibernateTemplate().merge(template);
0163:                }
0164:
0165:                lockTemplateFiles(template);
0166:
0167:                return template;
0168:            }
0169:
0170:            /**
0171:             * remove all the locks associated with this template
0172:             */
0173:            protected void clearLocks(Id id) {
0174:                getLockManager().removeAllLocks(id.getValue());
0175:            }
0176:
0177:            /**
0178:             * locks all the files associated with this template.
0179:             * @param template
0180:             */
0181:            protected void lockTemplateFiles(PresentationTemplate template) {
0182:                clearLocks(template.getId());
0183:                for (Iterator i = template.getFiles().iterator(); i.hasNext();) {
0184:                    TemplateFileRef fileRef = (TemplateFileRef) i.next();
0185:                    //getLockManager().addLock(fileRef.getFile().getId(), template.getId(), "saving a presentation template");
0186:                    getLockManager().lockObject(fileRef.getFileId(),
0187:                            template.getId().getValue(),
0188:                            "saving a presentation template", true);
0189:                }
0190:                //getLockManager().addLock(template.getRenderer(), template.getId(), "saving a presentation template");
0191:                getLockManager().lockObject(template.getRenderer().getValue(),
0192:                        template.getId().getValue(),
0193:                        "saving a presentation template", true);
0194:
0195:                if (template.getPropertyPage() != null) {
0196:                    getLockManager().lockObject(
0197:                            template.getPropertyPage().getValue(),
0198:                            template.getId().getValue(),
0199:                            "saving a presentation template", true);
0200:                }
0201:            }
0202:
0203:            public PresentationTemplate getPresentationTemplate(final Id id) {
0204:                HibernateCallback callback = new HibernateCallback() {
0205:
0206:                    public Object doInHibernate(Session session)
0207:                            throws HibernateException {
0208:                        PresentationTemplate template = (PresentationTemplate) session
0209:                                .load(PresentationTemplate.class, id);
0210:                        template.getItems().size(); //force load
0211:                        if (template.getOwner() == null) {
0212:                            reassignOwner(template);
0213:                        }
0214:
0215:                        for (Iterator i = template.getItemDefinitions()
0216:                                .iterator(); i.hasNext();) {
0217:                            PresentationItemDefinition itemDef = (PresentationItemDefinition) i
0218:                                    .next();
0219:                            //               if (itemDef.getHasMimeTypes()) {
0220:                            itemDef.getMimeTypes().size();
0221:                            //               }
0222:                        }
0223:
0224:                        return template;
0225:                    }
0226:
0227:                };
0228:
0229:                try {
0230:                    PresentationTemplate template = (PresentationTemplate) getHibernateTemplate()
0231:                            .execute(callback);
0232:                    if (template.getOwner() == null) {
0233:                        reassignOwner(template);
0234:                    }
0235:                    if (template.getPropertyPage() != null) {
0236:                        String propPage = getContentHosting().resolveUuid(
0237:                                template.getPropertyPage().getValue());
0238:                        getSecurityService()
0239:                                .pushAdvisor(
0240:                                        new AllowMapSecurityAdvisor(
0241:                                                ContentHostingService.EVENT_RESOURCE_READ,
0242:                                                getContentHosting()
0243:                                                        .getReference(propPage)));
0244:                    }
0245:                    return template;
0246:                } catch (HibernateObjectRetrievalFailureException e) {
0247:                    logger.debug(e);
0248:                    return null;
0249:                }
0250:            }
0251:
0252:            protected List getTemplatesForConversion() {
0253:
0254:                return getHibernateTemplate().findByNamedQuery(
0255:                        "findTemplatesForConversion");
0256:            }
0257:
0258:            protected List getPortfoliosForConversion() {
0259:
0260:                return getHibernateTemplate().findByNamedQuery(
0261:                        "findPortfoliosForConversion");
0262:            }
0263:
0264:            public void reassignOwner(PresentationTemplate templateId) {
0265:                templateId.setOwner(getAgentManager().getAgent("admin"));
0266:            }
0267:
0268:            public Presentation getPresentation(final Id id,
0269:                    String secretExportKey) {
0270:                Presentation pres = (Presentation) secretExportKeys
0271:                        .get(secretExportKey);
0272:                if (pres == null || !id.equals(pres.getId())) {
0273:                    throw new AuthorizationFailedException(
0274:                            "Exporting inappropriate presentation");
0275:                }
0276:
0277:                switchUser(pres.getOwner());
0278:
0279:                return getPresentation(id);
0280:            }
0281:
0282:            protected void switchUser(Agent owner) {
0283:                org.sakaiproject.tool.api.Session sakaiSession = SessionManager
0284:                        .getCurrentSession();
0285:                sakaiSession.setUserId(owner.getId().getValue());
0286:                sakaiSession.setUserEid(owner.getId().getValue());
0287:            }
0288:
0289:            public Presentation getLightweightPresentation(final Id id) {
0290:                HibernateCallback callback = new HibernateCallback() {
0291:
0292:                    public Object doInHibernate(Session session)
0293:                            throws HibernateException, SQLException {
0294:                        Presentation pres = (Presentation) session.load(
0295:                                Presentation.class, id);
0296:                        return pres;
0297:                    }
0298:
0299:                };
0300:
0301:                try {
0302:                    Presentation presentation = (Presentation) getHibernateTemplate()
0303:                            .execute(callback);
0304:
0305:                    return presentation;
0306:                } catch (HibernateObjectRetrievalFailureException e) {
0307:                    logger.debug(e);
0308:                    return null;
0309:                }
0310:            }
0311:
0312:            public Presentation getPresentation(final Id id) {
0313:
0314:                HibernateCallback callback = new HibernateCallback() {
0315:
0316:                    public Object doInHibernate(Session session)
0317:                            throws HibernateException, SQLException {
0318:                        Presentation pres = (Presentation) session.load(
0319:                                Presentation.class, id);
0320:
0321:                        viewingPresentation(pres);
0322:
0323:                        //remove any artifacts that have been removed from the repository
0324:                        for (Iterator i = pres.getPresentationItems()
0325:                                .iterator(); i.hasNext();) {
0326:                            PresentationItem item = (PresentationItem) i.next();
0327:                            ArtifactFinder artifactFinder = getArtifactFinderManager()
0328:                                    .getArtifactFinderByType(
0329:                                            item.getDefinition().getType());
0330:                            if (artifactFinder.load(item.getArtifactId()) == null) {
0331:                                deleteArtifactReference(item.getArtifactId());
0332:                            }
0333:                        }
0334:                        pres.getTemplate().getItemDefinitions().size(); //force load
0335:
0336:                        return pres;
0337:                    }
0338:
0339:                };
0340:
0341:                try {
0342:                    Presentation presentation = (Presentation) getHibernateTemplate()
0343:                            .execute(callback);
0344:
0345:                    if (!presentation.getIsPublic()
0346:                            && !presentation.getOwner().equals(
0347:                                    getAuthnManager().getAgent())) {
0348:                        getAuthzManager()
0349:                                .checkPermission(
0350:                                        PresentationFunctionConstants.VIEW_PRESENTATION,
0351:                                        presentation.getId());
0352:                    }
0353:
0354:                    Collection viewerAuthzs = getAuthzManager()
0355:                            .getAuthorizations(
0356:                                    null,
0357:                                    PresentationFunctionConstants.VIEW_PRESENTATION,
0358:                                    presentation.getId());
0359:
0360:                    for (Iterator i = viewerAuthzs.iterator(); i.hasNext();) {
0361:                        Authorization viewer = (Authorization) i.next();
0362:                        presentation.getViewers().add(viewer.getAgent());
0363:                    }
0364:                    return presentation;
0365:                } catch (HibernateObjectRetrievalFailureException e) {
0366:                    logger.debug(e);
0367:                    return null;
0368:                }
0369:            }
0370:
0371:            protected boolean artifactExists(Id artifactId) {
0372:                return (getNode(artifactId) != null);
0373:            }
0374:
0375:            public void deleteUnusedItemDefinition(PresentationTemplate template) {
0376:                Set deletedItems = template.getDeletedItems();
0377:
0378:                if (deletedItems == null) {
0379:                    return;
0380:                }
0381:
0382:                for (Iterator i = deletedItems.iterator(); i.hasNext();) {
0383:                    PresentationItemDefinition item = (PresentationItemDefinition) i
0384:                            .next();
0385:                    if (item.getId() != null) {
0386:                        deleteUnusedItemDefinition(item.getId());
0387:                    }
0388:                }
0389:            }
0390:
0391:            public void deleteUnusedItemDefinition(Id itemDefId) {
0392:                String statement = "delete from osp_presentation_item "
0393:                        + " where osp_presentation_item.item_definition_id = ?";
0394:                deleteByStatementHelper(statement, itemDefId);
0395:            }
0396:
0397:            /* 
0398:             * generic delete by Id using prepared statement helper function
0399:             * to reduce redundency.
0400:             */
0401:            private void deleteByStatementHelper(String statement, Id targetId) {
0402:                Connection connection = null;
0403:                PreparedStatement stmt = null;
0404:                Session session = getSession();
0405:                try {
0406:                    connection = session.connection();
0407:                    stmt = connection.prepareStatement(statement);
0408:                    stmt.setString(1, targetId.getValue());
0409:                    stmt.execute();
0410:                } catch (SQLException e) {
0411:                    logger.error("", e);
0412:                    throw new OspException(e);
0413:                } catch (HibernateException e) {
0414:                    logger.error("", e);
0415:                    throw new OspException(e);
0416:                } finally {
0417:                    if (stmt != null) {
0418:                        //ensure the statement is closed
0419:                        try {
0420:                            stmt.close();
0421:                        } catch (Exception e) {
0422:                            if (logger.isDebugEnabled()) {
0423:                                logger.debug(e);
0424:                            }
0425:                        }
0426:                    }
0427:                    if (connection != null) {
0428:                        //ensure the connection is closed
0429:                        //as of hibernate 3.1 we are responsible for this here
0430:                        try {
0431:                            connection.close();
0432:                        } catch (Exception e) {
0433:                            if (logger.isDebugEnabled()) {
0434:                                logger.debug(e);
0435:                            }
0436:                        }
0437:                    }
0438:                }
0439:            }
0440:
0441:            public boolean deletePresentationTemplate(final Id id) {
0442:                PresentationTemplate template = getPresentationTemplate(id);
0443:                getAuthzManager().checkPermission(
0444:                        PresentationFunctionConstants.DELETE_TEMPLATE,
0445:                        template.getId());
0446:                clearLocks(template.getId());
0447:
0448:                // first delete all presentations that use this template
0449:                // this will delete all authorization as well
0450:                Collection presentations = getHibernateTemplate()
0451:                        .findByNamedQuery("findPortfolioByTemplate",
0452:                                id.getValue());
0453:                //Query q = getHibernateTemplate().
0454:                for (Iterator i = presentations.iterator(); i.hasNext();) {
0455:                    //Presentation presentation = (Presentation) i.next();
0456:                    //deletePresentation(presentation.getId(), false);
0457:
0458:                    //Don't think we want to just delete presentations.
0459:                    // Let's return false instead.
0460:                    return false;
0461:                }
0462:
0463:                HibernateCallback callback = new HibernateCallback() {
0464:
0465:                    public Object doInHibernate(Session session)
0466:                            throws HibernateException, SQLException {
0467:                        PresentationTemplate template = (PresentationTemplate) session
0468:                                .load(PresentationTemplate.class, id);
0469:
0470:                        session.delete(template);
0471:
0472:                        return null;
0473:                    }
0474:
0475:                };
0476:                getHibernateTemplate().execute(callback);
0477:                return true;
0478:
0479:            }
0480:
0481:            protected void deleteViewers(Id presId) {
0482:                Collection authzs = getAuthzManager()
0483:                        .getAuthorizations(
0484:                                null,
0485:                                PresentationFunctionConstants.VIEW_PRESENTATION,
0486:                                presId);
0487:
0488:                for (Iterator i = authzs.iterator(); i.hasNext();) {
0489:                    Authorization authz = (Authorization) i.next();
0490:                    getAuthzManager().deleteAuthorization(authz.getAgent(),
0491:                            authz.getFunction(), authz.getQualifier());
0492:                }
0493:            }
0494:
0495:            public void deletePresentation(final Id id) {
0496:                deletePresentation(id, true);
0497:            }
0498:
0499:            public void deletePresentation(final Id id, boolean checkAuthz) {
0500:                if (checkAuthz) {
0501:                    getAuthzManager().checkPermission(
0502:                            PresentationFunctionConstants.DELETE_PRESENTATION,
0503:                            id);
0504:                }
0505:
0506:                HibernateCallback callback = new HibernateCallback() {
0507:                    public Object doInHibernate(Session session)
0508:                            throws HibernateException, SQLException {
0509:                        Presentation presentation = (Presentation) session
0510:                                .load(Presentation.class, id);
0511:
0512:                        if (presentation.getPropertyForm() != null) {
0513:                            deleteResource(presentation.getId(), presentation
0514:                                    .getPropertyForm());
0515:                        }
0516:
0517:                        // delete viewer authz
0518:                        deleteViewers(id);
0519:
0520:                        deleteComments(id);
0521:                        deleteLogs(id);
0522:                        deletePresentationPages(id);
0523:                        session.delete(presentation);
0524:                        return null;
0525:                    }
0526:                };
0527:
0528:                getHibernateTemplate().execute(callback);
0529:            }
0530:
0531:            protected void deleteLogs(final Id presentationId)
0532:                    throws HibernateException {
0533:                //session.delete("from PresentationLog where presentation_id=?",
0534:                //   presentation.getId().getValue(), Hibernate.STRING);
0535:                HibernateCallback callback = new HibernateCallback() {
0536:                    public Object doInHibernate(Session session)
0537:                            throws HibernateException, SQLException {
0538:
0539:                        Query q = session
0540:                                .createQuery("from PresentationLog where presentation_id=?");
0541:                        q.setString(0, presentationId.getValue());
0542:                        return q.list();
0543:                    }
0544:                };
0545:                List logs = (List) getHibernateTemplate().execute(callback);
0546:                getHibernateTemplate().deleteAll(logs);
0547:            }
0548:
0549:            protected void deleteComments(final Id presentationId)
0550:                    throws HibernateException {
0551:                //session.delete("from PresentationComment where presentation_id=?",
0552:                //   presentation.getId().getValue(), Hibernate.STRING);
0553:
0554:                HibernateCallback callback = new HibernateCallback() {
0555:                    public Object doInHibernate(Session session)
0556:                            throws HibernateException, SQLException {
0557:
0558:                        Query q = session
0559:                                .createQuery("from PresentationComment where presentation_id=?");
0560:                        q.setString(0, presentationId.getValue());
0561:                        return q.list();
0562:                    }
0563:                };
0564:                List comments = (List) getHibernateTemplate().execute(callback);
0565:                getHibernateTemplate().deleteAll(comments);
0566:            }
0567:
0568:            protected void deletePresentationPages(final Id presentationId)
0569:                    throws HibernateException {
0570:                //session.delete("from PresentationPage where presentation_id=?",
0571:                //      presentation.getId().getValue(), Hibernate.STRING);
0572:
0573:                HibernateCallback callback = new HibernateCallback() {
0574:                    public Object doInHibernate(Session session)
0575:                            throws HibernateException, SQLException {
0576:                        Query q = session
0577:                                .createQuery("from PresentationPage where presentation_id=?");
0578:                        q.setString(0, presentationId.getValue());
0579:                        return q.list();
0580:                    }
0581:                };
0582:
0583:                List pages = (List) getHibernateTemplate().execute(callback);
0584:                getHibernateTemplate().deleteAll(pages);
0585:            }
0586:
0587:            public PresentationItemDefinition getPresentationItemDefinition(
0588:                    final Id id) {
0589:                HibernateCallback callback = new HibernateCallback() {
0590:
0591:                    public Object doInHibernate(Session session)
0592:                            throws HibernateException, SQLException {
0593:                        PresentationItemDefinition itemDef = (PresentationItemDefinition) session
0594:                                .load(PresentationItemDefinition.class, id);
0595:                        itemDef.getMimeTypes().size(); //force load
0596:                        return itemDef;
0597:                    }
0598:
0599:                };
0600:
0601:                try {
0602:                    return (PresentationItemDefinition) getHibernateTemplate()
0603:                            .execute(callback);
0604:                } catch (HibernateObjectRetrievalFailureException e) {
0605:                    logger.debug(e);
0606:                    return null;
0607:                }
0608:            }
0609:
0610:            public void deletePresentationItemDefinition(Id id) {
0611:                PresentationItemDefinition item = getPresentationItemDefinition(id);
0612:                if (item == null) {
0613:                    return;
0614:                }
0615:                getHibernateTemplate().delete(item);
0616:            }
0617:
0618:            public PresentationItem getPresentationItem(Id id) {
0619:                try {
0620:                    return (PresentationItem) getHibernateTemplate().load(
0621:                            PresentationItem.class, id);
0622:                } catch (HibernateObjectRetrievalFailureException e) {
0623:                    logger.error("", e);
0624:                    throw new OspException(e);
0625:                }
0626:            }
0627:
0628:            public void updateItemDefintion(PresentationItemDefinition itemDef) {
0629:                getHibernateTemplate().saveOrUpdate(itemDef);
0630:            }
0631:
0632:            public void deletePresentationItem(Id id) {
0633:                PresentationItem item = getPresentationItem(id);
0634:                if (item == null) {
0635:                    return;
0636:                }
0637:                getHibernateTemplate().delete(item);
0638:            }
0639:
0640:            /**
0641:             * saves or updates a presentation and any associated presentention_items.
0642:             * This method does not persist the viewer list, for that use addViewer(), or deleteViewer()
0643:             *
0644:             * @param presentation
0645:             * @return
0646:             */
0647:            public Presentation storePresentation(Presentation presentation,
0648:                    boolean checkAuthz, boolean updateDates) {
0649:                if (updateDates || presentation.getModified() == null) {
0650:                    presentation.setModified(new Date(System
0651:                            .currentTimeMillis()));
0652:                }
0653:
0654:                if (presentation.getSiteId() == null
0655:                        || presentation.getSiteId().equals("")) {
0656:                    presentation.setSiteId(ToolManager.getCurrentPlacement()
0657:                            .getContext());
0658:                }
0659:
0660:                setupPresItemDefinition(presentation);
0661:
0662:                if (presentation.getOwner() == null) {
0663:                    presentation.setOwner(getAuthnManager().getAgent());
0664:                }
0665:
0666:                if (presentation.isNewObject()) {
0667:                    if (updateDates || presentation.getCreated() == null) {
0668:                        presentation.setCreated(new Date(System
0669:                                .currentTimeMillis()));
0670:                    }
0671:
0672:                    if (checkAuthz) {
0673:                        getAuthzManager()
0674:                                .checkPermission(
0675:                                        PresentationFunctionConstants.CREATE_PRESENTATION,
0676:                                        getIdManager().getId(
0677:                                                ToolManager
0678:                                                        .getCurrentPlacement()
0679:                                                        .getId()));
0680:                    }
0681:                    //getHibernateTemplate().save(presentation, presentation.getId());
0682:
0683:                    if (presentation.getId() != null) {
0684:                        presentation.setNewId(presentation.getId());
0685:                        presentation.setId(null);
0686:                    }
0687:                    getHibernateTemplate().save(presentation);
0688:                } else {
0689:                    if (checkAuthz) {
0690:                        getAuthzManager()
0691:                                .checkPermission(
0692:                                        PresentationFunctionConstants.EDIT_PRESENTATION,
0693:                                        presentation.getId());
0694:                    }
0695:                    getHibernateTemplate().merge(presentation);
0696:                }
0697:
0698:                //locking the prop form prohibits editing...this is bad!
0699:                //if (presentation.getPropertyForm() != null) {
0700:                //   getLockManager().lockObject(presentation.getPropertyForm().getValue(), 
0701:                //         presentation.getId().getValue(),
0702:                //         "Locking property form for this portfolio", true);
0703:                //}
0704:
0705:                storePresentationPages(presentation.getPages(), presentation
0706:                        .getId());
0707:
0708:                return presentation;
0709:            }
0710:
0711:            public Presentation storePresentation(Presentation presentation) {
0712:                return storePresentation(presentation, true, true);
0713:            }
0714:
0715:            protected void setupPresItemDefinition(Presentation presentation) {
0716:                if (presentation.getPresentationType().equals(
0717:                        Presentation.FREEFORM_TYPE)) {
0718:                    PresentationTemplate template = getPresentationTemplate(Presentation.FREEFORM_TEMPLATE_ID);
0719:                    presentation.setTemplate(template);
0720:                    PresentationItemDefinition itemDef = (PresentationItemDefinition) template
0721:                            .getItemDefinitions().iterator().next();
0722:                    for (Iterator i = presentation.getItems().iterator(); i
0723:                            .hasNext();) {
0724:                        PresentationItem item = (PresentationItem) i.next();
0725:                        item.setDefinition(itemDef);
0726:                    }
0727:                }
0728:            }
0729:
0730:            protected void storePresentationPages(List pages, Id presentationId) {
0731:                if (pages == null) {
0732:                    return;
0733:                }
0734:
0735:                for (Iterator i = pages.iterator(); i.hasNext();) {
0736:                    PresentationPage page = (PresentationPage) i.next();
0737:                    page.setModified(new Date(System.currentTimeMillis()));
0738:                    fixupRegions(page);
0739:                    if (page.isNewObject()) {
0740:                        page.setCreated(new Date(System.currentTimeMillis()));
0741:                        //getHibernateTemplate().save(page, page.getId());
0742:                        //TODO changing the save to use newId instead of Id since we're setting a specific one
0743:                        page.setNewId(page.getId());
0744:                        page.setId(null);
0745:                        getHibernateTemplate().save(page);
0746:                    } else {
0747:                        getHibernateTemplate().merge(page);
0748:                    }
0749:                }
0750:
0751:                List allPages = getPresentationPagesByPresentation(presentationId);
0752:                for (Iterator i = allPages.iterator(); i.hasNext();) {
0753:                    PresentationPage page = (PresentationPage) i.next();
0754:                    if (!pages.contains(page)) {
0755:                        getHibernateTemplate().delete(page);
0756:                    }
0757:                }
0758:            }
0759:
0760:            protected void fixupRegions(PresentationPage page) {
0761:                for (Iterator i = page.getRegions().iterator(); i.hasNext();) {
0762:                    PresentationPageRegion region = (PresentationPageRegion) i
0763:                            .next();
0764:                    region.setPage(page);
0765:                }
0766:            }
0767:
0768:            public Collection findPresentationsByOwner(Agent owner) {
0769:                return getHibernateTemplate().findByNamedQuery(
0770:                        "findPortfolioByOwner", owner);
0771:            }
0772:
0773:            public Collection findPresentationsByOwner(Agent owner,
0774:                    String toolId) {
0775:                return getHibernateTemplate().findByNamedQuery(
0776:                        "findPortfolioByOwnerAndTool",
0777:                        new Object[] { owner, toolId });
0778:            }
0779:
0780:            public Collection findTemplatesByOwner(Agent owner, String siteId) {
0781:                return getHibernateTemplate().findByNamedQuery(
0782:                        "findTemplateByOwnerAndSite",
0783:                        new Object[] { owner, siteId });
0784:            }
0785:
0786:            public Collection findTemplatesByOwner(Agent owner) {
0787:                return getHibernateTemplate().findByNamedQuery(
0788:                        "findTemplateByOwner", owner);
0789:            }
0790:
0791:            public Collection findPublishedTemplates() {
0792:                return getHibernateTemplate().findByNamedQuery(
0793:                        "findPublishedTemplates",
0794:                        new Object[] { new Boolean(true),
0795:                                getAuthnManager().getAgent() });
0796:            }
0797:
0798:            public Collection findPublishedTemplates(String siteId) {
0799:                return getHibernateTemplate().findByNamedQuery(
0800:                        "findPublishedTemplatesBySite",
0801:                        new Object[] { new Boolean(true),
0802:                                getAuthnManager().getAgent(), siteId });
0803:            }
0804:
0805:            public Collection findGlobalTemplates() {
0806:                String query = "from PresentationTemplate where published=? and owner_id!=? and site_id in (";
0807:
0808:                for (Iterator i = getGlobalSites().iterator(); i.hasNext();) {
0809:                    String site = (String) i.next();
0810:                    query += "'" + site + "'";
0811:                    query += ",";
0812:                }
0813:
0814:                query += "'') Order by name";
0815:                return getHibernateTemplate()
0816:                        .find(
0817:                                query,
0818:                                new Object[] {
0819:                                        new Boolean(true),
0820:                                        getAuthnManager().getAgent().getId()
0821:                                                .getValue() });
0822:            }
0823:
0824:            protected Collection findPublishedTemplatesBySite(String siteId) {
0825:                return getHibernateTemplate().findByNamedQuery(
0826:                        "findAllPublishedTemplatesBySite",
0827:                        new Object[] { new Boolean(true), siteId });
0828:            }
0829:
0830:            public Collection findPresentationsByViewer(Agent viewer) {
0831:
0832:                Collection presentationAuthzs = getAuthzManager()
0833:                        .getAuthorizations(
0834:                                viewer,
0835:                                PresentationFunctionConstants.VIEW_PRESENTATION,
0836:                                null);
0837:
0838:                Collection returned = new ArrayList(
0839:                        findPresentationsByOwner(viewer));
0840:
0841:                for (Iterator i = returned.iterator(); i.hasNext();) {
0842:                    getHibernateTemplate().evict(i.next());
0843:                }
0844:
0845:                for (Iterator i = presentationAuthzs.iterator(); i.hasNext();) {
0846:                    Id presId = ((Authorization) i.next()).getQualifier();
0847:                    Presentation pres = getLightweightPresentation(presId);
0848:
0849:                    if (!returned.contains(pres) && !pres.isExpired()
0850:                            && (pres.getOwner() != null)) {
0851:                        getHibernateTemplate().evict(pres);
0852:                        returned.add(pres);
0853:                    } else {
0854:                        getHibernateTemplate().evict(pres);
0855:                    }
0856:                }
0857:
0858:                return returned;
0859:            }
0860:
0861:            /**
0862:             * {@inheritDoc}
0863:             */
0864:            public Collection findPresentationsByViewer(Agent viewer,
0865:                    String toolId) {
0866:                return findPresentationsByViewer(viewer, toolId, true);
0867:            }
0868:
0869:            /**
0870:             * {@inheritDoc}
0871:             */
0872:            public Collection findPresentationsByViewer(Agent viewer,
0873:                    String toolId, boolean showHidden) {
0874:
0875:                Collection presentationAuthzs = getAuthzManager()
0876:                        .getAuthorizations(
0877:                                viewer,
0878:                                PresentationFunctionConstants.VIEW_PRESENTATION,
0879:                                null);
0880:
0881:                Collection hiddenAuths = getAuthzManager().getAuthorizations(
0882:                        viewer,
0883:                        PresentationFunctionConstants.HIDE_PRESENTATION, null);
0884:
0885:                Collection returned = findPresentationsByOwner(viewer, toolId);
0886:
0887:                for (Iterator i = returned.iterator(); i.hasNext();) {
0888:                    Presentation pres = (Presentation) i.next();
0889:                    pres.setAuthz(new PresentationAuthzMap(viewer, pres));
0890:                }
0891:
0892:                List<Id> hiddenIds = new ArrayList<Id>();
0893:                hiddenIds.add(getIdManager().getId("last"));
0894:                if (!showHidden) {
0895:                    hiddenIds = buildPresList(hiddenAuths);
0896:                }
0897:
0898:                String[] paramNames = new String[] { "toolId", "id", "hiddenId" };
0899:                Object[] params = new Object[] { toolId,
0900:                        buildPresList(presentationAuthzs), hiddenIds };
0901:
0902:                Collection authzPres = getHibernateTemplate()
0903:                        .findByNamedQueryAndNamedParam(
0904:                                "findPortfoliosByToolWithAuthzNoHidden",
0905:                                paramNames, params);
0906:
0907:                for (Iterator i = authzPres.iterator(); i.hasNext();) {
0908:                    Presentation pres = (Presentation) i.next();
0909:
0910:                    if (!returned.contains(pres) && !pres.isExpired()
0911:                            && (pres.getOwner() != null)) {
0912:                        pres.setAuthz(new PresentationAuthzMap(viewer, pres));
0913:                        returned.add(pres);
0914:                    } else {
0915:                        getHibernateTemplate().evict(pres);
0916:                    }
0917:                }
0918:
0919:                //Remove the regular ones that are hidden
0920:                for (Iterator j = returned.iterator(); j.hasNext();) {
0921:                    Presentation pres = (Presentation) j.next();
0922:                    if (hiddenIds.contains(pres.getId())) {
0923:                        j.remove();
0924:                    }
0925:                }
0926:
0927:                return returned;
0928:            }
0929:
0930:            protected List<Id> buildPresList(Collection presentationAuthzs) {
0931:                List<Id> presIdList = new ArrayList<Id>();
0932:
0933:                for (Iterator i = presentationAuthzs.iterator(); i.hasNext();) {
0934:                    Authorization authz = (Authorization) i.next();
0935:                    presIdList.add(authz.getQualifier());
0936:                }
0937:
0938:                //hibernate seems to be unhappy when the list is empty.
0939:                presIdList.add(getIdManager().getId("last"));
0940:
0941:                return presIdList;
0942:            }
0943:
0944:            public void createComment(PresentationComment comment) {
0945:                createComment(comment, true, true);
0946:            }
0947:
0948:            public void createComment(PresentationComment comment,
0949:                    boolean checkAuthz, boolean updateDates) {
0950:                if (checkAuthz) {
0951:                    getAuthzManager().checkPermission(
0952:                            PresentationFunctionConstants.COMMENT_PRESENTATION,
0953:                            comment.getPresentationId());
0954:                }
0955:
0956:                if (updateDates || comment.getCreated() == null) {
0957:                    comment.setCreated(new Date(System.currentTimeMillis()));
0958:                }
0959:
0960:                if (comment.getCreator() == null) {
0961:                    comment.setCreator(getAuthnManager().getAgent());
0962:                }
0963:
0964:                getHibernateTemplate().save(comment);
0965:            }
0966:
0967:            public List getPresentationComments(Id presentationId, Agent viewer) {
0968:                Session session = getSession();
0969:
0970:                SQLQuery query = session
0971:                        .createSQLQuery("SELECT {osp_presentation_comment.*} "
0972:                                + " FROM osp_presentation_comment {osp_presentation_comment}, osp_presentation p "
0973:                                + " WHERE {osp_presentation_comment}.presentation_id = p.id and p.id = :presentationId and"
0974:                                + " (visibility = "
0975:                                + PresentationComment.VISABILITY_PUBLIC
0976:                                + " or "
0977:                                + "   (visibility = "
0978:                                + PresentationComment.VISABILITY_SHARED
0979:                                + " and "
0980:                                + "    p.owner_id = :viewerId) or "
0981:                                + " creator_id = :viewerId)"
0982:                                + " ORDER BY {osp_presentation_comment}.created");
0983:
0984:                query.addEntity("osp_presentation_comment",
0985:                        PresentationComment.class);
0986:                query.setString("presentationId", presentationId.getValue());
0987:                query.setString("viewerId", viewer.getId().getValue());
0988:
0989:                try {
0990:                    return query.list();
0991:                } catch (HibernateException e) {
0992:                    logger.error("", e);
0993:                    throw new OspException(e);
0994:                } finally {
0995:                    /*
0996:                    try {
0997:                        session.close();
0998:                    } catch (HibernateException e) {
0999:                       logger.error("",e);
1000:                    }
1001:                     */
1002:                }
1003:            }
1004:
1005:            public PresentationComment getPresentationComment(Id id) {
1006:                try {
1007:                    return (PresentationComment) getHibernateTemplate().load(
1008:                            PresentationComment.class, id);
1009:                } catch (HibernateObjectRetrievalFailureException e) {
1010:                    logger.error("", e);
1011:                    throw new OspException(e);
1012:                }
1013:            }
1014:
1015:            public void deletePresentationComment(PresentationComment comment) {
1016:                getHibernateTemplate().delete(comment);
1017:            }
1018:
1019:            public void updatePresentationComment(PresentationComment comment) {
1020:                getHibernateTemplate().saveOrUpdate(comment);
1021:            }
1022:
1023:            public List getOwnerComments(Agent owner, CommentSortBy sortBy) {
1024:                return getOwnerComments(owner, sortBy, false);
1025:            }
1026:
1027:            public List getOwnerComments(Agent owner, CommentSortBy sortBy,
1028:                    boolean excludeOwner) {
1029:                String orderBy = sortBy.getSortByColumn();
1030:
1031:                if (orderBy.startsWith("owner_id")
1032:                        || orderBy.startsWith("name")) {
1033:                    orderBy = "p." + orderBy;
1034:                } else {
1035:                    orderBy = "{osp_presentation_comment}." + orderBy;
1036:                }
1037:
1038:                Session session = getSession();
1039:
1040:                String includeOwnerCondition = "";
1041:                if (!excludeOwner) {
1042:                    includeOwnerCondition = " or creator_id = :ownerId ) ";
1043:                } else {
1044:                    includeOwnerCondition = " ) and ( creator_id != :ownerId )";
1045:                }
1046:
1047:                SQLQuery query = session
1048:                        .createSQLQuery("SELECT {osp_presentation_comment.*} "
1049:                                + " FROM osp_presentation_comment {osp_presentation_comment}, osp_presentation p "
1050:                                + " WHERE {osp_presentation_comment}.presentation_id = p.id and "
1051:                                + " (visibility = "
1052:                                + PresentationComment.VISABILITY_PUBLIC
1053:                                + " or " + "  visibility = "
1054:                                + PresentationComment.VISABILITY_SHARED
1055:                                + includeOwnerCondition + " and "
1056:                                + "  p.owner_id = :ownerId " + " ORDER BY "
1057:                                + orderBy + " " + sortBy.getDirection());
1058:
1059:                query.addEntity("osp_presentation_comment",
1060:                        PresentationComment.class);
1061:                query.setString("ownerId", owner.getId().getValue());
1062:
1063:                try {
1064:                    return query.list();
1065:                } catch (HibernateException e) {
1066:                    logger.error("", e);
1067:                    throw new OspException(e);
1068:                } finally {
1069:                    /*
1070:                    try {
1071:                       // session.close();
1072:                    } catch (HibernateException e) {
1073:                       logger.error("",e);
1074:                    }
1075:                     */
1076:                }
1077:            }
1078:
1079:            public List getOwnerComments(Agent owner, String toolId,
1080:                    CommentSortBy sortBy) {
1081:                return getOwnerComments(owner, toolId, sortBy, false);
1082:            }
1083:
1084:            public List getOwnerComments(Agent owner, String toolId,
1085:                    CommentSortBy sortBy, boolean excludeOwner) {
1086:                String orderBy = sortBy.getSortByColumn();
1087:
1088:                if (orderBy.startsWith("owner_id")
1089:                        || orderBy.startsWith("name")) {
1090:                    orderBy = "p." + orderBy;
1091:                } else {
1092:                    orderBy = "{osp_presentation_comment}." + orderBy;
1093:                }
1094:
1095:                Session session = getSession();
1096:                String includeOwnerCondition = "";
1097:                if (!excludeOwner) {
1098:                    includeOwnerCondition = " or creator_id = :ownerId ) ";
1099:                } else {
1100:                    includeOwnerCondition = " ) and ( creator_id != :ownerId )";
1101:                }
1102:
1103:                SQLQuery query = session
1104:                        .createSQLQuery("SELECT {osp_presentation_comment.*} "
1105:                                + " FROM osp_presentation_comment {osp_presentation_comment}, osp_presentation p "
1106:                                + " WHERE {osp_presentation_comment}.presentation_id = p.id and "
1107:                                + " p.tool_id = :toolId and "
1108:                                + " (visibility = "
1109:                                + PresentationComment.VISABILITY_PUBLIC
1110:                                + " or " + "  visibility = "
1111:                                + PresentationComment.VISABILITY_SHARED
1112:                                + includeOwnerCondition + " and "
1113:                                + "  p.owner_id = :ownerId " + " ORDER BY "
1114:                                + orderBy + " " + sortBy.getDirection());
1115:
1116:                query.addEntity("osp_presentation_comment",
1117:                        PresentationComment.class);
1118:                query.setString("toolId", toolId);
1119:                query.setString("ownerId", owner.getId().getValue());
1120:
1121:                try {
1122:                    return query.list();
1123:                } catch (HibernateException e) {
1124:                    logger.error("", e);
1125:                    throw new OspException(e);
1126:                } /* finally {
1127:                        try {
1128:                           // session.close();
1129:                        } catch (HibernateException e) {
1130:                           logger.error("",e);
1131:                        }
1132:                     }        */
1133:            }
1134:
1135:            public List getCreatorComments(Agent creator, CommentSortBy sortBy) {
1136:                String orderBy = sortBy.getSortByColumn();
1137:
1138:                if (orderBy.startsWith("owner_id")
1139:                        || orderBy.startsWith("name")) {
1140:                    orderBy = "p." + orderBy;
1141:                } else {
1142:                    orderBy = "{osp_presentation_comment}." + orderBy;
1143:                }
1144:
1145:                String queryString = "SELECT {osp_presentation_comment.*} "
1146:                        + " FROM osp_presentation_comment {osp_presentation_comment}, osp_presentation p "
1147:                        + " WHERE {osp_presentation_comment}.presentation_id = p.id and "
1148:                        + " creator_id = :creatorId" + " ORDER BY " + orderBy
1149:                        + " " + sortBy.getDirection();
1150:
1151:                Session session = getSession();
1152:
1153:                SQLQuery query = session.createSQLQuery(queryString);
1154:
1155:                query.addEntity("osp_presentation_comment",
1156:                        PresentationComment.class);
1157:                query.setString("creatorId", creator.getId().getValue());
1158:
1159:                try {
1160:                    return query.list();
1161:                } catch (HibernateException e) {
1162:                    logger.error("", e);
1163:                    throw new OspException(e);
1164:                } /* finally {
1165:                        try {
1166:                           // session.close();
1167:                        } catch (HibernateException e) {
1168:                           logger.error("",e);
1169:                        }
1170:                     }    */
1171:            }
1172:
1173:            public List getCreatorComments(Agent creator, String toolId,
1174:                    CommentSortBy sortBy) {
1175:                String orderBy = sortBy.getSortByColumn();
1176:
1177:                if (orderBy.startsWith("owner_id")
1178:                        || orderBy.startsWith("name")) {
1179:                    orderBy = "p." + orderBy;
1180:                } else {
1181:                    orderBy = "{osp_presentation_comment}." + orderBy;
1182:                }
1183:
1184:                String queryString = "SELECT {osp_presentation_comment.*} "
1185:                        + " FROM osp_presentation_comment {osp_presentation_comment}, osp_presentation p "
1186:                        + " WHERE {osp_presentation_comment}.presentation_id = p.id and "
1187:                        + " tool_id = :toolId and" + " creator_id = :creatorId"
1188:                        + " ORDER BY " + orderBy + " " + sortBy.getDirection();
1189:
1190:                Session session = getSession();
1191:
1192:                SQLQuery query = session.createSQLQuery(queryString);
1193:
1194:                query.addEntity("osp_presentation_comment",
1195:                        PresentationComment.class);
1196:                query.setString("toolId", toolId);
1197:                query.setString("creatorId", creator.getId().getValue());
1198:
1199:                try {
1200:                    return query.list();
1201:                } catch (HibernateException e) {
1202:                    logger.error("", e);
1203:                    throw new OspException(e);
1204:                } /* finally {
1205:                        try {
1206:                           // session.close();
1207:                        } catch (HibernateException e) {
1208:                           logger.error("",e);
1209:                        }
1210:                     }  */
1211:            }
1212:
1213:            public boolean isGlobal() {
1214:                String siteId = getWorksiteManager().getCurrentWorksiteId()
1215:                        .getValue();
1216:
1217:                if (getGlobalSites().contains(siteId)) {
1218:                    return true;
1219:                }
1220:
1221:                Site site = getWorksiteManager().getSite(siteId);
1222:                if (site.getType() != null
1223:                        && getGlobalSiteTypes().contains(site.getType())) {
1224:                    return true;
1225:                }
1226:
1227:                return false;
1228:            }
1229:
1230:            public AgentManager getAgentManager() {
1231:                return agentManager;
1232:            }
1233:
1234:            public void setAgentManager(AgentManager agentManager) {
1235:                this .agentManager = agentManager;
1236:            }
1237:
1238:            public AuthorizationFacade getAuthzManager() {
1239:                return authzManager;
1240:            }
1241:
1242:            public void setAuthzManager(AuthorizationFacade authzManager) {
1243:                this .authzManager = authzManager;
1244:            }
1245:
1246:            public Collection getPresentationItems(Id artifactId) {
1247:                Session session = getSession();
1248:
1249:                SQLQuery query = session
1250:                        .createSQLQuery("SELECT {osp_presentation.*} "
1251:                                + " FROM osp_presentation {osp_presentation}, osp_presentation_item pi "
1252:                                + " WHERE {osp_presentation}.id = pi.presentation_id and pi.artifact_id = :artifactId");
1253:
1254:                query.addEntity("osp_presentation", Presentation.class);
1255:                query.setString("artifactId", artifactId.getValue());
1256:
1257:                try {
1258:                    return query.list();
1259:                } catch (HibernateException e) {
1260:                    logger.error("", e);
1261:                    throw new OspException(e);
1262:                } /* finally {
1263:                        try {
1264:                           // session.close();
1265:                        } catch (HibernateException e) {
1266:                           logger.error("",e);
1267:                        }
1268:                     }    */
1269:            }
1270:
1271:            public Collection getPresentationsBasedOnTemplateFileRef(
1272:                    Id artifactId) {
1273:                Session session = getSession();
1274:
1275:                try {
1276:                    SQLQuery query = session
1277:                            .createSQLQuery("SELECT {osp_presentation.*} "
1278:                                    + " FROM osp_presentation {osp_presentation}, osp_template_file_ref tfr"
1279:                                    + " WHERE {osp_presentation}.template_id = tfr.template_id and tfr.file_id = :artifactId");
1280:
1281:                    query.addEntity("osp_presentation", Presentation.class);
1282:                    query.setString("artifactId", artifactId.getValue());
1283:
1284:                    Collection tfr = query.list();
1285:                    query = session
1286:                            .createSQLQuery("SELECT {osp_presentation.*} "
1287:                                    + " FROM osp_presentation {osp_presentation}, osp_presentation_template templ "
1288:                                    + " WHERE {osp_presentation}.template_id = templ.id and (templ.renderer = :artifactId "
1289:                                    + "       or templ.propertyPage = :artifactId)");
1290:
1291:                    query.addEntity("osp_presentation", Presentation.class);
1292:                    query.setString("artifactId", artifactId.getValue());
1293:                    tfr.addAll(query.list());
1294:                    return tfr;
1295:                } catch (HibernateException e) {
1296:                    logger.error("", e);
1297:                    throw new OspException(e);
1298:                } /* finally {
1299:                        try {
1300:                           // session.close();
1301:                        } catch (HibernateException e) {
1302:                           logger.error("",e);
1303:                        }
1304:                     }    */
1305:            }
1306:
1307:            public Collection findPresentationsByTool(Id id) {
1308:                return getHibernateTemplate().find(
1309:                        "from Presentation where tool_id=?", id.getValue());
1310:            }
1311:
1312:            public void deleteArtifactReference(Id artifactId) {
1313:                String statement = "delete from osp_presentation_item where artifact_id = ?";
1314:                deleteByStatementHelper(statement, artifactId);
1315:            }
1316:
1317:            public PresentationTemplate copyTemplate(Id templateId) {
1318:                return copyTemplate(templateId, ToolManager
1319:                        .getCurrentPlacement().getContext(), true, true);
1320:            }
1321:
1322:            public String packageTemplateForExport(Id templateId,
1323:                    OutputStream os) throws IOException {
1324:                getAuthzManager().checkPermission(
1325:                        PresentationFunctionConstants.EXPORT_TEMPLATE,
1326:                        templateId);
1327:                return packageTemplateForExportInternal(templateId, os);
1328:            }
1329:
1330:            protected String packageTemplateForExportInternal(Id templateId,
1331:                    OutputStream os) throws IOException {
1332:                PresentationTemplate oldTemplate = this 
1333:                        .getPresentationTemplate(templateId);
1334:
1335:                String filename = oldTemplate.getName() + ".zip";
1336:
1337:                Set items = oldTemplate.getItems();
1338:                Set files = oldTemplate.getFiles();
1339:
1340:                CheckedOutputStream checksum = new CheckedOutputStream(os,
1341:                        new Adler32());
1342:                ZipOutputStream zos = new ZipOutputStream(
1343:                        new BufferedOutputStream(checksum));
1344:
1345:                List existingEntries = new ArrayList();
1346:                storeTemplateFile(zos, oldTemplate.getRenderer(),
1347:                        existingEntries);
1348:                storeTemplateFile(zos, oldTemplate.getPropertyPage(),
1349:                        existingEntries);
1350:
1351:                Collection exportedFormIds = new ArrayList();
1352:
1353:                if (oldTemplate.getPropertyFormType() != null) {
1354:                    ReadableObjectHome propFormHome = (ReadableObjectHome) getHomeFactory()
1355:                            .getHome(
1356:                                    oldTemplate.getPropertyFormType()
1357:                                            .getValue());
1358:
1359:                    if (propFormHome instanceof  StructuredArtifactHomeInterface
1360:                            && !exportedFormIds.contains(propFormHome.getType()
1361:                                    .getId().getValue())) {
1362:                        // need to store the form
1363:                        storeFormInZip(zos, propFormHome);
1364:                        exportedFormIds.add(propFormHome.getType().getId()
1365:                                .getValue());
1366:                    }
1367:                }
1368:
1369:                // go through each associated file... store them...
1370:                if (files != null) {
1371:                    for (Iterator i = files.iterator(); i.hasNext();) {
1372:                        TemplateFileRef fileRef = (TemplateFileRef) i.next();
1373:                        storeTemplateFile(zos, getIdManager().getId(
1374:                                fileRef.getFileId()), existingEntries);
1375:                    }
1376:                    oldTemplate.setFiles(new HashSet(files));
1377:                }
1378:
1379:                if (items != null) {
1380:                    oldTemplate.setItems(new HashSet(items));
1381:                    for (Iterator i = oldTemplate.getItems().iterator(); i
1382:                            .hasNext();) {
1383:                        PresentationItemDefinition item = (PresentationItemDefinition) i
1384:                                .next();
1385:
1386:                        ReadableObjectHome home = (ReadableObjectHome) getHomeFactory()
1387:                                .getHome(item.getType());
1388:
1389:                        if (home != null) {
1390:                            item.setExternalType(home.getExternalType());
1391:                        }
1392:
1393:                        if (home instanceof  StructuredArtifactHomeInterface
1394:                                && !exportedFormIds.contains(home.getType()
1395:                                        .getId().getValue())) {
1396:                            // need to store the form
1397:                            storeFormInZip(zos, home);
1398:                            exportedFormIds.add(home.getType().getId()
1399:                                    .getValue());
1400:                        }
1401:
1402:                        if (item.getMimeTypes() != null) {
1403:                            item.setMimeTypes(new HashSet(item.getMimeTypes()));
1404:                        }
1405:                    }
1406:                }
1407:
1408:                ByteArrayOutputStream bos = new ByteArrayOutputStream();
1409:                ObjectOutputStream oos = new ObjectOutputStream(bos);
1410:                oos.writeObject(oldTemplate);
1411:
1412:                storeFileInZip(zos,
1413:                        new ByteArrayInputStream(bos.toByteArray()), "template");
1414:
1415:                oldTemplate.setFiles(files);
1416:                oldTemplate.setItems(items);
1417:
1418:                bos.close();
1419:
1420:                zos.finish();
1421:                zos.flush();
1422:
1423:                return filename;
1424:            }
1425:
1426:            protected void storeFormInZip(ZipOutputStream zos,
1427:                    ReadableObjectHome home) throws IOException {
1428:
1429:                ZipEntry newfileEntry = new ZipEntry("forms/"
1430:                        + home.getType().getId().getValue() + ".form");
1431:
1432:                zos.putNextEntry(newfileEntry);
1433:
1434:                getStructuredArtifactDefinitionManager().packageFormForExport(
1435:                        home.getType().getId().getValue(), zos, false);
1436:
1437:                zos.closeEntry();
1438:            }
1439:
1440:            public PresentationTemplate uploadTemplate(String templateFileName,
1441:                    String toContext, InputStream zipFileStream)
1442:                    throws IOException {
1443:                try {
1444:                    return uploadTemplate(templateFileName, toContext,
1445:                            zipFileStream, true);
1446:                } catch (InvalidUploadException exp) {
1447:                    throw exp;
1448:                } catch (Exception exp) {
1449:                    throw new InvalidUploadException("Invalid template file.",
1450:                            exp, "uploadedTemplate");
1451:                }
1452:            }
1453:
1454:            protected PresentationTemplate uploadTemplate(
1455:                    String templateFileName, String toContext,
1456:                    InputStream zipFileStream, boolean checkAuthz)
1457:                    throws IOException {
1458:
1459:                if (checkAuthz) {
1460:                    getAuthzManager().checkPermission(
1461:                            PresentationFunctionConstants.CREATE_TEMPLATE,
1462:                            getIdManager().getId(toContext));
1463:                }
1464:
1465:                ZipInputStream zis = new UncloseableZipInputStream(
1466:                        zipFileStream);
1467:
1468:                ZipEntry currentEntry = zis.getNextEntry();
1469:                Hashtable<Id, Id> fileMap = new Hashtable<Id, Id>();
1470:                Hashtable<String, String> formMap = new Hashtable<String, String>();
1471:                PresentationTemplate template = null;
1472:
1473:                String tempDirName = getIdManager().createId().getValue();
1474:
1475:                boolean itWorked = false;
1476:
1477:                try {
1478:                    ContentCollectionEdit fileParent = getTemplateFileDir(tempDirName);
1479:                    boolean gotFile = false;
1480:
1481:                    while (currentEntry != null) {
1482:                        logger.debug("current entry name: "
1483:                                + currentEntry.getName());
1484:
1485:                        if (currentEntry.getName().equals("template")) {
1486:                            try {
1487:                                template = processTemplate(zis);
1488:                            } catch (ClassNotFoundException e) {
1489:                                logger.error(
1490:                                        "Class not found loading template", e);
1491:                                throw new OspException(e);
1492:                            }
1493:                        } else if (!currentEntry.isDirectory()) {
1494:                            if (currentEntry.getName().startsWith("forms/")) {
1495:                                processTemplateForm(currentEntry, zis, formMap,
1496:                                        getIdManager().getId(toContext));
1497:                            } else {
1498:                                gotFile = true;
1499:                                processTemplateFile(currentEntry, zis, fileMap,
1500:                                        fileParent);
1501:                            }
1502:                        }
1503:
1504:                        zis.closeEntry();
1505:                        currentEntry = zis.getNextEntry();
1506:                    }
1507:
1508:                    if (template == null) {
1509:                        throw new InvalidUploadException(
1510:                                "Template zip must contain template definition",
1511:                                "uploadedTemplate");
1512:                    }
1513:
1514:                    if (gotFile) {
1515:                        fileParent.getPropertiesEdit().addProperty(
1516:                                ResourceProperties.PROP_DISPLAY_NAME,
1517:                                template.getName());
1518:                        getContentHosting().commitCollection(fileParent);
1519:                    } else {
1520:                        getContentHosting().cancelCollection(fileParent);
1521:                    }
1522:
1523:                    template.setId(null);
1524:                    template.setOwner(getAuthnManager().getAgent());
1525:                    template.setRenderer((Id) fileMap.get(template
1526:                            .getRenderer()));
1527:
1528:                    if (template.getPropertyFormType() != null)
1529:                        template.setPropertyFormType(getIdManager().getId(
1530:                                (String) formMap.get(template
1531:                                        .getPropertyFormType().getValue())));
1532:
1533:                    //template.setToolId(toolConfiguration.getId());
1534:                    template.setSiteId(toContext);
1535:                    template.setPublished(false);
1536:
1537:                    if (template.getPropertyPage() != null) {
1538:                        template.setPropertyPage((Id) fileMap.get(template
1539:                                .getPropertyPage()));
1540:                    }
1541:
1542:                    for (Iterator i = template.getFiles().iterator(); i
1543:                            .hasNext();) {
1544:                        TemplateFileRef ref = (TemplateFileRef) i.next();
1545:                        Id refFileId = getIdManager().getId(ref.getFileId());
1546:                        ref.setFileId(((Id) fileMap.get(refFileId)).getValue());
1547:                        ref.setPresentationTemplate(template);
1548:                    }
1549:
1550:                    int index = 100;
1551:                    for (Iterator i = template.getItems().iterator(); i
1552:                            .hasNext();) {
1553:                        PresentationItemDefinition item = (PresentationItemDefinition) i
1554:                                .next();
1555:
1556:                        if (item.getSequence() == 0) {
1557:                            item.setSequence(index);
1558:                        }
1559:                        index++;
1560:
1561:                        if (formMap.containsKey(item.getType())) {
1562:                            item.setType((String) formMap.get(item.getType()));
1563:                        }
1564:
1565:                        item.setId(null);
1566:                        item.setNewId(idManager.createId());
1567:                        item.setPresentationTemplate(template);
1568:                    }
1569:                    template.orderItemDefs();
1570:
1571:                    substituteIds(fileMap);
1572:
1573:                    storeTemplate(template, checkAuthz);
1574:                    //TODO: 20050810 ContentHosting
1575:                    //fileParent.persistent().rename(getUniqueTemplateName(fileParent, template.getName()));
1576:                    itWorked = true;
1577:                    return template;
1578:                } catch (Exception exp) {
1579:                    throw new RuntimeException(exp);
1580:                } finally {
1581:                    //if (!itWorked) {
1582:                    //   fileParent.persistent().destroy();
1583:                    //}
1584:
1585:                    try {
1586:                        zis.closeEntry();
1587:                    } catch (IOException e) {
1588:                        logger.error("", e);
1589:                    }
1590:                }
1591:            }
1592:
1593:            // TODO: 20050810 ContentHosting
1594:            /*
1595:            protected String getUniqueTemplateName(Node currentNode, String name) {
1596:               Node parent = currentNode.getParent();
1597:               String newName = name;
1598:               int count = 1;
1599:
1600:               while (parent.hasChild(newName)) {
1601:                  count++;
1602:                  newName = name + "_" + count;
1603:               }
1604:
1605:               return newName;
1606:            }
1607:             */
1608:            protected void processTemplateForm(ZipEntry currentEntry,
1609:                    ZipInputStream zis, Map formMap, Id worksite)
1610:                    throws IOException {
1611:                File file = new File(currentEntry.getName());
1612:                String fileName = file.getName();
1613:                String oldId = fileName.substring(0, fileName.indexOf(".form"));
1614:
1615:                StructuredArtifactDefinitionBean bean;
1616:                try {
1617:                    //we want the bean even if it exists already
1618:                    bean = getStructuredArtifactDefinitionManager().importSad(
1619:                            worksite, zis, true, false, false);
1620:                } catch (ImportException ie) {
1621:                    throw new RuntimeException(
1622:                            "the structured artifact failed to import", ie);
1623:                }
1624:
1625:                formMap.put(oldId, bean.getId().getValue());
1626:            }
1627:
1628:            protected void processTemplateFile(ZipEntry currentEntry,
1629:                    ZipInputStream zis, Hashtable fileMap,
1630:                    ContentCollection fileParent) throws IOException {
1631:
1632:                File file = new File(currentEntry.getName());
1633:
1634:                MimeType mimeType = new MimeType(file.getParentFile()
1635:                        .getParentFile().getParentFile().getName(), file
1636:                        .getParentFile().getParentFile().getName());
1637:
1638:                String contentType = mimeType.getValue();
1639:
1640:                Id oldId = getIdManager().getId(file.getParentFile().getName());
1641:
1642:                try {
1643:                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
1644:                    int c = zis.read();
1645:
1646:                    while (c != -1) {
1647:                        bos.write(c);
1648:                        c = zis.read();
1649:                    }
1650:
1651:                    String fileName = findUniqueFileName(fileParent.getId(),
1652:                            file.getName());
1653:                    ResourcePropertiesEdit resourceProperties = getContentHosting()
1654:                            .newResourceProperties();
1655:                    resourceProperties.addProperty(
1656:                            ResourceProperties.PROP_DISPLAY_NAME, fileName);
1657:                    ContentResource /*Edit*/resource;
1658:
1659:                    resource = getContentHosting().addResource(
1660:                            fileParent.getId() + fileName, contentType,
1661:                            bos.toByteArray(), resourceProperties,
1662:                            NotificationService.NOTI_NONE);
1663:                    //         ResourcePropertiesEdit resourceProperties = resource.getPropertiesEdit();
1664:                    //         resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, file.getName());
1665:                    //         resource.setContent(bos.toByteArray());
1666:                    //         resource.setContentType(contentType);
1667:                    //         getContentHosting().commitResource(resource);
1668:
1669:                    Id newId = getIdManager().getId(
1670:                            getContentHosting().getUuid(resource.getId()));
1671:                    fileMap.put(oldId, newId);
1672:                } catch (Exception exp) {
1673:                    throw new RuntimeException(exp);
1674:                }
1675:            }
1676:
1677:            protected String findUniqueFileName(String id, String name)
1678:                    throws TypeException, PermissionException {
1679:                String orig = name;
1680:                String testId = id + name;
1681:                int current = 0;
1682:                while (resourceExists(testId)) {
1683:                    current++;
1684:                    int dotPos = orig.lastIndexOf('.');
1685:                    if (dotPos == -1) {
1686:                        name = orig + current;
1687:                    } else {
1688:                        name = orig.substring(0, dotPos) + "-" + current
1689:                                + orig.substring(dotPos);
1690:                    }
1691:                    testId = id + name;
1692:                }
1693:
1694:                return name;
1695:            }
1696:
1697:            protected boolean resourceExists(String returned)
1698:                    throws TypeException, PermissionException {
1699:                try {
1700:                    return getContentHosting().getResource(returned) != null;
1701:                } catch (IdUnusedException e) {
1702:                    return false;
1703:                }
1704:            }
1705:
1706:            protected PresentationTemplate processTemplate(ZipInputStream zis)
1707:                    throws IOException, ClassNotFoundException {
1708:                ObjectInputStream oos = new ObjectInputStream(zis);
1709:
1710:                return (PresentationTemplate) oos.readObject();
1711:            }
1712:
1713:            protected void storeTemplateFile(ZipOutputStream zos, Id fileId,
1714:                    List existingEntries) throws IOException {
1715:                if (fileId == null) {
1716:                    return;
1717:                }
1718:                //TODO: Need to add file to security authorizer
1719:                Node oldNode = getNode(fileId);
1720:                String newName = oldNode.getName();
1721:                String cleanedName = newName.substring(newName
1722:                        .lastIndexOf('\\') + 1);
1723:
1724:                if (!existingEntries.contains(fileId)) {
1725:                    existingEntries.add(fileId);
1726:                    storeFileInZip(zos, oldNode.getInputStream(), oldNode
1727:                            .getMimeType().getValue()
1728:                            + File.separator
1729:                            + fileId.getValue()
1730:                            + File.separator + cleanedName);
1731:                }
1732:            }
1733:
1734:            protected void storeFileInZip(ZipOutputStream zos, InputStream in,
1735:                    String entryName) throws IOException {
1736:
1737:                byte data[] = new byte[1024 * 10];
1738:
1739:                if (File.separatorChar == '\\') {
1740:                    entryName = entryName.replace('\\', '/');
1741:                }
1742:
1743:                ZipEntry newfileEntry = new ZipEntry(entryName);
1744:
1745:                zos.putNextEntry(newfileEntry);
1746:
1747:                BufferedInputStream origin = new BufferedInputStream(in,
1748:                        data.length);
1749:
1750:                int count;
1751:                while ((count = origin.read(data, 0, data.length)) != -1) {
1752:                    zos.write(data, 0, count);
1753:                }
1754:                zos.closeEntry();
1755:                in.close();
1756:            }
1757:
1758:            protected WritableObjectHome getFileHome() {
1759:                return fileHome;
1760:            }
1761:
1762:            protected void substituteIds(Hashtable fileMap) {
1763:                // go through each file....  all text mime types, do the subst on
1764:
1765:                for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
1766:                    Node node = getNode((Id) i.next());
1767:
1768:                    if (node.getMimeType().getPrimaryType().equals("text")) {
1769:                        try {
1770:                            processFile(node, fileMap);
1771:                        } catch (IOException e) {
1772:                            logger.error("error processing file.", e);
1773:                            throw new OspException(e);
1774:                        }
1775:                    }
1776:                }
1777:
1778:            }
1779:
1780:            protected void processFile(Node node, Hashtable fileMap)
1781:                    throws IOException {
1782:                // read file into StringBuffer
1783:                InputStream is = null;
1784:                try {
1785:                    is = node.getInputStream();
1786:
1787:                    byte[] buffer = new byte[1024 * 10];
1788:
1789:                    StringBuffer sb = new StringBuffer();
1790:
1791:                    int read = is.read(buffer);
1792:
1793:                    while (read != -1) {
1794:                        sb.append(new String(buffer, 0, read));
1795:                        read = is.read(buffer);
1796:                    }
1797:
1798:                    is.close();
1799:                    is = null;
1800:
1801:                    boolean changed = false;
1802:
1803:                    // subst.
1804:                    for (Iterator i = fileMap.keySet().iterator(); i.hasNext();) {
1805:                        Id key = (Id) i.next();
1806:
1807:                        if (substituteFileId(sb, key, (Id) fileMap.get(key))) {
1808:                            changed = true;
1809:                        }
1810:                    }
1811:
1812:                    if (changed) {
1813:                        // write StringBuffer out
1814:                        ContentResourceEdit cre = (ContentResourceEdit) node
1815:                                .getResource();
1816:                        cre.setContent(sb.toString().getBytes());
1817:                        getContentHosting().commitResource(cre);
1818:                    }
1819:                } catch (OverQuotaException e) {
1820:                    // TODO Better error message here?
1821:                    logger.error("", e);
1822:                } catch (ServerOverloadException e) {
1823:                    // TODO Better error message here?
1824:                    logger.error("", e);
1825:                } finally {
1826:                    try {
1827:                        if (is != null) {
1828:                            is.close();
1829:                        }
1830:                    } catch (Exception e) {
1831:                        logger.warn("", e);
1832:                    }
1833:                }
1834:            }
1835:
1836:            protected boolean substituteFileId(StringBuffer sb, Id oldId,
1837:                    Id newId) {
1838:                int index = sb.indexOf(oldId.getValue());
1839:                boolean changed = false;
1840:                while (index != -1) {
1841:                    sb.replace(index, index + oldId.getValue().length(), newId
1842:                            .getValue());
1843:                    changed = true;
1844:                    index = sb.indexOf(oldId.getValue());
1845:                }
1846:
1847:                return changed;
1848:            }
1849:
1850:            protected void handleChildren(PresentationTemplate oldTemplate,
1851:                    ContentCollection templateParent, Hashtable fileMap) {
1852:                Set files = oldTemplate.getFiles();
1853:                oldTemplate.setFiles(new HashSet());
1854:                for (Iterator i = files.iterator(); i.hasNext();) {
1855:                    TemplateFileRef fileRef = (TemplateFileRef) i.next();
1856:
1857:                    fileRef.setId(null);
1858:                    fileRef.setFileId(copyTemplateFile(templateParent,
1859:                            getIdManager().getId(fileRef.getFileId()), fileMap)
1860:                            .getValue());
1861:                    oldTemplate.getFiles().add(fileRef);
1862:                }
1863:
1864:                Set items = oldTemplate.getItems();
1865:                oldTemplate.setItems(new HashSet());
1866:                for (Iterator i = items.iterator(); i.hasNext();) {
1867:                    PresentationItemDefinition itemDef = (PresentationItemDefinition) i
1868:                            .next();
1869:                    itemDef.setId(null);
1870:                    Set itemMimeTypes = new HashSet();
1871:
1872:                    for (Iterator j = itemDef.getMimeTypes().iterator(); j
1873:                            .hasNext();) {
1874:                        ItemDefinitionMimeType mimeType = (ItemDefinitionMimeType) j
1875:                                .next();
1876:
1877:                        itemMimeTypes.add(new ItemDefinitionMimeType(mimeType
1878:                                .getPrimary(), mimeType.getSecondary()));
1879:                    }
1880:
1881:                    itemDef.setMimeTypes(itemMimeTypes);
1882:                    oldTemplate.getItems().add(itemDef);
1883:                }
1884:            }
1885:
1886:            /**
1887:             * gets the current user's resource collection
1888:             * 
1889:             * @return ContentCollection
1890:             * @throws TypeException
1891:             * @throws IdUnusedException
1892:             * @throws PermissionException
1893:             */
1894:            protected ContentCollection getUserCollection()
1895:                    throws TypeException, IdUnusedException,
1896:                    PermissionException {
1897:                User user = UserDirectoryService.getCurrentUser();
1898:                String userId = user.getId();
1899:                String wsId = SiteService.getUserSiteId(userId);
1900:                String wsCollectionId = getContentHosting().getSiteCollection(
1901:                        wsId);
1902:                ContentCollection collection = getContentHosting()
1903:                        .getCollection(wsCollectionId);
1904:                return collection;
1905:            }
1906:
1907:            /**
1908:             * This gets the directory in which the import places files into.
1909:             * 
1910:             * This method gets the current users base collection, creates an imported directory,
1911:             * then uses the param to create a new directory.
1912:             * 
1913:             * this uses the bean property importFolderName to name the
1914:             * 
1915:             * @param origName String
1916:             * @return ContentCollectionEdit
1917:             * @throws InconsistentException
1918:             * @throws PermissionException
1919:             * @throws IdUsedException
1920:             * @throws IdInvalidException
1921:             * @throws IdUnusedException
1922:             * @throws TypeException
1923:             */
1924:            protected ContentCollectionEdit getTemplateFileDir(String origName)
1925:                    throws TypeException, IdUnusedException,
1926:                    PermissionException, IdUsedException, IdInvalidException,
1927:                    InconsistentException {
1928:                ContentCollection userCollection = getUserCollection();
1929:
1930:                try {
1931:                    //TODO use the bean org.theospi.portfolio.admin.model.IntegrationOption.siteOption 
1932:                    // in common/components to get the name and id for this site.
1933:
1934:                    ContentCollectionEdit groupCollection = getContentHosting()
1935:                            .addCollection(
1936:                                    userCollection.getId()
1937:                                            + IMPORT_BASE_FOLDER_ID);
1938:                    groupCollection.getPropertiesEdit().addProperty(
1939:                            ResourceProperties.PROP_DISPLAY_NAME,
1940:                            getImportFolderName());
1941:                    getContentHosting().commitCollection(groupCollection);
1942:                } catch (IdUsedException e) {
1943:                    // ignore... it is already there.
1944:                    if (logger.isDebugEnabled()) {
1945:                        logger.debug(e);
1946:                    }
1947:                } catch (Exception e) {
1948:                    throw new RuntimeException(e);
1949:                }
1950:
1951:                ContentCollection collection = getContentHosting()
1952:                        .getCollection(
1953:                                userCollection.getId() + IMPORT_BASE_FOLDER_ID
1954:                                        + "/");
1955:
1956:                String childId = collection.getId() + origName;
1957:                return getContentHosting().addCollection(childId);
1958:            }
1959:
1960:            protected Id copyTemplateFile(ContentCollection templateParent,
1961:                    Id oldFileId, Hashtable fileMap) {
1962:                if (oldFileId == null) {
1963:                    return null;
1964:                }
1965:
1966:                Node oldNode = (Node) getNode(oldFileId);
1967:
1968:                String newName = oldNode.getName();
1969:                //    TODO: 20050810 ContentHosting
1970:                /*
1971:                int index = 1;
1972:                while (templateParent.hasChild(newName)) {
1973:                   newName = "copy_" + index + "_" + oldNode.getName();
1974:                   index++;
1975:                }
1976:
1977:                RepositoryNode newNode = oldNode.copy(oldNode.getName(), templateParent.getId());
1978:
1979:                fileMap.put(oldFileId, newNode.getId());
1980:
1981:                return newNode.getId();
1982:                 */
1983:                return null;
1984:            }
1985:
1986:            public Document createDocument(Presentation presentation) {
1987:                // build up the document from objects...
1988:                viewingPresentation(presentation);
1989:
1990:                Collection items = presentation.getItems();
1991:
1992:                Element root = new Element("ospiPresentation");
1993:
1994:                for (Iterator i = items.iterator(); i.hasNext();) {
1995:                    PresentationItem item = (PresentationItem) i.next();
1996:                    Element itemElement = root.getChild(item.getDefinition()
1997:                            .getName());
1998:
1999:                    if (itemElement == null) {
2000:                        itemElement = new Element(item.getDefinition()
2001:                                .getName());
2002:                        root.addContent(itemElement);
2003:                    }
2004:
2005:                    Artifact art = getPresentationItem(item.getDefinition()
2006:                            .getType(), item.getArtifactId(), presentation);
2007:
2008:                    if (art != null
2009:                            && art.getHome() instanceof  PresentableObjectHome) {
2010:                        PresentableObjectHome home = (PresentableObjectHome) art
2011:                                .getHome();
2012:                        Element node = home.getArtifactAsXml(art);
2013:                        node.setName("artifact");
2014:                        itemElement.addContent(node);
2015:                    }
2016:                }
2017:
2018:                if (presentation.getProperties() != null) {
2019:                    Element presProperties = new Element(
2020:                            "deprecatedPresentationProperties");
2021:                    presProperties.addContent((Element) presentation
2022:                            .getProperties().currentElement().clone());
2023:                    root.addContent(presProperties);
2024:                }
2025:
2026:                Node propNode = getNode(presentation.getPropertyForm());
2027:                if (presentation.getPropertyForm() != null && propNode != null) {
2028:                    Element presProperties = new Element(
2029:                            "presentationProperties");
2030:
2031:                    Document doc = new Document();
2032:                    SAXBuilder saxBuilder = new SAXBuilder();
2033:                    try {
2034:                        doc = saxBuilder.build(propNode.getInputStream());
2035:                    } catch (JDOMException e) {
2036:                        throw new OspException(e);
2037:                    } catch (IOException e) {
2038:                        throw new OspException(e);
2039:                    }
2040:
2041:                    presProperties.addContent((Element) doc.getRootElement()
2042:                            .clone());
2043:                    root.addContent(presProperties);
2044:                }
2045:
2046:                if (presentation.getTemplate().getFiles() != null) {
2047:                    Element presFiles = new Element("presentationFiles");
2048:                    root.addContent(presFiles);
2049:
2050:                    for (Iterator files = presentation.getTemplate().getFiles()
2051:                            .iterator(); files.hasNext();) {
2052:                        TemplateFileRef fileRef = (TemplateFileRef) files
2053:                                .next();
2054:                        presFiles.addContent(getFileRefAsXml(presentation,
2055:                                fileRef));
2056:                    }
2057:                }
2058:
2059:                return new Document(root);
2060:            }
2061:
2062:            public Collection getAllPresentationsForWarehouse() {
2063:                Collection presentations = getHibernateTemplate()
2064:                        .findByNamedQuery("findPortfolios");
2065:                //need to load up all of the pages, since hibernate isn't linking them.
2066:                for (Iterator i = presentations.iterator(); i.hasNext();) {
2067:                    Presentation presentation = (Presentation) i.next();
2068:                    List pages = getPresentationPagesByPresentation(presentation
2069:                            .getId());
2070:                    presentation.setPages(pages);
2071:                }
2072:
2073:                return presentations;
2074:            }
2075:
2076:            public Collection getAllPresentationTemplates() {
2077:                HibernateCallback callback = new HibernateCallback() {
2078:                    public Object doInHibernate(Session session)
2079:                            throws HibernateException, SQLException {
2080:                        List templates = getHibernateTemplate()
2081:                                .findByNamedQuery("findTemplates");
2082:                        for (Iterator i = templates.iterator(); i.hasNext();) {
2083:                            PresentationTemplate template = (PresentationTemplate) i
2084:                                    .next();
2085:                            for (Iterator j = template.getItems().iterator(); j
2086:                                    .hasNext();) {
2087:                                PresentationItemDefinition itemDef = (PresentationItemDefinition) j
2088:                                        .next();
2089:                                itemDef.getMimeTypes().size();
2090:                            }
2091:                        }
2092:                        return templates;
2093:                    }
2094:                };
2095:
2096:                try {
2097:                    return (Collection) getHibernateTemplate()
2098:                            .execute(callback);
2099:                } catch (HibernateObjectRetrievalFailureException e) {
2100:                    logger.debug(e);
2101:                    return new ArrayList();
2102:                }
2103:            }
2104:
2105:            public Collection getAllPresentationLayouts() {
2106:
2107:                return getHibernateTemplate().findByNamedQuery("findLayouts");
2108:
2109:            }
2110:
2111:            public void viewingPresentation(Presentation presentation) {
2112:                // go through and setup all pres and pres template files for read access
2113:                List readableFiles = new ArrayList();
2114:                Collection artifacts = presentation.getItems();
2115:
2116:                for (Iterator i = artifacts.iterator(); i.hasNext();) {
2117:                    PresentationItem item = (PresentationItem) i.next();
2118:                    String id = getContentHosting().resolveUuid(
2119:                            item.getArtifactId().getValue());
2120:                    if (id != null) {
2121:                        readableFiles.add(getContentHosting().getReference(id));
2122:                    }
2123:                }
2124:
2125:                if (presentation.getTemplate().getFiles() != null) {
2126:
2127:                    for (Iterator files = presentation.getTemplate().getFiles()
2128:                            .iterator(); files.hasNext();) {
2129:                        TemplateFileRef fileRef = (TemplateFileRef) files
2130:                                .next();
2131:                        String id = getContentHosting().resolveUuid(
2132:                                fileRef.getFileId());
2133:                        if (id != null) {
2134:                            readableFiles.add(getContentHosting().getReference(
2135:                                    id));
2136:                        }
2137:                    }
2138:                }
2139:
2140:                String id = null;
2141:                if (presentation.getTemplate() == null
2142:                        || presentation.getTemplate().getRenderer() == null) {
2143:                    setupPresItemDefinition(presentation);
2144:                }
2145:
2146:                id = getContentHosting().resolveUuid(
2147:                        presentation.getTemplate().getRenderer().getValue());
2148:
2149:                if (id != null) {
2150:                    readableFiles.add(getContentHosting().getReference(id));
2151:                }
2152:
2153:                //Files related to layouts
2154:                List pages = null;
2155:                if (presentation.getPages() != null) {
2156:                    pages = presentation.getPages();
2157:                } else {
2158:                    pages = getPresentationPagesByPresentation(presentation
2159:                            .getId());
2160:                }
2161:                for (Iterator pagesIter = pages.iterator(); pagesIter.hasNext();) {
2162:                    PresentationPage page = (PresentationPage) pagesIter.next();
2163:                    String xhtmlFileId = getContentHosting().resolveUuid(
2164:                            page.getLayout().getXhtmlFileId().getValue());
2165:                    if (xhtmlFileId != null) {
2166:                        readableFiles.add(getContentHosting().getReference(
2167:                                xhtmlFileId));
2168:                    }
2169:                    if (page.getLayout().getPreviewImageId() != null) {
2170:                        String previewImageId = getContentHosting()
2171:                                .resolveUuid(
2172:                                        page.getLayout().getPreviewImageId()
2173:                                                .getValue());
2174:                        if (previewImageId != null) {
2175:                            readableFiles.add(getContentHosting().getReference(
2176:                                    previewImageId));
2177:                        }
2178:                    }
2179:                    Style pageStyle = page.getStyle() != null ? page.getStyle()
2180:                            : page.getPresentation().getStyle();
2181:                    if (pageStyle != null && pageStyle.getStyleFile() != null) {
2182:                        String styleFileId = getContentHosting().resolveUuid(
2183:                                pageStyle.getStyleFile().getValue());
2184:                        readableFiles.add(getContentHosting().getReference(
2185:                                styleFileId));
2186:                    }
2187:
2188:                    for (Iterator regions = page.getRegions().iterator(); regions
2189:                            .hasNext();) {
2190:                        PresentationPageRegion region = (PresentationPageRegion) regions
2191:                                .next();
2192:                        for (Iterator items = region.getItems().iterator(); items
2193:                                .hasNext();) {
2194:                            PresentationPageItem pageItem = (PresentationPageItem) items
2195:                                    .next();
2196:                            String itemId = getContentHosting().resolveUuid(
2197:                                    pageItem.getValue());
2198:                            if (itemId != null) {
2199:                                readableFiles.add(getContentHosting()
2200:                                        .getReference(itemId));
2201:                            }
2202:                        }
2203:                    }
2204:                }
2205:
2206:                getSecurityService().pushAdvisor(
2207:                        new AllowMapSecurityAdvisor(
2208:                                ContentHostingService.EVENT_RESOURCE_READ,
2209:                                readableFiles));
2210:            }
2211:
2212:            protected Element getFileRefAsXml(Presentation presentation,
2213:                    TemplateFileRef fileRef) {
2214:                Element fileRefElement = new Element(fileRef.getUsage());
2215:                String fileId = fileRef.getFileId();
2216:
2217:                Artifact art = getPresentationItem(fileRef.getFileType(),
2218:                        getIdManager().getId(fileId), presentation);
2219:
2220:                PresentableObjectHome home = (PresentableObjectHome) art
2221:                        .getHome();
2222:                fileRefElement.addContent(home.getArtifactAsXml(art));
2223:                return fileRefElement;
2224:            }
2225:
2226:            public void storePresentationLog(PresentationLog log) {
2227:                getHibernateTemplate().save(log);
2228:            }
2229:
2230:            public Collection findLogsByPresID(Id presID) {
2231:                return getHibernateTemplate().findByNamedQuery(
2232:                        "findLogsByPortfolio", presID.getValue());
2233:            }
2234:
2235:            public TemplateFileRef getTemplateFileRef(Id refId) {
2236:                return (TemplateFileRef) getHibernateTemplate().load(
2237:                        TemplateFileRef.class, refId);
2238:            }
2239:
2240:            public void updateTemplateFileRef(TemplateFileRef ref) {
2241:                getHibernateTemplate().saveOrUpdate(ref);
2242:            }
2243:
2244:            public void deleteTemplateFileRef(Id refId) {
2245:                getHibernateTemplate().delete(getTemplateFileRef(refId));
2246:            }
2247:
2248:            public AuthenticationManager getAuthnManager() {
2249:                return authnManager;
2250:            }
2251:
2252:            public void setAuthnManager(AuthenticationManager authnManager) {
2253:                this .authnManager = authnManager;
2254:            }
2255:
2256:            public IdManager getIdManager() {
2257:                return idManager;
2258:            }
2259:
2260:            public void setIdManager(IdManager idManager) {
2261:                this .idManager = idManager;
2262:            }
2263:
2264:            public void setFileHome(WritableObjectHome fileHome) {
2265:                this .fileHome = fileHome;
2266:            }
2267:
2268:            public HomeFactory getHomeFactory() {
2269:                return homeFactory;
2270:            }
2271:
2272:            public void setHomeFactory(HomeFactory homeFactory) {
2273:                this .homeFactory = homeFactory;
2274:            }
2275:
2276:            public WorksiteManager getWorksiteManager() {
2277:                return worksiteManager;
2278:            }
2279:
2280:            public void setWorksiteManager(WorksiteManager worksiteManager) {
2281:                this .worksiteManager = worksiteManager;
2282:            }
2283:
2284:            public LockManager getLockManager() {
2285:                return lockManager;
2286:            }
2287:
2288:            public void setLockManager(LockManager lockManager) {
2289:                this .lockManager = lockManager;
2290:            }
2291:
2292:            public ArtifactFinderManager getArtifactFinderManager() {
2293:                return artifactFinderManager;
2294:            }
2295:
2296:            public void setArtifactFinderManager(
2297:                    ArtifactFinderManager artifactFinderManager) {
2298:                this .artifactFinderManager = artifactFinderManager;
2299:            }
2300:
2301:            public void importResources(String fromContext, String toContext,
2302:                    List resourceIds) {
2303:                //Agent agent = getAuthnManager().getAgent();
2304:                //Collection templates = findTemplatesByOwner(agent, fromContext);
2305:                Collection templates = findPublishedTemplatesBySite(fromContext);
2306:
2307:                for (Iterator i = templates.iterator(); i.hasNext();) {
2308:                    PresentationTemplate template = (PresentationTemplate) i
2309:                            .next();
2310:                    copyTemplate(template.getId(), toContext, false, false);
2311:                }
2312:            }
2313:
2314:            protected PresentationTemplate copyTemplate(Id templateId,
2315:                    String toContext, boolean checkAuthz, boolean rename) {
2316:                try {
2317:                    if (checkAuthz) {
2318:                        getAuthzManager().checkPermission(
2319:                                PresentationFunctionConstants.COPY_TEMPLATE,
2320:                                templateId);
2321:                    }
2322:
2323:                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
2324:
2325:                    PresentationTemplate oldTemplate = this 
2326:                            .getPresentationTemplate(templateId);
2327:
2328:                    packageTemplateForExportInternal(templateId, bos);
2329:
2330:                    ByteArrayInputStream bis = new ByteArrayInputStream(bos
2331:                            .toByteArray());
2332:
2333:                    PresentationTemplate newTemplate = uploadTemplate(
2334:                            oldTemplate.getName() + ".zip", toContext, bis,
2335:                            false);
2336:
2337:                    if (rename) {
2338:                        newTemplate.setName(newTemplate.getName() + " Copy");
2339:                        storeTemplate(newTemplate, false);
2340:                    }
2341:                    return newTemplate;
2342:                } catch (IOException e) {
2343:                    logger.error("", e);
2344:                    throw new OspException(e);
2345:                }
2346:            }
2347:
2348:            public String packageForDownload(Map params, OutputStream out)
2349:                    throws IOException {
2350:
2351:                String filename = "";
2352:                if (params.get(TEMPLATE_ID_TAG) != null) {
2353:                    filename = packageTemplateForExport(getIdManager().getId(
2354:                            ((String[]) params.get(TEMPLATE_ID_TAG))[0]), out);
2355:                } else if (params.get(PRESENTATION_ID_TAG) != null) {
2356:                    filename = packagePresentationForExport(
2357:                            getIdManager()
2358:                                    .getId(
2359:                                            ((String[]) params
2360:                                                    .get(PRESENTATION_ID_TAG))[0]),
2361:                            out);
2362:                }
2363:                return filename;
2364:            }
2365:
2366:            protected String packagePresentationForExport(Id presentationId,
2367:                    OutputStream out) throws IOException {
2368:                Presentation presentation = getLightweightPresentation(presentationId);
2369:
2370:                String filename = presentation.getName() + ".zip";
2371:
2372:                if (!presentation.getOwner().equals(
2373:                        getAuthnManager().getAgent())) {
2374:                    throw new AuthorizationFailedException(
2375:                            "Only the presentation owner can export a presentation");
2376:                }
2377:
2378:                File tempDir = new File(tempPresDownloadDir);
2379:                if (!tempDir.exists()) {
2380:                    tempDir.mkdirs();
2381:                }
2382:
2383:                String secretExportKey = getIdManager().createId().getValue();
2384:                String url = presentation.getExternalUri()
2385:                        + "&secretExportKey=" + secretExportKey;
2386:
2387:                //This should come from the above presentation.getExternalUri() call;
2388:                //url += "&" + Tool.PLACEMENT_ID + "=" + SessionManager.getCurrentToolSession().getPlacementId();
2389:
2390:                File tempDirectory = new File(tempDir, secretExportKey);
2391:
2392:                PresentationExport export = new PresentationExport(url,
2393:                        tempDirectory.getPath());
2394:
2395:                try {
2396:                    synchronized (secretExportKeys) {
2397:                        secretExportKeys.put(secretExportKey, presentation);
2398:                    }
2399:
2400:                    export.run();
2401:
2402:                    synchronized (secretExportKeys) {
2403:                        secretExportKeys.remove(secretExportKey);
2404:                    }
2405:
2406:                    export.createZip(out);
2407:                } finally {
2408:                    export.deleteTemp();
2409:                }
2410:                return filename;
2411:            }
2412:
2413:            public Node getNode(Id artifactId) {
2414:                if (artifactId == null) {
2415:                    return null;
2416:                }
2417:
2418:                String id = getContentHosting().resolveUuid(
2419:                        artifactId.getValue());
2420:                if (id == null) {
2421:                    return null;
2422:                }
2423:
2424:                try {
2425:                    String ref = getContentHosting().getReference(id);
2426:                    getSecurityService().pushAdvisor(
2427:                            new AllowMapSecurityAdvisor(
2428:                                    ContentHostingService.EVENT_RESOURCE_READ,
2429:                                    ref));
2430:                    ContentResource resource = getContentHosting().getResource(
2431:                            id);
2432:                    String ownerId = resource.getProperties().getProperty(
2433:                            resource.getProperties().getNamePropCreator());
2434:                    Agent owner = getAgentManager().getAgent(
2435:                            getIdManager().getId(ownerId));
2436:                    return new Node(artifactId, resource, owner);
2437:                } catch (PermissionException e) {
2438:                    logger.error("", e);
2439:                    throw new RuntimeException(e);
2440:                } catch (IdUnusedException e) {
2441:                    logger.error("", e);
2442:                    throw new RuntimeException(e);
2443:                } catch (TypeException e) {
2444:                    logger.error("", e);
2445:                    throw new RuntimeException(e);
2446:                }
2447:            }
2448:
2449:            public Node getNode(Reference ref, Presentation presentation) {
2450:                return getNode(getNode(ref), presentation);
2451:            }
2452:
2453:            public Node getNode(Id nodeId, Presentation presentation) {
2454:                Node node = getNode(nodeId);
2455:                return getNode(node, presentation);
2456:            }
2457:
2458:            public Node getNode(Id artifactId, PresentationLayout layout) {
2459:                String id = getContentHosting().resolveUuid(
2460:                        artifactId.getValue());
2461:                String ref = getContentHosting().getReference(id);
2462:                getSecurityService()
2463:                        .pushAdvisor(
2464:                                new AllowMapSecurityAdvisor(
2465:                                        ContentHostingService.EVENT_RESOURCE_READ,
2466:                                        ref));
2467:                Node node = getNode(artifactId);
2468:                return getNode(node, layout);
2469:            }
2470:
2471:            protected Node getNode(Node node, Presentation presentation) {
2472:                if (node == null) {
2473:                    return null;
2474:                }
2475:
2476:                ContentResource wrapped = new ContentEntityWrapper(node
2477:                        .getResource(), buildRef(presentation.getSiteId(),
2478:                        presentation.getId().getValue(), node.getResource()));
2479:
2480:                return new Node(node.getId(), wrapped, node
2481:                        .getTechnicalMetadata().getOwner());
2482:            }
2483:
2484:            protected Node getNode(Node node, PresentationLayout layout) {
2485:                if (node == null) {
2486:                    return null;
2487:                }
2488:                String siteId = layout.getSiteId();
2489:                if (siteId == null) {
2490:                    siteId = "~admin";
2491:                }
2492:                ContentResource wrapped = new ContentEntityWrapper(node
2493:                        .getResource(), buildLayoutRef(layout.getSiteId(),
2494:                        layout.getId().getValue(), node.getResource()));
2495:
2496:                return new Node(node.getId(), wrapped, node
2497:                        .getTechnicalMetadata().getOwner());
2498:            }
2499:
2500:            protected String buildRef(String siteId, String contextId,
2501:                    ContentResource resource) {
2502:                return ContentEntityUtil.getInstance().buildRef(
2503:                        PresentationContentEntityProducer.PRODUCER_NAME,
2504:                        siteId, contextId, resource.getReference());
2505:            }
2506:
2507:            protected String buildLayoutRef(String siteId, String contextId,
2508:                    ContentResource resource) {
2509:                return ContentEntityUtil.getInstance().buildRef(
2510:                        LayoutEntityProducer.PRODUCER_NAME, siteId, contextId,
2511:                        resource.getReference());
2512:            }
2513:
2514:            public Node getNode(Reference ref) {
2515:                String nodeId = getContentHosting().getUuid(ref.getId());
2516:
2517:                return getNode(getIdManager().getId(nodeId));
2518:            }
2519:
2520:            public Collection loadArtifactsForItemDef(
2521:                    PresentationItemDefinition itemDef, Agent agent) {
2522:                ArtifactFinder artifactFinder = getArtifactFinderManager()
2523:                        .getArtifactFinderByType(itemDef.getType());
2524:                // for performance, don't do a deep load, only load id, displayName
2525:                artifactFinder.setLoadArtifacts(false);
2526:
2527:                if (itemDef.getHasMimeTypes()) {
2528:                    Collection items = new ArrayList();
2529:                    if (itemDef.getMimeTypes().size() > 0) {
2530:                        for (Iterator i = itemDef.getMimeTypes().iterator(); i
2531:                                .hasNext();) {
2532:                            ItemDefinitionMimeType mimeType = (ItemDefinitionMimeType) i
2533:                                    .next();
2534:                            items.addAll(artifactFinder.findByOwnerAndType(
2535:                                    agent.getId(), itemDef.getType(),
2536:                                    new MimeType(mimeType.getPrimary(),
2537:                                            mimeType.getSecondary())));
2538:                        }
2539:                    } else {
2540:                        return artifactFinder.findByOwnerAndType(agent.getId(),
2541:                                itemDef.getType());
2542:                    }
2543:
2544:                    return items;
2545:                } else {
2546:                    return artifactFinder.findByOwnerAndType(agent.getId(),
2547:                            itemDef.getType());
2548:                }
2549:            }
2550:
2551:            public void cleanupTool(Id toolId) {
2552:                for (Iterator i = findPresentationsByTool(toolId).iterator(); i
2553:                        .hasNext();) {
2554:                    Presentation presentation = (Presentation) i.next();
2555:                    deletePresentation(presentation.getId());
2556:                }
2557:            }
2558:
2559:            public ContentHostingService getContentHosting() {
2560:                return contentHosting;
2561:            }
2562:
2563:            public void setContentHosting(ContentHostingService contentHosting) {
2564:                this .contentHosting = contentHosting;
2565:            }
2566:
2567:            public SecurityService getSecurityService() {
2568:                return securityService;
2569:            }
2570:
2571:            public void setSecurityService(SecurityService securityService) {
2572:                this .securityService = securityService;
2573:            }
2574:
2575:            public Collection findPublishedLayouts(String siteId) {
2576:                /*
2577:                return getHibernateTemplate().find(
2578:                      "from PresentationLayout where globalState=? and owner_id!=? and site_id=? Order by name",
2579:                      new Object[]{new Integer(PresentationLayout.STATE_PUBLISHED), 
2580:                            getAuthnManager().getAgent().getId().getValue(), siteId});
2581:                 */
2582:                return new ArrayList();
2583:            }
2584:
2585:            public Collection findLayoutsByOwner(Agent owner, String siteId) {
2586:                return getHibernateTemplate().findByNamedQuery(
2587:                        "findLayoutsByOwner", new Object[] { owner, siteId });
2588:            }
2589:
2590:            public Collection findMyGlobalLayouts() {
2591:                return getHibernateTemplate().findByNamedQuery(
2592:                        "findPublishedLayouts",
2593:                        new Object[] { new Integer(
2594:                                PresentationLayout.STATE_PUBLISHED) });
2595:            }
2596:
2597:            public Collection findAllGlobalLayouts() {
2598:                return getHibernateTemplate()
2599:                        .findByNamedQuery(
2600:                                "findGlobalLayouts",
2601:                                new Object[] {
2602:                                        new Integer(
2603:                                                PresentationLayout.STATE_PUBLISHED),
2604:                                        new Integer(
2605:                                                PresentationLayout.STATE_WAITING_APPROVAL) });
2606:            }
2607:
2608:            public PresentationLayout storeLayout(PresentationLayout layout) {
2609:                return storeLayout(layout, true);
2610:            }
2611:
2612:            public PresentationLayout storeLayout(PresentationLayout layout,
2613:                    boolean checkAuthz) {
2614:                layout.setModified(new Date(System.currentTimeMillis()));
2615:
2616:                boolean newLayout = (layout.getId() == null);
2617:
2618:                if (newLayout) {
2619:                    layout.setCreated(new Date(System.currentTimeMillis()));
2620:
2621:                    if (checkAuthz) {
2622:                        getAuthzManager().checkPermission(
2623:                                PresentationFunctionConstants.CREATE_LAYOUT,
2624:                                getIdManager().getId(layout.getSiteId()));
2625:                    }
2626:                } else {
2627:                    if (checkAuthz) {
2628:                        getAuthzManager().checkPermission(
2629:                                PresentationFunctionConstants.EDIT_LAYOUT,
2630:                                layout.getId());
2631:                    }
2632:                }
2633:                getHibernateTemplate().saveOrUpdate(layout);
2634:                lockLayoutFiles(layout);
2635:
2636:                return layout;
2637:            }
2638:
2639:            protected void lockLayoutFiles(PresentationLayout layout) {
2640:                clearLocks(layout.getId());
2641:                getLockManager().lockObject(layout.getXhtmlFileId().getValue(),
2642:                        layout.getId().getValue(),
2643:                        "saving a presentation layout", true);
2644:
2645:                if (layout.getPreviewImageId() != null) {
2646:                    getLockManager().lockObject(
2647:                            layout.getPreviewImageId().getValue(),
2648:                            layout.getId().getValue(),
2649:                            "saving a presentation layout", true);
2650:                }
2651:            }
2652:
2653:            protected void lockStyleFiles(Style style) {
2654:                clearLocks(style.getId());
2655:                getLockManager().lockObject(style.getStyleFile().getValue(),
2656:                        style.getId().getValue(), "saving a style", true);
2657:
2658:            }
2659:
2660:            public PresentationLayout getPresentationLayout(Id id) {
2661:                return (PresentationLayout) getHibernateTemplate().get(
2662:                        PresentationLayout.class, id);
2663:            }
2664:
2665:            public List getPresentationPagesByPresentation(Id presentationId) {
2666:                return getHibernateTemplate().findByNamedQuery(
2667:                        "findPortfolioPagesByPortfolio",
2668:                        new Object[] { presentationId });
2669:            }
2670:
2671:            public void deletePresentationLayout(final Id id) {
2672:                PresentationLayout layout = getPresentationLayout(id);
2673:                getAuthzManager().checkPermission(
2674:                        PresentationFunctionConstants.DELETE_LAYOUT,
2675:                        layout.getId());
2676:                clearLocks(layout.getId());
2677:
2678:                //TODO handle things that are using this layout
2679:                // first delete all presentations that use this template
2680:                // this will delete all authorization as well
2681:                //Collection presentations = getHibernateTemplate().find("from Presentation where template_id=?", id.getValue(), Hibernate.STRING);
2682:                //for (Iterator i = presentations.iterator(); i.hasNext();) {
2683:                //   Presentation presentation = (Presentation) i.next();
2684:                //   deletePresentation(presentation.getId(), false);
2685:                //}
2686:
2687:                HibernateCallback callback = new HibernateCallback() {
2688:
2689:                    public Object doInHibernate(Session session)
2690:                            throws HibernateException, SQLException {
2691:
2692:                        PresentationLayout layout = (PresentationLayout) session
2693:                                .load(PresentationLayout.class, id);
2694:                        //session.delete("from PresentationLayout where id=?", id.getValue(), Hibernate.STRING);
2695:                        //Query q = session.createQuery("from PresentationLayout where id=?");
2696:                        //q.setString(0, id.getValue());
2697:                        //q.executeUpdate();
2698:                        session.delete(layout);
2699:                        return null;
2700:                    }
2701:
2702:                };
2703:                getHibernateTemplate().execute(callback);
2704:            }
2705:
2706:            public PresentationPage getPresentationPage(Id id) {
2707:                PresentationPage page = (PresentationPage) getHibernateTemplate()
2708:                        .get(PresentationPage.class, id);
2709:
2710:                if (page != null) {
2711:                    for (Iterator i = page.getRegions().iterator(); i.hasNext();) {
2712:                        PresentationPageRegion region = (PresentationPageRegion) i
2713:                                .next();
2714:                        for (Iterator j = region.getItems().iterator(); j
2715:                                .hasNext();) {
2716:                            PresentationPageItem item = (PresentationPageItem) j
2717:                                    .next();
2718:                            item.getProperties().size();
2719:                        }
2720:                    }
2721:                }
2722:                return page;
2723:            }
2724:
2725:            public PresentationPage getFirstPresentationPage(Id presentationId) {
2726:                return getPresentationPage(presentationId, 0);
2727:            }
2728:
2729:            public PresentationPage getPresentationPage(Id presentationId,
2730:                    int pageIndex) {
2731:                List pages = getHibernateTemplate()
2732:                        .findByNamedQuery(
2733:                                "findPortfolioPagesByPortfolioAndSequence",
2734:                                new Object[] { presentationId,
2735:                                        new Integer(pageIndex) });
2736:
2737:                return (PresentationPage) pages.get(0);
2738:            }
2739:
2740:            public Document getPresentationLayoutAsXml(
2741:                    Presentation presentation, String pageId) {
2742:                viewingPresentation(presentation);
2743:                PresentationPage page;
2744:                if (pageId == null || pageId.equals("")) {
2745:                    page = getFirstPresentationPage(presentation.getId());
2746:                } else {
2747:                    page = getPresentationPage(getIdManager().getId(pageId));
2748:                }
2749:                if (page == null) {
2750:                    return null;
2751:                }
2752:                return getPresentationLayoutAsXml(page.getId());
2753:            }
2754:
2755:            /**
2756:             * Create an xml document represenation of the requested page from the 
2757:             * presentation passed in.
2758:             * 
2759:             * @param presentation
2760:             * @param pageId
2761:             * @return xml representation of the requested page or null
2762:             */
2763:            public Document getPresentationPreviewLayoutAsXml(
2764:                    Presentation presentation, String pageId) {
2765:                viewingPresentation(presentation);
2766:                PresentationPage page = null;
2767:                List pages = presentation.getPages();
2768:                if (pageId == null || pageId.equals("")) {
2769:                    page = (PresentationPage) pages.get(0);
2770:                } else {
2771:                    for (Iterator i = pages.iterator(); i.hasNext();) {
2772:                        PresentationPage iterPage = (PresentationPage) i.next();
2773:                        if (iterPage != null && iterPage.getId() != null
2774:                                && pageId.equals(iterPage.getId().toString())) {
2775:                            page = iterPage;
2776:                        }
2777:                    }
2778:                }
2779:
2780:                if (page == null) {
2781:                    return null;
2782:                }
2783:
2784:                page.setPresentation(presentation);
2785:                return getPresentationPageLayoutAsXml(page);
2786:            }
2787:
2788:            protected Document getPresentationLayoutAsXml(Id pageId) {
2789:
2790:                PresentationPage page = getPresentationPage(pageId);
2791:                return getPresentationPageLayoutAsXml(page);
2792:            }
2793:
2794:            protected Document getPresentationPageLayoutAsXml(
2795:                    PresentationPage page) {
2796:
2797:                Element root = new Element("ospiPresentation");
2798:                Element pageStyleElement = new Element("pageStyle");
2799:                Element layoutElement = new Element("layout");
2800:                Element regionsElement = new Element("regions");
2801:
2802:                Id fileId = page.getLayout().getXhtmlFileId();
2803:                Artifact art = getPresentationItem("fileArtifact", fileId, page
2804:                        .getPresentation());
2805:
2806:                PresentableObjectHome home = (PresentableObjectHome) art
2807:                        .getHome();
2808:                layoutElement.addContent(home.getArtifactAsXml(art));
2809:
2810:                Style pageStyle = page.getStyle() != null ? page.getStyle()
2811:                        : page.getPresentation().getStyle();
2812:                if (pageStyle != null && pageStyle.getStyleFile() != null) {
2813:                    Id cssFileId = pageStyle.getStyleFile();
2814:                    Artifact cssArt = getPresentationItem("fileArtifact",
2815:                            cssFileId, page.getPresentation());
2816:                    PresentableObjectHome cssHome = (PresentableObjectHome) cssArt
2817:                            .getHome();
2818:                    pageStyleElement.addContent(cssHome
2819:                            .getArtifactAsXml(cssArt));
2820:                    root.addContent(pageStyleElement);
2821:                }
2822:
2823:                for (Iterator regions = page.getRegions().iterator(); regions
2824:                        .hasNext();) {
2825:                    PresentationPageRegion region = (PresentationPageRegion) regions
2826:                            .next();
2827:                    int itemSeq = 0;
2828:                    for (Iterator items = region.getItems().iterator(); items
2829:                            .hasNext();) {
2830:                        PresentationPageItem item = (PresentationPageItem) items
2831:                                .next();
2832:                        Element regionElement = new Element("region");
2833:                        regionElement.setAttribute("id", region.getRegionId());
2834:                        if (region.getItems().size() > 1) {
2835:                            regionElement.setAttribute("sequence", String
2836:                                    .valueOf(itemSeq));
2837:                        }
2838:                        regionElement.setAttribute("type", item.getType());
2839:                        Element itemPropertiesElement = new Element(
2840:                                "itemProperties");
2841:                        String contentType = "";
2842:                        if (item.getProperties() != null) {
2843:                            for (Iterator properties = item.getProperties()
2844:                                    .iterator(); properties.hasNext();) {
2845:                                PresentationItemProperty prop = (PresentationItemProperty) properties
2846:                                        .next();
2847:                                itemPropertiesElement
2848:                                        .addContent(createElementNode(prop
2849:                                                .getKey(), prop.getValue()));
2850:                                if (prop.getKey().equals(
2851:                                        PresentationItemProperty.CONTENT_TYPE)) {
2852:                                    contentType = prop.getValue();
2853:                                }
2854:                            }
2855:                        }
2856:                        regionElement.addContent(itemPropertiesElement);
2857:                        regionElement.addContent(outputTypedContent(item
2858:                                .getType(), item.getValue(), page
2859:                                .getPresentation(), contentType));
2860:                        regionsElement.addContent(regionElement);
2861:                        itemSeq++;
2862:                    }
2863:                }
2864:
2865:                root.addContent(layoutElement);
2866:                root.addContent(createNavigationElement(page));
2867:                root.addContent(regionsElement);
2868:                return new Document(root);
2869:            }
2870:
2871:            protected Element outputTypedContent(String type, String value,
2872:                    Presentation presentation, String contentType) {
2873:                if (type.equals("text") || type.equals("richtext")) {
2874:                    Element textRegion = new Element("value");
2875:                    textRegion.addContent(new CDATA(value));
2876:                    return textRegion;
2877:                } else if (type.equals("form") || type.equals("link")
2878:                        || type.equals("inline")) {
2879:                    //String fileId = value;
2880:                    Element artifactAsXml = null;
2881:                    Id itemId = getIdManager().getId(value);
2882:                    if (!contentType.equals("page")) {
2883:                        Artifact art = getPresentationItem(contentType, itemId,
2884:                                presentation);
2885:
2886:                        PresentableObjectHome home = (PresentableObjectHome) art
2887:                                .getHome();
2888:                        artifactAsXml = home.getArtifactAsXml(art);
2889:                    } else {
2890:                        artifactAsXml = getPresentationPageAsXml(getPresentationPage(itemId));
2891:                    }
2892:                    return artifactAsXml;
2893:                }
2894:                return new Element("empty");
2895:            }
2896:
2897:            protected Artifact getPresentationItem(String type, Id itemId,
2898:                    Presentation presentation) {
2899:                ArtifactFinder finder = getArtifactFinderManager()
2900:                        .getArtifactFinderByType(type);
2901:
2902:                Artifact art;
2903:
2904:                if (finder instanceof  EntityContextFinder
2905:                        && !presentation.isPreview()) {
2906:                    art = ((EntityContextFinder) finder).loadInContext(itemId,
2907:                            PresentationContentEntityProducer.PRODUCER_NAME,
2908:                            presentation.getSiteId(), presentation.getId()
2909:                                    .getValue());
2910:                } else {
2911:                    art = finder.load(itemId);
2912:                }
2913:                return art;
2914:            }
2915:
2916:            protected Element getPresentationPageAsXml(PresentationPage page) {
2917:                Element root = new Element("artifact");
2918:
2919:                Element metadata = new Element("metaData");
2920:                metadata.addContent(createElementNode("id", page.getId()
2921:                        .getValue()));
2922:                metadata.addContent(createElementNode("displayName", page
2923:                        .getTitle()));
2924:
2925:                Element type = new Element("type");
2926:                metadata.addContent(type);
2927:
2928:                type.addContent(createElementNode("id", "page"));
2929:                type.addContent(createElementNode("description",
2930:                        "Presentation Page"));
2931:
2932:                Element fileData = new Element("fileArtifact");
2933:                Element uri = new Element("uri");
2934:                uri.addContent(page.getUrl());
2935:                fileData.addContent(uri);
2936:
2937:                root.addContent(metadata);
2938:                root.addContent(fileData);
2939:
2940:                return root;
2941:            }
2942:
2943:            protected Element createElementNode(String name, String value) {
2944:                Element newNode = new Element(name);
2945:                newNode.addContent(value);
2946:                return newNode;
2947:            }
2948:
2949:            protected Element createNavigationElement(PresentationPage page) {
2950:                int currentPage = page.getSequence();
2951:                Element navigationElement = new Element("navigation");
2952:                Element previousPage = new Element("previousPage");
2953:                Element nextPage = new Element("nextPage");
2954:
2955:                boolean isAdvancedNavigation = page.getPresentation()
2956:                        .isAdvancedNavigation();
2957:
2958:                if (isAdvancedNavigation) {
2959:                    List pages = null;
2960:                    if (page.getPresentation().isPreview()) {
2961:                        pages = page.getPresentation().getPages();
2962:                    } else {
2963:                        pages = getPresentationPagesByPresentation(page
2964:                                .getPresentation().getId());
2965:                    }
2966:                    PresentationPage lastNavPage = null;
2967:                    PresentationPage nextNavPage = null;
2968:                    boolean foundCurrent = false;
2969:
2970:                    for (Iterator i = pages.iterator(); i.hasNext();) {
2971:                        PresentationPage iterPage = (PresentationPage) i.next();
2972:                        if (iterPage.getSequence() == currentPage) {
2973:                            foundCurrent = true;
2974:                        } else if (!foundCurrent) {
2975:                            lastNavPage = iterPage;
2976:                        } else {
2977:                            nextNavPage = iterPage;
2978:                            break;
2979:                        }
2980:                    }
2981:
2982:                    if (lastNavPage != null) {
2983:                        previousPage
2984:                                .addContent(getPresentationPageAsXml(lastNavPage));
2985:                        navigationElement.addContent(previousPage);
2986:                    }
2987:                    if (nextNavPage != null) {
2988:                        nextPage
2989:                                .addContent(getPresentationPageAsXml(nextNavPage));
2990:                        navigationElement.addContent(nextPage);
2991:                    }
2992:                }
2993:                return navigationElement;
2994:            }
2995:
2996:            public String getTempPresDownloadDir() {
2997:                return tempPresDownloadDir;
2998:            }
2999:
3000:            public void setTempPresDownloadDir(String tempPresDownloadDir) {
3001:                this .tempPresDownloadDir = tempPresDownloadDir;
3002:            }
3003:
3004:            public void init() {
3005:                logger.info("init()");
3006:                if (isAutoDdl()) {
3007:                    try {
3008:                        initFreeFormTemplate();
3009:                        initGlobalLayouts();
3010:                    } catch (Exception e) {
3011:                        logger
3012:                                .warn(
3013:                                        "Temporarily catching all exceptions in osp.PresentationManagerImpl.init()",
3014:                                        e);
3015:                    }
3016:                }
3017:
3018:                if (isPortfolioPropertyFormConversion()) {
3019:                    final String convertProperty = "osp.portfolio.propertyConversion";
3020:                    String inited = System.getProperty(convertProperty);
3021:                    if (inited == null) {
3022:                        System.setProperty(convertProperty, "true");
3023:                        try {
3024:                            // do conversion for template property form types
3025:                            List templates = getTemplatesForConversion();
3026:                            logger.debug("There are " + templates.size()
3027:                                    + " templates needing conversion");
3028:                            convertPortfolioTemplates(templates);
3029:                        } catch (Exception e) {
3030:                            logger
3031:                                    .warn(
3032:                                            "Error converting portfolio template property form types",
3033:                                            e);
3034:                        }
3035:                        try {
3036:                            // do conversion for portfolio property form data
3037:                            List portfolios = getPortfoliosForConversion();
3038:                            logger.debug("There are " + portfolios.size()
3039:                                    + " portfolios needing conversion");
3040:                            convertPortfolios(portfolios);
3041:                        } catch (Exception e) {
3042:                            logger
3043:                                    .warn(
3044:                                            "Error converting portfolio property form data",
3045:                                            e);
3046:                        }
3047:                    }
3048:                }
3049:
3050:            }
3051:
3052:            protected void initGlobalLayouts() {
3053:                getSecurityService().pushAdvisor(new AllowAllSecurityAdvisor());
3054:
3055:                org.sakaiproject.tool.api.Session sakaiSession = SessionManager
3056:                        .getCurrentSession();
3057:                String userId = sakaiSession.getUserId();
3058:                sakaiSession.setUserId("admin");
3059:                sakaiSession.setUserEid("admin");
3060:                List layouts = new ArrayList();
3061:
3062:                try {
3063:                    for (Iterator i = getDefinedLayouts().iterator(); i
3064:                            .hasNext();) {
3065:                        layouts
3066:                                .add(processDefinedLayout((PresentationLayoutWrapper) i
3067:                                        .next()));
3068:                    }
3069:
3070:                    for (Iterator i = layouts.iterator(); i.hasNext();) {
3071:                        PresentationLayout layout = (PresentationLayout) i
3072:                                .next();
3073:                        getHibernateTemplate().saveOrUpdate(layout);
3074:                        lockLayoutFiles(layout);
3075:                    }
3076:
3077:                } finally {
3078:                    getSecurityService().popAdvisor();
3079:                    sakaiSession.setUserEid(userId);
3080:                    sakaiSession.setUserId(userId);
3081:                }
3082:
3083:            }
3084:
3085:            protected PresentationLayout processDefinedLayout(
3086:                    PresentationLayoutWrapper wrapper) {
3087:                PresentationLayout layout = getPresentationLayout(getIdManager()
3088:                        .getId(wrapper.getIdValue()));
3089:
3090:                if (layout == null) {
3091:                    layout = new PresentationLayout();
3092:                    layout.setCreated(new Date());
3093:                    layout.setNewId(getIdManager().getId(wrapper.getIdValue()));
3094:                }
3095:
3096:                updateLayout(wrapper, layout);
3097:                return layout;
3098:            }
3099:
3100:            protected void updateLayout(PresentationLayoutWrapper wrapper,
3101:                    PresentationLayout layout) {
3102:                if (layout.getPreviewImageId() != null) {
3103:                    deleteResource(layout.getId(), layout.getPreviewImageId());
3104:                }
3105:                if (layout.getXhtmlFileId() != null) {
3106:                    deleteResource(layout.getId(), layout.getXhtmlFileId());
3107:                }
3108:
3109:                layout.setPreviewImageId(createResource(wrapper
3110:                        .getPreviewFileLocation(),
3111:                        wrapper.getPreviewFileName(), wrapper.getIdValue()
3112:                                + " layout preview", wrapper
3113:                                .getPreviewFileType()));
3114:                layout.setXhtmlFileId(createResource(wrapper
3115:                        .getLayoutFileLocation(),
3116:                        wrapper.getIdValue() + ".xml", wrapper.getIdValue()
3117:                                + " layout file", "text/xml"));
3118:
3119:                layout.setModified(new Date());
3120:                layout.setName(wrapper.getName());
3121:                layout.setDescription(wrapper.getDescription());
3122:                layout.setGlobalState(PresentationLayout.STATE_PUBLISHED);
3123:                layout.setSiteId(null);
3124:                layout.setToolId(null);
3125:                layout.setOwner(getAgentManager().getAgent("admin"));
3126:            }
3127:
3128:            protected void deleteResource(Id qualifierId, Id resourceId) {
3129:                try {
3130:                    getContentHosting().removeAllLocks(qualifierId.getValue());
3131:                    String id = getContentHosting().resolveUuid(
3132:                            resourceId.getValue());
3133:                    if (id == null) {
3134:                        return;
3135:                    }
3136:                    getContentHosting().removeResource(id);
3137:                } catch (Exception e) {
3138:                    throw new RuntimeException(e);
3139:                }
3140:            }
3141:
3142:            protected void initFreeFormTemplate() {
3143:                getSecurityService().pushAdvisor(new AllowAllSecurityAdvisor());
3144:
3145:                org.sakaiproject.tool.api.Session sakaiSession = SessionManager
3146:                        .getCurrentSession();
3147:                String userId = sakaiSession.getUserId();
3148:                sakaiSession.setUserId("admin");
3149:                sakaiSession.setUserEid("admin");
3150:                String resourceLocation = "/org/theospi/portfolio/presentation/freeform_template.xsl";
3151:
3152:                try {
3153:                    PresentationTemplate template = getPresentationTemplate(getFreeFormTemplateId());
3154:                    if (template == null) {
3155:                        template = createFreeFormTemplate(createResource(
3156:                                resourceLocation, "freeFormRenderer",
3157:                                "used for rendering the free form template",
3158:                                "text/xml"));
3159:                    } else {
3160:                        updateResource(template.getId(),
3161:                                template.getRenderer(), resourceLocation);
3162:                        if (template.getItemDefinitions().size() == 0) {
3163:                            template.getItemDefinitions().add(
3164:                                    createFreeFormItemDef(template));
3165:                        }
3166:                    }
3167:                    storeTemplate(template, false);
3168:                } finally {
3169:                    getSecurityService().popAdvisor();
3170:                    sakaiSession.setUserEid(userId);
3171:                    sakaiSession.setUserId(userId);
3172:                }
3173:            }
3174:
3175:            protected PresentationTemplate createFreeFormTemplate(Id rendererId) {
3176:                PresentationTemplate template = new PresentationTemplate();
3177:                template.setId(getFreeFormTemplateId());
3178:                template.setNewId(getFreeFormTemplateId());
3179:                template.setName("Free Form Presentation");
3180:                template.setRenderer(rendererId);
3181:                template.setNewObject(true);
3182:                template.setSiteId(getIdManager().createId().getValue());
3183:                template.setOwner(getAgentManager().getAnonymousAgent());
3184:                template.getItemDefinitions().add(
3185:                        createFreeFormItemDef(template));
3186:                return template;
3187:            }
3188:
3189:            protected PresentationItemDefinition createFreeFormItemDef(
3190:                    PresentationTemplate template) {
3191:                PresentationItemDefinition def = new PresentationItemDefinition();
3192:                def.setPresentationTemplate(template);
3193:                def.setAllowMultiple(true);
3194:                def.setName("freeFormItem");
3195:                def.setSequence(0);
3196:                return def;
3197:            }
3198:
3199:            protected Id updateResource(Id qualifierId, Id resourceId,
3200:                    String resourceLocation) {
3201:                ByteArrayOutputStream bos = loadResource(resourceLocation);
3202:
3203:                try {
3204:                    getContentHosting().removeAllLocks(qualifierId.getValue());
3205:                    ContentResourceEdit resourceEdit = getContentHosting()
3206:                            .editResource(
3207:                                    getContentHosting().resolveUuid(
3208:                                            resourceId.getValue()));
3209:                    resourceEdit.setContent(bos.toByteArray());
3210:                    getContentHosting().commitResource(resourceEdit,
3211:                            NotificationService.NOTI_NONE);
3212:                    return resourceId;
3213:                } catch (Exception e) {
3214:                    throw new RuntimeException(e);
3215:                }
3216:            }
3217:
3218:            protected ByteArrayOutputStream loadResource(String name) {
3219:                ByteArrayOutputStream bos = new ByteArrayOutputStream();
3220:                InputStream is = getClass().getResourceAsStream(name);
3221:
3222:                try {
3223:                    int c = is.read();
3224:                    while (c != -1) {
3225:                        bos.write(c);
3226:                        c = is.read();
3227:                    }
3228:                    bos.flush();
3229:                } catch (IOException e) {
3230:                    throw new RuntimeException(e);
3231:                } finally {
3232:                    try {
3233:                        is.close();
3234:                    } catch (IOException e) {
3235:                        //can't do anything now..
3236:                        if (logger.isDebugEnabled()) {
3237:                            logger.debug(e);
3238:                        }
3239:                    }
3240:                }
3241:                return bos;
3242:            }
3243:
3244:            protected Id createResource(String resourceLocation, String name,
3245:                    String description, String type) {
3246:                ByteArrayOutputStream bos = loadResource(resourceLocation);
3247:                ContentResource resource;
3248:                ResourcePropertiesEdit resourceProperties = getContentHosting()
3249:                        .newResourceProperties();
3250:                resourceProperties.addProperty(
3251:                        ResourceProperties.PROP_DISPLAY_NAME, name);
3252:                resourceProperties.addProperty(
3253:                        ResourceProperties.PROP_DESCRIPTION, description);
3254:                resourceProperties.addProperty(
3255:                        ResourceProperties.PROP_CONTENT_ENCODING, "UTF-8");
3256:
3257:                String folder = "/group/PortfolioAdmin" + SYSTEM_COLLECTION_ID;
3258:
3259:                try {
3260:                    //TODO use the bean org.theospi.portfolio.admin.model.IntegrationOption.siteOption 
3261:                    // in common/components to get the name and id for this site.
3262:
3263:                    ContentCollectionEdit groupCollection = getContentHosting()
3264:                            .addCollection("/group/PortfolioAdmin");
3265:                    groupCollection.getPropertiesEdit().addProperty(
3266:                            ResourceProperties.PROP_DISPLAY_NAME,
3267:                            "Portfolio Admin");
3268:                    getContentHosting().commitCollection(groupCollection);
3269:                } catch (IdUsedException e) {
3270:                    // ignore... it is already there.
3271:                    if (logger.isDebugEnabled()) {
3272:                        logger.debug(e);
3273:                    }
3274:                } catch (Exception e) {
3275:                    throw new RuntimeException(e);
3276:                }
3277:
3278:                try {
3279:                    ContentCollectionEdit collection = getContentHosting()
3280:                            .addCollection(folder);
3281:                    collection.getPropertiesEdit().addProperty(
3282:                            ResourceProperties.PROP_DISPLAY_NAME, "system");
3283:                    getContentHosting().commitCollection(collection);
3284:
3285:                } catch (IdUsedException e) {
3286:                    // ignore... it is already there.
3287:                    if (logger.isDebugEnabled()) {
3288:                        logger.debug(e);
3289:                    }
3290:                } catch (Exception e) {
3291:                    throw new RuntimeException(e);
3292:                }
3293:
3294:                try {
3295:                    String id = folder + name;
3296:                    getContentHosting().removeResource(id);
3297:                } catch (TypeException e) {
3298:                    // ignore, must be new
3299:                    if (logger.isDebugEnabled()) {
3300:                        logger.debug(e);
3301:                    }
3302:                } catch (IdUnusedException e) {
3303:                    // ignore, must be new
3304:                    if (logger.isDebugEnabled()) {
3305:                        logger.debug(e);
3306:                    }
3307:                } catch (PermissionException e) {
3308:                    // ignore, must be new
3309:                    if (logger.isDebugEnabled()) {
3310:                        logger.debug(e);
3311:                    }
3312:                } catch (InUseException e) {
3313:                    // ignore, must be new
3314:                    if (logger.isDebugEnabled()) {
3315:                        logger.debug(e);
3316:                    }
3317:                }
3318:
3319:                try {
3320:                    resource = getContentHosting().addResource(name, folder,
3321:                            100, type, bos.toByteArray(), resourceProperties,
3322:                            NotificationService.NOTI_NONE);
3323:                } catch (Exception e) {
3324:                    throw new RuntimeException(e);
3325:                }
3326:                String uuid = getContentHosting().getUuid(resource.getId());
3327:                return getIdManager().getId(uuid);
3328:            }
3329:
3330:            /**
3331:             * 
3332:             * @param portfolios A list of Presentation objects
3333:             */
3334:            protected void convertPortfolios(List portfolios) {
3335:                org.sakaiproject.tool.api.Session sakaiSession = SessionManager
3336:                        .getCurrentSession();
3337:                String userId = sakaiSession.getUserId();
3338:                String userEid = sakaiSession.getUserEid();
3339:                try {
3340:                    sakaiSession.setUserId("admin");
3341:                    sakaiSession.setUserEid("admin");
3342:
3343:                    for (Iterator i = portfolios.iterator(); i.hasNext();) {
3344:                        Presentation presentation = (Presentation) i.next();
3345:                        byte[] formData = convertFormData(presentation
3346:                                .getProperties());
3347:                        Id propForm = saveForm(presentation.getOwner().getId()
3348:                                .getValue(), presentation.getName()
3349:                                + " Properties", formData, presentation
3350:                                .getTemplate().getPropertyFormType().getValue());
3351:                        presentation.setPropertyForm(propForm);
3352:                        storePresentation(presentation, false, true);
3353:
3354:                        logger
3355:                                .info("OSP Portfolio Conversion: For Portfolio with id "
3356:                                        + presentation.getId().getValue()
3357:                                        + ": Creating new Form Resource with id of "
3358:                                        + propForm.getValue());
3359:
3360:                    }
3361:                } catch (Exception e) {
3362:                    logger
3363:                            .warn(
3364:                                    "Unexpected error occurred in PresentationManagerImpl.convertPortfolios()",
3365:                                    e);
3366:                } finally {
3367:                    sakaiSession.setUserEid(userEid);
3368:                    sakaiSession.setUserId(userId);
3369:                }
3370:            }
3371:
3372:            private byte[] convertFormData(ElementBean elementBean) {
3373:                Document doc = new Document();
3374:                Element rootElement = elementBean.getBaseElement();
3375:                rootElement.detach();
3376:                doc.setRootElement(rootElement);
3377:                ByteArrayOutputStream out = new ByteArrayOutputStream();
3378:                XMLOutputter xmlOutputter = new XMLOutputter();
3379:                try {
3380:                    xmlOutputter.output(doc, out);
3381:                } catch (IOException e) {
3382:                    throw new HibernateException(e);
3383:                }
3384:                return out.toByteArray();
3385:            }
3386:
3387:            /**
3388:             * 
3389:             * @param templates A list of PresentationTemplate objects
3390:             */
3391:            protected void convertPortfolioTemplates(List templates) {
3392:                org.sakaiproject.tool.api.Session sakaiSession = SessionManager
3393:                        .getCurrentSession();
3394:                String userId = sakaiSession.getUserId();
3395:                String userEid = sakaiSession.getUserEid();
3396:                try {
3397:                    sakaiSession.setUserId("admin");
3398:                    sakaiSession.setUserEid("admin");
3399:
3400:                    for (Iterator i = templates.iterator(); i.hasNext();) {
3401:                        PresentationTemplate template = (PresentationTemplate) i
3402:                                .next();
3403:                        Id fileId = template.getPropertyPage();
3404:                        StructuredArtifactDefinitionBean tempFormDef = null;
3405:
3406:                        logger
3407:                                .info("OSP Portfolio Template Conversion: For Template with id "
3408:                                        + template.getId().getValue()
3409:                                        + ": Attempting to locate a Form using a File id of "
3410:                                        + fileId.getValue());
3411:
3412:                        //Doing this to make sure the file is setup in the security stack
3413:                        Node node = getNode(fileId);
3414:
3415:                        List formDefs = structuredArtifactDefinitionManager
3416:                                .findBySchema(node.getResource());
3417:                        if (formDefs == null || formDefs.isEmpty()) {
3418:                            //create a new form
3419:                            tempFormDef = new StructuredArtifactDefinitionBean();
3420:                            //tempFormDef.setSchemaFile(fileId);
3421:                            tempFormDef.setSchema(node.getResource()
3422:                                    .getContent());
3423:                            tempFormDef.setDocumentRoot(template
3424:                                    .getDocumentRoot());
3425:                            tempFormDef.setDescription("Portfolio Properties");
3426:                            tempFormDef.setOwner(template.getOwner());
3427:                            tempFormDef.setSiteId(template.getSiteId());
3428:                            if (template.isPublished()) {
3429:                                tempFormDef
3430:                                        .setSiteState(StructuredArtifactDefinitionBean.STATE_PUBLISHED);
3431:                            }
3432:                            structuredArtifactDefinitionManager
3433:                                    .save(tempFormDef);
3434:                            logger
3435:                                    .info("OSP Portfolio Template Conversion: Template with id "
3436:                                            + template.getId().getValue()
3437:                                            + " needs to create a new Form object.");
3438:                        } else {
3439:                            int counter = 0;
3440:                            while (tempFormDef == null && counter < 3) {
3441:                                tempFormDef = findUsableFormDef(formDefs,
3442:                                        counter, template.getSiteId());
3443:                                counter++;
3444:                            }
3445:                        }
3446:                        template.setPropertyFormType(tempFormDef.getId());
3447:                        storeTemplate(template, false);
3448:                        logger
3449:                                .info("OSP Portfolio Template Conversion: Template with id "
3450:                                        + template.getId().getValue()
3451:                                        + " is being updated to use form with id "
3452:                                        + tempFormDef.getId().getValue());
3453:                    }
3454:                } catch (Exception e) {
3455:                    logger
3456:                            .warn(
3457:                                    "Unexpected error occurred in PresentationManagerImpl.convertPortfolioTemplates()",
3458:                                    e);
3459:                } finally {
3460:                    sakaiSession.setUserEid(userEid);
3461:                    sakaiSession.setUserId(userId);
3462:                }
3463:            }
3464:
3465:            /**
3466:             * 
3467:             * @param formDefs A List of StructuredArtifactDefinitionBean objects to search through
3468:             * @param caseSwitch 0 for global published, 1 for site published, 2 for any in site
3469:             * @param siteId The id of site to search in
3470:             * @return The StructuredArtifactDefinitionBean object that was found, null of none found
3471:             */
3472:            protected StructuredArtifactDefinitionBean findUsableFormDef(
3473:                    List formDefs, int caseSwitch, String siteId) {
3474:                StructuredArtifactDefinitionBean retVal = null;
3475:                switch (caseSwitch) {
3476:                case 0:
3477:                    for (Iterator i = formDefs.iterator(); i.hasNext();) {
3478:                        StructuredArtifactDefinitionBean iterVal = (StructuredArtifactDefinitionBean) i
3479:                                .next();
3480:                        if (iterVal.getGlobalState() == StructuredArtifactDefinitionBean.STATE_PUBLISHED) {
3481:                            retVal = iterVal;
3482:                            break;
3483:                        }
3484:                    }
3485:                    break;
3486:                case 1:
3487:                    for (Iterator i = formDefs.iterator(); i.hasNext();) {
3488:                        StructuredArtifactDefinitionBean iterVal = (StructuredArtifactDefinitionBean) i
3489:                                .next();
3490:                        if (iterVal.getSiteState() == StructuredArtifactDefinitionBean.STATE_PUBLISHED
3491:                                && iterVal.getSiteId().equals(siteId)) {
3492:                            retVal = iterVal;
3493:                            break;
3494:                        }
3495:                    }
3496:                    break;
3497:                case 2:
3498:                    for (Iterator i = formDefs.iterator(); i.hasNext();) {
3499:                        StructuredArtifactDefinitionBean iterVal = (StructuredArtifactDefinitionBean) i
3500:                                .next();
3501:                        if (iterVal.getSiteId().equals(siteId)) {
3502:                            retVal = iterVal;
3503:                            break;
3504:                        }
3505:                    }
3506:                    break;
3507:                }
3508:                return retVal;
3509:            }
3510:
3511:            private Id saveForm(String owner, String name, byte[] fileContent,
3512:                    String formType) {
3513:                getSecurityService().pushAdvisor(new AllowAllSecurityAdvisor());
3514:
3515:                org.sakaiproject.tool.api.Session sakaiSession = SessionManager
3516:                        .getCurrentSession();
3517:                String userId = sakaiSession.getUserId();
3518:                sakaiSession.setUserId(owner);
3519:                sakaiSession.setUserEid(owner);
3520:
3521:                String description = "";
3522:                String folder = "/user/" + owner;
3523:                String type = "application/x-osp";
3524:
3525:                try {
3526:                    ContentCollectionEdit groupCollection = getContentHosting()
3527:                            .addCollection(folder);
3528:                    groupCollection.getPropertiesEdit().addProperty(
3529:                            ResourceProperties.PROP_DISPLAY_NAME, owner);
3530:                    getContentHosting().commitCollection(groupCollection);
3531:                } catch (IdUsedException e) {
3532:                    // ignore... it is already there.
3533:                } catch (Exception e) {
3534:                    throw new RuntimeException(e);
3535:                }
3536:
3537:                folder = "/user/" + owner + PRESENTATION_PROPERTIES_FOLDER_PATH;
3538:
3539:                try {
3540:                    ContentCollectionEdit groupCollection = getContentHosting()
3541:                            .addCollection(folder);
3542:                    groupCollection.getPropertiesEdit().addProperty(
3543:                            ResourceProperties.PROP_DISPLAY_NAME,
3544:                            PRESENTATION_PROPERTIES_FOLDER);
3545:                    groupCollection.getPropertiesEdit().addProperty(
3546:                            ResourceProperties.PROP_DESCRIPTION,
3547:                            "Folder for Portfolio Property Forms");
3548:                    getContentHosting().commitCollection(groupCollection);
3549:                } catch (IdUsedException e) {
3550:                    // ignore... it is already there.
3551:                } catch (Exception e) {
3552:                    throw new RuntimeException(e);
3553:                }
3554:
3555:                try {
3556:                    ResourcePropertiesEdit resourceProperties = getContentHosting()
3557:                            .newResourceProperties();
3558:                    resourceProperties.addProperty(
3559:                            ResourceProperties.PROP_DISPLAY_NAME, name);
3560:                    resourceProperties.addProperty(
3561:                            ResourceProperties.PROP_DESCRIPTION, description);
3562:                    resourceProperties.addProperty(
3563:                            ResourceProperties.PROP_CONTENT_ENCODING, "UTF-8");
3564:                    resourceProperties.addProperty(
3565:                            ResourceProperties.PROP_STRUCTOBJ_TYPE, formType);
3566:                    resourceProperties.addProperty(
3567:                            ContentHostingService.PROP_ALTERNATE_REFERENCE,
3568:                            MetaobjEntityManager.METAOBJ_ENTITY_PREFIX);
3569:
3570:                    ContentResource resource = getContentHosting().addResource(
3571:                            name, folder, 0, type, fileContent,
3572:                            resourceProperties, NotificationService.NOTI_NONE);
3573:                    return idManager.getId(getContentHosting().getUuid(
3574:                            resource.getId()));
3575:                } catch (Exception e) {
3576:                    throw new RuntimeException(e);
3577:                } finally {
3578:                    getSecurityService().popAdvisor();
3579:                    sakaiSession.setUserEid(userId);
3580:                    sakaiSession.setUserId(userId);
3581:                }
3582:            }
3583:
3584:            public Id getFreeFormTemplateId() {
3585:                return Presentation.FREEFORM_TEMPLATE_ID;
3586:            }
3587:
3588:            public List getDefinedLayouts() {
3589:                return definedLayouts;
3590:            }
3591:
3592:            public void setDefinedLayouts(List definedLayouts) {
3593:                this .definedLayouts = definedLayouts;
3594:            }
3595:
3596:            public StructuredArtifactDefinitionManager getStructuredArtifactDefinitionManager() {
3597:                return structuredArtifactDefinitionManager;
3598:            }
3599:
3600:            public void setStructuredArtifactDefinitionManager(
3601:                    StructuredArtifactDefinitionManager structuredArtifactDefinitionManager) {
3602:                this .structuredArtifactDefinitionManager = structuredArtifactDefinitionManager;
3603:            }
3604:
3605:            public List getGlobalSites() {
3606:                return globalSites;
3607:            }
3608:
3609:            public void setGlobalSites(List globalSites) {
3610:                this .globalSites = globalSites;
3611:            }
3612:
3613:            public List getGlobalSiteTypes() {
3614:                return globalSiteTypes;
3615:            }
3616:
3617:            public void setGlobalSiteTypes(List globalSiteTypes) {
3618:                this .globalSiteTypes = globalSiteTypes;
3619:            }
3620:
3621:            public List getInitializedServices() {
3622:                return initializedServices;
3623:            }
3624:
3625:            public void setInitializedServices(List initializedServices) {
3626:                this .initializedServices = initializedServices;
3627:            }
3628:
3629:            protected List getPresentationPagesByStyle(Id styleId) {
3630:                Object[] params = new Object[] { styleId };
3631:                return getHibernateTemplate().findByNamedQuery(
3632:                        "findPortfolioPagesByStyle", params);
3633:            }
3634:
3635:            protected List getPresentationsByStyle(Id styleId) {
3636:                Object[] params = new Object[] { styleId };
3637:                return getHibernateTemplate().findByNamedQuery(
3638:                        "findPortfoliosByStyle", params);
3639:            }
3640:
3641:            public boolean checkStyleConsumption(Id styleId) {
3642:                List pages = getPresentationPagesByStyle(styleId);
3643:                if (pages != null && !pages.isEmpty() && pages.size() > 0) {
3644:                    return true;
3645:                }
3646:
3647:                List presentations = getPresentationsByStyle(styleId);
3648:                if (presentations != null && !presentations.isEmpty()
3649:                        && presentations.size() > 0) {
3650:                    return true;
3651:                }
3652:
3653:                return false;
3654:            }
3655:
3656:            public String getImportFolderName() {
3657:                return importFolderName;
3658:            }
3659:
3660:            public void setImportFolderName(String importFolderName) {
3661:                this .importFolderName = importFolderName;
3662:            }
3663:
3664:            public boolean checkFormConsumption(Id formId) {
3665:                Collection objectsWithForms = getHibernateTemplate().find(
3666:                        "from PresentationTemplate where propertyFormType = ?",
3667:                        new Object[] { formId });
3668:
3669:                if (objectsWithForms.size() > 0) {
3670:                    return true;
3671:                }
3672:
3673:                String queryString = "from PresentationItemDefinition where "
3674:                        + "type = ?";
3675:                Collection additionalForms = getHibernateTemplate().find(
3676:                        queryString, new Object[] { formId.getValue() });
3677:
3678:                return additionalForms.size() > 0;
3679:            }
3680:
3681:            public boolean isAutoDdl() {
3682:                return autoDdl;
3683:            }
3684:
3685:            public void setAutoDdl(boolean autoDdl) {
3686:                this .autoDdl = autoDdl;
3687:            }
3688:
3689:            public boolean isPortfolioPropertyFormConversion() {
3690:                return portfolioPropertyFormConversion;
3691:            }
3692:
3693:            public void setPortfolioPropertyFormConversion(
3694:                    boolean portfolioPropertyFormConversion) {
3695:                this.portfolioPropertyFormConversion = portfolioPropertyFormConversion;
3696:            }
3697:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.