0001: /**********************************************************************************
0002: * $URL: https://source.sakaiproject.org/svn/osp/tags/sakai_2-4-1/matrix/api-impl/src/java/org/theospi/portfolio/matrix/HibernateMatrixManagerImpl.java $
0003: * $Id: HibernateMatrixManagerImpl.java 22545 2007-03-13 16:41:38Z john.ellis@rsmart.com $
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.matrix;
0021:
0022: import java.beans.XMLDecoder;
0023: import java.beans.XMLEncoder;
0024: import java.io.BufferedInputStream;
0025: import java.io.BufferedOutputStream;
0026: import java.io.ByteArrayInputStream;
0027: import java.io.ByteArrayOutputStream;
0028: import java.io.File;
0029: import java.io.IOException;
0030: import java.io.InputStream;
0031: import java.io.OutputStream;
0032: import java.sql.SQLException;
0033: import java.util.ArrayList;
0034: import java.util.Collection;
0035: import java.util.Date;
0036: import java.util.HashSet;
0037: import java.util.Hashtable;
0038: import java.util.Iterator;
0039: import java.util.List;
0040: import java.util.Map;
0041: import java.util.Set;
0042: import java.util.zip.Adler32;
0043: import java.util.zip.CheckedOutputStream;
0044: import java.util.zip.ZipEntry;
0045: import java.util.zip.ZipInputStream;
0046: import java.util.zip.ZipOutputStream;
0047:
0048: import org.hibernate.AssertionFailure;
0049: import org.hibernate.Criteria;
0050: import org.hibernate.FetchMode;
0051: import org.hibernate.HibernateException;
0052: import org.hibernate.Session;
0053: import org.hibernate.criterion.Expression;
0054: import org.jdom.Element;
0055: import org.sakaiproject.authz.api.SecurityService;
0056: import org.sakaiproject.content.api.ContentCollection;
0057: import org.sakaiproject.content.api.ContentCollectionEdit;
0058: import org.sakaiproject.content.api.ContentHostingService;
0059: import org.sakaiproject.content.api.ContentResource;
0060: import org.sakaiproject.content.api.ContentResourceEdit;
0061: import org.sakaiproject.content.api.LockManager;
0062: import org.sakaiproject.entity.api.Reference;
0063: import org.sakaiproject.entity.api.ResourceProperties;
0064: import org.sakaiproject.entity.api.ResourcePropertiesEdit;
0065: import org.sakaiproject.exception.IdInvalidException;
0066: import org.sakaiproject.exception.IdUnusedException;
0067: import org.sakaiproject.exception.IdUsedException;
0068: import org.sakaiproject.exception.ImportException;
0069: import org.sakaiproject.exception.InconsistentException;
0070: import org.sakaiproject.exception.OverQuotaException;
0071: import org.sakaiproject.exception.PermissionException;
0072: import org.sakaiproject.exception.ServerOverloadException;
0073: import org.sakaiproject.exception.TypeException;
0074: import org.sakaiproject.metaobj.security.AuthenticationManager;
0075: import org.sakaiproject.metaobj.shared.ArtifactFinder;
0076: import org.sakaiproject.metaobj.shared.DownloadableManager;
0077: import org.sakaiproject.metaobj.shared.mgt.*;
0078: import org.sakaiproject.metaobj.shared.model.Agent;
0079: import org.sakaiproject.metaobj.shared.model.Artifact;
0080: import org.sakaiproject.metaobj.shared.model.FinderException;
0081: import org.sakaiproject.metaobj.shared.model.Id;
0082: import org.sakaiproject.metaobj.shared.model.MimeType;
0083: import org.sakaiproject.metaobj.shared.model.StructuredArtifactDefinitionBean;
0084: import org.sakaiproject.metaobj.shared.model.InvalidUploadException;
0085: import org.sakaiproject.metaobj.worksite.mgt.WorksiteManager;
0086: import org.sakaiproject.service.legacy.resource.DuplicatableToolService;
0087: import org.sakaiproject.site.api.Site;
0088: import org.sakaiproject.site.api.SitePage;
0089: import org.sakaiproject.site.api.ToolConfiguration;
0090: import org.sakaiproject.site.cover.SiteService;
0091: import org.sakaiproject.tool.cover.ToolManager;
0092: import org.sakaiproject.user.api.User;
0093: import org.sakaiproject.user.cover.UserDirectoryService;
0094: import org.springframework.dao.DataAccessResourceFailureException;
0095: import org.springframework.orm.hibernate3.HibernateCallback;
0096: import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
0097: import org.theospi.portfolio.guidance.mgt.GuidanceManager;
0098: import org.theospi.portfolio.guidance.model.Guidance;
0099: import org.theospi.portfolio.matrix.model.*;
0100: import org.theospi.portfolio.matrix.model.impl.MatrixContentEntityProducer;
0101: import org.theospi.portfolio.review.mgt.ReviewManager;
0102: import org.theospi.portfolio.review.model.Review;
0103: import org.theospi.portfolio.security.AllowMapSecurityAdvisor;
0104: import org.theospi.portfolio.security.Authorization;
0105: import org.theospi.portfolio.security.AuthorizationFacade;
0106: import org.theospi.portfolio.shared.intf.EntityContextFinder;
0107: import org.theospi.portfolio.shared.model.Node;
0108: import org.theospi.portfolio.shared.model.OspException;
0109: import org.theospi.portfolio.style.StyleConsumer;
0110: import org.theospi.portfolio.style.mgt.StyleManager;
0111: import org.theospi.portfolio.style.model.Style;
0112: import org.theospi.portfolio.wizard.WizardFunctionConstants;
0113: import org.theospi.portfolio.workflow.mgt.WorkflowManager;
0114: import org.theospi.portfolio.workflow.model.Workflow;
0115: import org.theospi.portfolio.workflow.model.WorkflowItem;
0116: import org.theospi.utils.zip.UncloseableZipInputStream;
0117:
0118: /**
0119: * @author rpembry
0120: */
0121: public class HibernateMatrixManagerImpl extends HibernateDaoSupport
0122: implements MatrixManager, ReadableObjectHome, ArtifactFinder,
0123: DownloadableManager, PresentableObjectHome,
0124: DuplicatableToolService, StyleConsumer, FormConsumer {
0125:
0126: static final private String IMPORT_BASE_FOLDER_ID = "importedMatrices";
0127:
0128: private IdManager idManager;
0129: private AuthenticationManager authnManager = null;
0130: private AuthorizationFacade authzManager = null;
0131: private AgentManager agentManager = null;
0132: private PresentableObjectHome xmlRenderer;
0133: private WorksiteManager worksiteManager;
0134: private LockManager lockManager;
0135: private boolean loadArtifacts = true;
0136: private ContentHostingService contentHosting = null;
0137: private SecurityService securityService;
0138: private DefaultScaffoldingBean defaultScaffoldingBean;
0139: private WorkflowManager workflowManager;
0140: private StructuredArtifactDefinitionManager structuredArtifactDefinitionManager;
0141: private GuidanceManager guidanceManager;
0142: private ReviewManager reviewManager;
0143: private StyleManager styleManager;
0144:
0145: private static final String SCAFFOLDING_ID_TAG = "scaffoldingId";
0146: private EntityContextFinder contentFinder = null;
0147: private String importFolderName;
0148: private boolean useExperimentalMatrix = false;
0149:
0150: public Scaffolding createDefaultScaffolding() {
0151: return getDefaultScaffoldingBean().createDefaultScaffolding();
0152: }
0153:
0154: public List getScaffolding() {
0155: return getHibernateTemplate().find("from Scaffolding");
0156: }
0157:
0158: /**
0159: * {@inheritDoc}
0160: */
0161: public List findAvailableScaffolding(String siteIdStr, Agent user) {
0162:
0163: Object[] params = new Object[] {
0164: getIdManager().getId(siteIdStr), user,
0165: new Boolean(true) };
0166: return getHibernateTemplate().find(
0167: "from Scaffolding s where s.worksiteId=? "
0168: + "and (s.owner=? or s.published=?) ", params);
0169: }
0170:
0171: /**
0172: * gathers all the published scaffolding from the given site (id)
0173: * @param siteId String
0174: * @return List of Scaffolding
0175: */
0176: protected List findPublishedScaffolding(String siteId) {
0177: Object[] params = new Object[] { getIdManager().getId(siteId),
0178: new Boolean(true) };
0179: return getHibernateTemplate().find(
0180: "from Scaffolding s where s.worksiteId=? "
0181: + "and s.published=?", params);
0182: }
0183:
0184: /**
0185: *
0186: * @param sites A list of site Ids (Ids)
0187: * @return
0188: */
0189: public List findPublishedScaffolding(List sites) {
0190: String[] paramNames = new String[] { "siteIds", "published" };
0191: Object[] params = new Object[] { sites, new Boolean(true) };
0192: return getHibernateTemplate().findByNamedParam(
0193: "from Scaffolding s where s.worksiteId in ( :siteIds ) "
0194: + "and s.published=:published", paramNames,
0195: params);
0196: }
0197:
0198: /**
0199: * Gets all the scaffolding for the data warehouse. It preloads all the cells, levels, criterion.
0200: * It sets the back trace from the level and criterion back to the scaffolding and sets the sequence
0201: * index number for ordering.
0202: * @return List of Scaffolding
0203: */
0204: public List getScaffoldingForWarehousing() {
0205: List scaffolding = getHibernateTemplate().find(
0206: "from Scaffolding");
0207:
0208: for (Iterator i = scaffolding.iterator(); i.hasNext();) {
0209: Scaffolding scaff = (Scaffolding) i.next();
0210: Set cells = scaff.getScaffoldingCells();
0211:
0212: //Load the evaluators for the cells as well.
0213: for (Iterator ii = cells.iterator(); ii.hasNext();) {
0214: ScaffoldingCell cell = (ScaffoldingCell) ii.next();
0215:
0216: cell.setEvaluators(getScaffoldingCellEvaluators(cell
0217: .getWizardPageDefinition().getId(), true));
0218: }
0219:
0220: List levels = scaff.getLevels();
0221: int n = 0;
0222: for (Iterator ii = levels.iterator(); ii.hasNext();) {
0223: Level level = (Level) ii.next();
0224:
0225: level.setSequenceNumber(n++);
0226: level.setScaffolding(scaff);
0227: }
0228:
0229: List criteria = scaff.getCriteria();
0230: criteria.size();
0231: n = 0;
0232: for (Iterator ii = criteria.iterator(); ii.hasNext();) {
0233: Criterion criterion = (Criterion) ii.next();
0234:
0235: criterion.setSequenceNumber(n++);
0236: criterion.setScaffolding(scaff);
0237: }
0238: }
0239:
0240: return scaffolding;
0241: }
0242:
0243: public List getMatrices(Id scaffoldingId) {
0244: List matrices = getHibernateTemplate().find(
0245: "from Matrix matrix where matrix.scaffolding.id = ?",
0246: new Object[] { scaffoldingId });
0247:
0248: return matrices;
0249: }
0250:
0251: public List getCellsByScaffoldingCell(Id scaffoldingCellId) {
0252: List list = getHibernateTemplate().find(
0253: "from Cell cell where cell.scaffoldingCell.id=?",
0254: scaffoldingCellId);
0255: return list;
0256: }
0257:
0258: public List getPagesByPageDef(Id pageDefId) {
0259: List list = getHibernateTemplate().find(
0260: "from WizardPage page where page.pageDefinition.id=?",
0261: pageDefId);
0262: return list;
0263: }
0264:
0265: public List getMatrices(Id scaffoldingId, Id agentId) {
0266: String query = "from Matrix matrix";
0267: Object[] params = new Object[] {};
0268:
0269: if (scaffoldingId == null && agentId == null) {
0270: } else if (scaffoldingId == null) {
0271: query += " where matrix.owner like ?";
0272: params = new Object[] { getAgentManager().getAgent(agentId) };
0273: } else if (agentId == null) {
0274: query += " where matrix.scaffolding.id like ?";
0275: params = new Object[] { scaffoldingId };
0276: } else {
0277: query += " where matrix.scaffolding.id like ? and matrix.owner like ?";
0278: params = new Object[] { scaffoldingId,
0279: getAgentManager().getAgent(agentId) };
0280: }
0281:
0282: //TODO move this into a callback
0283: getHibernateTemplate().setCacheQueries(true);
0284:
0285: List list = getHibernateTemplate().find(query, params);
0286:
0287: return list;
0288: }
0289:
0290: public Matrix getMatrix(Id scaffoldingId, Id agentId) {
0291: List list = getMatrices(scaffoldingId, agentId);
0292:
0293: if (list.size() > 0)
0294: return (Matrix) list.get(0);
0295: else
0296: return null;
0297: }
0298:
0299: public List getCells(Matrix matrix) {
0300: getHibernateTemplate().setCacheQueries(true);
0301: return getHibernateTemplate()
0302: .find("from Cell cell where cell.matrix.id=?",
0303: matrix.getId());
0304:
0305: }
0306:
0307: public Cell getCell(Matrix matrix, Criterion rootCriterion,
0308: Level level) {
0309: //TODO should be something easier for this HQL
0310:
0311: Object[] params = new Object[] { matrix.getId(),
0312: rootCriterion.getId(), level.getId() };
0313: getHibernateTemplate().setCacheQueries(true);
0314: List list = getHibernateTemplate()
0315: .find(
0316: "from Cell cell where cell.matrix.id=? and cell.scaffoldingCell.rootCriterion.id=? and cell.scaffoldingCell.level.id=?",
0317: params);
0318: return (Cell) list.get(0);
0319: }
0320:
0321: public void unlockNextCell(Cell cell) {
0322: Matrix matrix = cell.getMatrix();
0323: List levels = matrix.getScaffolding().getLevels();
0324: int i = levels.indexOf(cell.getScaffoldingCell().getLevel());
0325: if (i < levels.size() - 1) {
0326: Level nextLevel = (Level) levels.get(i + 1);
0327: Cell nextCell = getCell(cell.getMatrix(), cell
0328: .getScaffoldingCell().getRootCriterion(), nextLevel);
0329: if (nextCell.getStatus().equals(
0330: MatrixFunctionConstants.LOCKED_STATUS)) {
0331: nextCell
0332: .setStatus(MatrixFunctionConstants.READY_STATUS);
0333: storeCell(nextCell);
0334: }
0335: }
0336: }
0337:
0338: public ScaffoldingCell getNextScaffoldingCell(
0339: ScaffoldingCell scaffoldingCell, int progressionOption) {
0340: Scaffolding scaffolding = scaffoldingCell.getScaffolding();
0341: ScaffoldingCell nextCell = null;
0342:
0343: if (progressionOption == Scaffolding.HORIZONTAL_PROGRESSION) {
0344: List columns = scaffolding.getLevels();
0345: int i = columns.indexOf(scaffoldingCell.getLevel());
0346: if (i < columns.size() - 1) {
0347: Level column = (Level) columns.get(i + 1);
0348: nextCell = getScaffoldingCell(scaffoldingCell
0349: .getRootCriterion(), column);
0350: }
0351: } else if (progressionOption == Scaffolding.VERTICAL_PROGRESSION) {
0352: List rows = scaffolding.getCriteria();
0353: int i = rows.indexOf(scaffoldingCell.getRootCriterion());
0354: if (i < rows.size() - 1) {
0355: Criterion row = (Criterion) rows.get(i + 1);
0356: nextCell = getScaffoldingCell(row, scaffoldingCell
0357: .getLevel());
0358: }
0359: }
0360: return nextCell;
0361: }
0362:
0363: public Cell getNextCell(Cell cell, int progressionOption) {
0364: ScaffoldingCell scaffoldingCell = cell.getScaffoldingCell();
0365: Scaffolding scaffolding = scaffoldingCell.getScaffolding();
0366: Cell nextCell = null;
0367:
0368: if (progressionOption == Scaffolding.HORIZONTAL_PROGRESSION) {
0369: List columns = scaffolding.getLevels();
0370: int i = columns.indexOf(scaffoldingCell.getLevel());
0371: if (i < columns.size() - 1) {
0372: Level column = (Level) columns.get(i + 1);
0373: nextCell = getCell(cell.getMatrix(), scaffoldingCell
0374: .getRootCriterion(), column);
0375: }
0376: } else if (progressionOption == Scaffolding.VERTICAL_PROGRESSION) {
0377: List rows = scaffolding.getCriteria();
0378: int i = rows.indexOf(scaffoldingCell.getRootCriterion());
0379: if (i < rows.size() - 1) {
0380: Criterion row = (Criterion) rows.get(i + 1);
0381: nextCell = getCell(cell.getMatrix(), row,
0382: scaffoldingCell.getLevel());
0383: }
0384: }
0385: return nextCell;
0386: }
0387:
0388: protected Cell getMatrixCellByWizardPageDef(Matrix matrix,
0389: Id wizardPageDefId) {
0390: for (Iterator cells = matrix.getCells().iterator(); cells
0391: .hasNext();) {
0392: Cell cell = (Cell) cells.next();
0393: if (cell.getScaffoldingCell().getWizardPageDefinition()
0394: .getId().getValue().equals(
0395: wizardPageDefId.getValue())) {
0396: return cell;
0397: }
0398: }
0399: return null;
0400: }
0401:
0402: public Criterion getCriterion(Id criterionId) {
0403: return (Criterion) this .getHibernateTemplate().load(
0404: Criterion.class, criterionId);
0405: }
0406:
0407: public Level getLevel(Id levelId) {
0408: return (Level) this .getHibernateTemplate().load(Level.class,
0409: levelId);
0410: }
0411:
0412: public Cell getCell(Id cellId) {
0413: Cell cell = (Cell) this .getHibernateTemplate().get(Cell.class,
0414: cellId);
0415: return cell;
0416: }
0417:
0418: public Cell getCellFromPage(Id pageId) {
0419: List cells = getHibernateTemplate().find(
0420: "from Cell where wizard_page_id=?",
0421: new Object[] { pageId.getValue() });
0422:
0423: if (cells.size() > 0) {
0424: return (Cell) cells.get(0);
0425: }
0426:
0427: return null;
0428: }
0429:
0430: public Id storeCell(Cell cell) {
0431: this .getHibernateTemplate().saveOrUpdate(cell);
0432: return cell.getId();
0433: }
0434:
0435: public Id storePage(WizardPage page) {
0436: this .getHibernateTemplate().saveOrUpdate(page);
0437: return page.getId();
0438: }
0439:
0440: public void publishScaffolding(Id scaffoldingId) {
0441: Scaffolding scaffolding = this .getScaffolding(scaffoldingId);
0442: scaffolding.setPreview(false);
0443: scaffolding.setPublished(true);
0444: scaffolding.setPublishedBy(authnManager.getAgent());
0445: scaffolding.setPublishedDate(new Date(System
0446: .currentTimeMillis()));
0447: this .storeScaffolding(scaffolding);
0448:
0449: }
0450:
0451: public void previewScaffolding(Id scaffoldingId) {
0452: Scaffolding scaffolding = this .getScaffolding(scaffoldingId);
0453: scaffolding.setPreview(true);
0454: this .storeScaffolding(scaffolding);
0455:
0456: }
0457:
0458: public Scaffolding storeScaffolding(Scaffolding scaffolding) {
0459: scaffolding = (Scaffolding) this .store(scaffolding);
0460: getHibernateTemplate().flush();
0461: return scaffolding;
0462: }
0463:
0464: public Scaffolding saveNewScaffolding(Scaffolding scaffolding) {
0465:
0466: Id id = (Id) this .save(scaffolding);
0467: getHibernateTemplate().flush();
0468: scaffolding = getScaffolding(id);
0469:
0470: return scaffolding;
0471: }
0472:
0473: public Id storeScaffoldingCell(ScaffoldingCell scaffoldingCell) {
0474: scaffoldingCell = (ScaffoldingCell) store(scaffoldingCell);
0475: return scaffoldingCell.getId();
0476: }
0477:
0478: public Object store(Object obj) {
0479: obj = this .getHibernateTemplate().merge(obj);
0480: return obj;
0481: }
0482:
0483: public Object save(Object obj) {
0484: obj = this .getHibernateTemplate().save(obj);
0485: return obj;
0486: }
0487:
0488: public Matrix createMatrix(Agent owner, Scaffolding scaffolding) {
0489: Matrix matrix = new Matrix();
0490: matrix.setOwner(owner);
0491: matrix.setScaffolding(scaffolding);
0492:
0493: List levels = scaffolding.getLevels();
0494: List criteria = scaffolding.getCriteria();
0495:
0496: Criterion criterion = null;
0497: Level level = null;
0498:
0499: for (Iterator criteriaIterator = criteria.iterator(); criteriaIterator
0500: .hasNext();) {
0501: criterion = (Criterion) criteriaIterator.next();
0502:
0503: for (Iterator levelsIterator = levels.iterator(); levelsIterator
0504: .hasNext();) {
0505: level = (Level) levelsIterator.next();
0506:
0507: Cell cell = new Cell();
0508: cell.getWizardPage().setOwner(owner);
0509: ScaffoldingCell sCell = getScaffoldingCell(criterion,
0510: level);
0511: cell.setScaffoldingCell(sCell);
0512: if (sCell != null) {
0513: String status = sCell.getInitialStatus();
0514: cell.setStatus(status);
0515: } else
0516: cell
0517: .setStatus(MatrixFunctionConstants.LOCKED_STATUS);
0518:
0519: matrix.add(cell);
0520: }
0521: }
0522:
0523: this .getHibernateTemplate().save(matrix);
0524: return matrix;
0525: }
0526:
0527: public Attachment attachArtifact(Id pageId, Reference artifactRef) {
0528: Id artifactId = convertRef(artifactRef);
0529: detachArtifact(pageId, artifactId);
0530: WizardPage page = getWizardPage(pageId);
0531: Attachment attachment = new Attachment();
0532: attachment.setArtifactId(artifactId);
0533: attachment.setWizardPage(page);
0534: attachment.setNewId(getIdManager().createId());
0535:
0536: page.getAttachments().add(attachment);
0537:
0538: this .getHibernateTemplate().saveOrUpdate(page);
0539: return attachment;
0540: }
0541:
0542: public WizardPage getWizardPage(Id pageId) {
0543: WizardPage page = (WizardPage) this .getHibernateTemplate().get(
0544: WizardPage.class, pageId);
0545:
0546: // check for invalid page (in case wizard/matrix is deleted)
0547: if (page == null) {
0548: logger.warn("Invalid wizard or matrix page: "
0549: + pageId.toString());
0550: return null;
0551: }
0552:
0553: page.getAttachments().size();
0554: page.getPageForms().size();
0555:
0556: removeFromSession(page);
0557: return page;
0558: }
0559:
0560: protected List getWizardPages() {
0561: return this .getHibernateTemplate().find("from WizardPage");
0562: }
0563:
0564: protected Id convertRef(Reference artifactRef) {
0565: String uuid = getContentHosting().getUuid(artifactRef.getId());
0566: return getIdManager().getId(uuid);
0567: }
0568:
0569: public void detachArtifact(final Id pageId, final Id artifactId) {
0570:
0571: HibernateCallback callback = new HibernateCallback() {
0572: public Object doInHibernate(Session session)
0573: throws HibernateException, SQLException {
0574: WizardPage page = (WizardPage) session.load(
0575: WizardPage.class, pageId);
0576: Set attachments = page.getAttachments();
0577: Iterator iter = attachments.iterator();
0578: List toRemove = new ArrayList();
0579: while (iter.hasNext()) {
0580: Attachment a = (Attachment) iter.next();
0581: if (a.getArtifactId() == null
0582: || artifactId.equals(a.getArtifactId())) {
0583: toRemove.add(a);
0584: }
0585: }
0586: attachments.removeAll(toRemove);
0587: page.setAttachments(attachments);
0588:
0589: session.saveOrUpdate(page);
0590: return null;
0591: }
0592:
0593: };
0594:
0595: getHibernateTemplate().execute(callback);
0596:
0597: }
0598:
0599: public void detachForm(final Id pageId, final Id artifactId) {
0600:
0601: HibernateCallback callback = new HibernateCallback() {
0602: public Object doInHibernate(Session session)
0603: throws HibernateException, SQLException {
0604: WizardPage page = (WizardPage) session.load(
0605: WizardPage.class, pageId);
0606: Set forms = page.getPageForms();
0607:
0608: Iterator iter = forms.iterator();
0609: List toRemove = new ArrayList();
0610: while (iter.hasNext()) {
0611: WizardPageForm wpf = (WizardPageForm) iter.next();
0612: if (wpf.getArtifactId() == null
0613: || artifactId.equals(wpf.getArtifactId())) {
0614: toRemove.add(wpf);
0615: }
0616: }
0617: forms.removeAll(toRemove);
0618: page.setPageForms(forms);
0619:
0620: session.saveOrUpdate(page);
0621: return null;
0622: }
0623:
0624: };
0625:
0626: getHibernateTemplate().execute(callback);
0627:
0628: }
0629:
0630: public Matrix getMatrixByPage(Id pageId) {
0631: Matrix matrix = null;
0632: Object[] params = new Object[] { pageId };
0633:
0634: List list = this .getHibernateTemplate().find(
0635: "select cell.matrix from "
0636: + "Cell cell where cell.wizardPage.id=? ",
0637: params);
0638: if (list.size() == 1) {
0639: matrix = (Matrix) list.get(0);
0640: }
0641:
0642: return matrix;
0643: }
0644:
0645: public Matrix getMatrix(Id matrixId) {
0646: return (Matrix) this .getHibernateTemplate().load(Matrix.class,
0647: matrixId);
0648: }
0649:
0650: public List getMatricesForWarehousing() {
0651:
0652: List matrices = getMatrices(null, null);
0653:
0654: for (Iterator ii = matrices.iterator(); ii.hasNext();) {
0655: Matrix mat = (Matrix) ii.next();
0656:
0657: mat.getId();
0658: //mat.setMatrixTool(tool);
0659:
0660: mat.getCells().size();
0661:
0662: for (Iterator iii = mat.getCells().iterator(); iii
0663: .hasNext();) {
0664: Cell cell = (Cell) iii.next();
0665:
0666: cell.getWizardPage().getPageForms().size();
0667: cell.getWizardPage().getAttachments().size();
0668: }
0669:
0670: getHibernateTemplate().evict(mat);
0671: }
0672: return matrices;
0673: }
0674:
0675: public List getWizardPagesForWarehousing() {
0676:
0677: List wizardPages = this .getWizardPages();
0678:
0679: for (Iterator ii = wizardPages.iterator(); ii.hasNext();) {
0680: WizardPage wizardPage = (WizardPage) ii.next();
0681:
0682: wizardPage.getId();
0683: wizardPage.getPageForms().size();
0684: wizardPage.getAttachments().size();
0685:
0686: getHibernateTemplate().evict(wizardPage);
0687: }
0688: return wizardPages;
0689: }
0690:
0691: public Scaffolding getScaffolding(Id scaffoldingId) {
0692: return (Scaffolding) this .getHibernateTemplate().get(
0693: Scaffolding.class, scaffoldingId);
0694: //return getScaffolding(scaffoldingId, false);
0695: }
0696:
0697: protected Scaffolding getScaffoldingForExport(Id scaffoldingId) {
0698: Scaffolding scaffolding = (Scaffolding) this
0699: .getHibernateTemplate().get(Scaffolding.class,
0700: scaffoldingId);
0701:
0702: for (Iterator iter = scaffolding.getScaffoldingCells()
0703: .iterator(); iter.hasNext();) {
0704: ScaffoldingCell sCell = (ScaffoldingCell) iter.next();
0705: Collection evaluators = this .getScaffoldingCellEvaluators(
0706: sCell.getWizardPageDefinition().getId(), false);
0707: sCell.setEvaluators(new HashSet(evaluators));
0708: }
0709:
0710: return scaffolding;
0711: }
0712:
0713: protected List getScaffoldingByStyle(Id styleId) {
0714: Object[] params = new Object[] { styleId };
0715: return getHibernateTemplate().find(
0716: "from Scaffolding s where s.style.id=? ", params);
0717:
0718: }
0719:
0720: protected List getWizardPageDefByStyle(Id styleId) {
0721: Object[] params = new Object[] { styleId };
0722: return getHibernateTemplate().find(
0723: "from WizardPageDefinition wpd where wpd.style.id=? ",
0724: params);
0725:
0726: }
0727:
0728: public ScaffoldingCell getScaffoldingCell(Criterion criterion,
0729: Level level) {
0730: ScaffoldingCell scaffoldingCell = null;
0731: Object[] params = new Object[] { criterion.getId(),
0732: level.getId() };
0733:
0734: List list = this
0735: .getHibernateTemplate()
0736: .find(
0737: "from "
0738: + "ScaffoldingCell scaffoldingCell where scaffoldingCell.rootCriterion.id=? "
0739: + "and scaffoldingCell.level.id=?",
0740: params);
0741: if (list.size() == 1) {
0742: scaffoldingCell = (ScaffoldingCell) list.get(0);
0743: }
0744:
0745: return scaffoldingCell;
0746: }
0747:
0748: public String getScaffoldingCellsStatus(Id scaffoldingCellId) {
0749: ScaffoldingCell scaffoldingCell = null;
0750: String result = "";
0751: Criteria c = this .getSession().createCriteria(
0752: ScaffoldingCell.class);
0753: try {
0754: c.add(Expression.eq("id", scaffoldingCellId));
0755:
0756: scaffoldingCell = (ScaffoldingCell) c.uniqueResult();
0757: result = scaffoldingCell.getInitialStatus();
0758: this .removeFromSession(scaffoldingCell);
0759: } catch (HibernateException e) {
0760: logger.error("Error returning scaffoldingCell with id: "
0761: + scaffoldingCellId);
0762: return null;
0763: }
0764: return result;
0765: }
0766:
0767: public ScaffoldingCell getScaffoldingCell(Id id) {
0768: ScaffoldingCell scaffoldingCell = (ScaffoldingCell) this
0769: .getHibernateTemplate().load(ScaffoldingCell.class, id);
0770:
0771: scaffoldingCell
0772: .setEvaluators(getScaffoldingCellEvaluators(
0773: scaffoldingCell.getWizardPageDefinition()
0774: .getId(), true));
0775:
0776: return scaffoldingCell;
0777: }
0778:
0779: public ScaffoldingCell getScaffoldingCellByWizardPageDef(Id id) {
0780: ScaffoldingCell scaffoldingCell = null;
0781: Object[] params = new Object[] { id };
0782:
0783: List list = this
0784: .getHibernateTemplate()
0785: .find(
0786: "from "
0787: + "ScaffoldingCell scaffoldingCell where scaffoldingCell.wizardPageDefinition.id=?",
0788: params);
0789: if (list.size() == 1) {
0790: scaffoldingCell = (ScaffoldingCell) list.get(0);
0791: }
0792:
0793: return scaffoldingCell;
0794: }
0795:
0796: protected Collection getScaffoldingCellEvaluators(
0797: Id wizardPageDefId, boolean useAgentId) {
0798: Collection evaluators = new HashSet();
0799: Collection viewerAuthzs = getAuthzManager().getAuthorizations(
0800: null, MatrixFunctionConstants.EVALUATE_MATRIX,
0801: wizardPageDefId);
0802:
0803: for (Iterator i = viewerAuthzs.iterator(); i.hasNext();) {
0804: Authorization evaluator = (Authorization) i.next();
0805: if (useAgentId)
0806: evaluators.add(evaluator.getAgent());
0807: else
0808: evaluators.add(evaluator.getAgent().getId());
0809: }
0810: return evaluators;
0811: }
0812:
0813: public void removeFromSession(Object obj) {
0814: this .getHibernateTemplate().evict(obj);
0815: }
0816:
0817: public void clearSession() {
0818: this .getHibernateTemplate().clear();
0819: }
0820:
0821: private Scaffolding getScaffoldingByArtifact(Id artifactId) {
0822:
0823: List list = this
0824: .getHibernateTemplate()
0825: .find(
0826: "from "
0827: + "Scaffolding scaffolding where scaffolding.artifactId=?",
0828: artifactId.getValue());
0829: if (list == null)
0830: return null;
0831: if (list.size() == 1)
0832: return (Scaffolding) list.get(0);
0833: return null;
0834: }
0835:
0836: List getCellAttachments(Id cellId) {
0837: return this .getHibernateTemplate().find(
0838: "from Attachment attachment where attachment.cell=?",
0839: cellId.getValue());
0840: }
0841:
0842: public Attachment getAttachment(Id attachmentId) {
0843: return (Attachment) this .getHibernateTemplate().load(
0844: Attachment.class, attachmentId);
0845: }
0846:
0847: public Set getPageForms(WizardPage page) {
0848: Set result = new HashSet();
0849: Set removes = new HashSet();
0850: if (page.getPageForms() != null) {
0851: for (Iterator iter = page.getPageForms().iterator(); iter
0852: .hasNext();) {
0853: WizardPageForm wpf = (WizardPageForm) iter.next();
0854: Node node = getNode(wpf.getArtifactId(), page);
0855: if (node != null) {
0856: result.add(node);
0857: } else {
0858: //logger.warn("Cell contains stale artifact references (null node encountered) for Cell: " + cell.getId().getValue() + ". Detaching");
0859: //detachArtifact(cell.getId(),attachment.getArtifactId());
0860: removes.add(wpf.getArtifactId());
0861: }
0862: }
0863: for (Iterator iter2 = removes.iterator(); iter2.hasNext();) {
0864: Id id = (Id) iter2.next();
0865: logger
0866: .warn("Cell contains stale form references (null node encountered) for Cell: "
0867: + page.getId().getValue()
0868: + ". Detaching");
0869: detachForm(page.getId(), id);
0870: }
0871: }
0872: return result;
0873: }
0874:
0875: public Set getPageContents(WizardPage page) {
0876: Set result = new HashSet();
0877: Set removes = new HashSet();
0878: if (page.getAttachments() != null) {
0879: for (Iterator iter = page.getAttachments().iterator(); iter
0880: .hasNext();) {
0881: Attachment attachment = (Attachment) iter.next();
0882: Node node = getNode(attachment.getArtifactId(), page);
0883: if (node != null) {
0884: result.add(node);
0885: } else {
0886: //logger.warn("Cell contains stale artifact references (null node encountered) for Cell: " + cell.getId().getValue() + ". Detaching");
0887: //detachArtifact(cell.getId(),attachment.getArtifactId());
0888: removes.add(attachment.getArtifactId());
0889: }
0890: }
0891: for (Iterator iter2 = removes.iterator(); iter2.hasNext();) {
0892: Id id = (Id) iter2.next();
0893: logger
0894: .warn("Cell contains stale artifact references (null node encountered) for Cell: "
0895: + page.getId().getValue()
0896: + ". Detaching");
0897: detachArtifact(page.getId(), id);
0898: }
0899: }
0900: return result;
0901: }
0902:
0903: protected Node getNode(Id artifactId, WizardPage page) {
0904: Node node = getNode(artifactId);
0905: if (node == null) {
0906: return null;
0907: }
0908: String siteId = page.getPageDefinition().getSiteId();
0909: ContentResource wrapped = new ContentEntityWrapper(node
0910: .getResource(), buildRef(siteId, page.getId()
0911: .getValue(), node.getResource()));
0912:
0913: return new Node(artifactId, wrapped, node
0914: .getTechnicalMetadata().getOwner());
0915: }
0916:
0917: public Node getNode(Id artifactId) {
0918: String id = getContentHosting().resolveUuid(
0919: artifactId.getValue());
0920: if (id == null) {
0921: return null;
0922: }
0923:
0924: getSecurityService().pushAdvisor(
0925: new AllowMapSecurityAdvisor(
0926: ContentHostingService.EVENT_RESOURCE_READ,
0927: getContentHosting().getReference(id)));
0928:
0929: try {
0930: ContentResource resource = getContentHosting().getResource(
0931: id);
0932: String ownerId = resource.getProperties().getProperty(
0933: resource.getProperties().getNamePropCreator());
0934: Agent owner = getAgentFromId(getIdManager().getId(ownerId));
0935:
0936: return new Node(artifactId, resource, owner);
0937: } catch (PermissionException e) {
0938: logger.error("", e);
0939: throw new RuntimeException(e);
0940: } catch (IdUnusedException e) {
0941: logger.error("", e);
0942: throw new RuntimeException(e);
0943: } catch (TypeException e) {
0944: logger.error("", e);
0945: throw new RuntimeException(e);
0946: }
0947: }
0948:
0949: public Node getNode(Reference ref) {
0950: String nodeId = getContentHosting().getUuid(ref.getId());
0951:
0952: return getNode(getIdManager().getId(nodeId));
0953: }
0954:
0955: /*
0956: public List getPageArtifacts(WizardPage page)
0957: {
0958: List nodeList = new ArrayList();
0959: Set attachments = page.getAttachments();
0960:
0961: for (Iterator attachmentIterator = attachments.iterator(); attachmentIterator.hasNext();) {
0962: Attachment att = (Attachment)attachmentIterator.next();
0963: //TODO is it okay to clear the whole thing here?
0964: getHibernateTemplate().clear();
0965:
0966: Node node = getNode(att.getArtifactId(), page);
0967: if (node != null) {
0968: nodeList.add(node);
0969: } else
0970: logger.warn("Cell contains stale artifact references (null node encountered) for Cell: " + page.getId());
0971:
0972: }
0973: return nodeList;
0974: }
0975: */
0976: public List getCellsByArtifact(Id artifactId) {
0977: //return this.getHibernateTemplate().find("select distinct attachment.cell from Attachment attachment where attachment.artifactId=?", artifactId.getValue());
0978: //this.getHibernateTemplate().find
0979: Criteria c = null;
0980: try {
0981: c = this .getSession().createCriteria(Cell.class);
0982: c.setFetchMode("scaffoldingCell", FetchMode.JOIN);
0983: c.setFetchMode("scaffoldingCell.scaffolding",
0984: FetchMode.JOIN);
0985: //c.add(Expression.eq("artifactId", artifactId));
0986: Criteria att = c.createCriteria("attachments");
0987: att.add(Expression.eq("artifactId", artifactId));
0988:
0989: return new ArrayList(c.list());
0990: } catch (DataAccessResourceFailureException e) {
0991: logger.error("", e);
0992: } catch (HibernateException e) {
0993: logger.error("", e);
0994: } catch (IllegalStateException e) {
0995: logger.error("", e);
0996: }
0997: return new ArrayList();
0998: }
0999:
1000: public List getCellsByForm(Id formId) {
1001: //return this.getHibernateTemplate().find("select distinct attachment.cell from Attachment attachment where attachment.artifactId=?", artifactId.getValue());
1002: //this.getHibernateTemplate().find
1003: Criteria c = null;
1004: try {
1005: c = this .getSession().createCriteria(Cell.class);
1006: c.setFetchMode("scaffoldingCell", FetchMode.JOIN);
1007: c.setFetchMode("scaffoldingCell.scaffolding",
1008: FetchMode.JOIN);
1009: //c.add(Expression.eq("artifactId", artifactId));
1010: Criteria att = c.createCriteria("pageForms");
1011: att.add(Expression.eq("artifactId", formId));
1012:
1013: return new ArrayList(c.list());
1014: } catch (DataAccessResourceFailureException e) {
1015: logger.error("", e);
1016: } catch (HibernateException e) {
1017: logger.error("", e);
1018: } catch (IllegalStateException e) {
1019: logger.error("", e);
1020: }
1021: return new ArrayList();
1022: }
1023:
1024: protected Agent getAgentFromId(Id agentId) {
1025: return agentManager.getAgent(agentId);
1026: }
1027:
1028: /**
1029: * @return Returns the idManager.
1030: */
1031: public IdManager getIdManager() {
1032: return idManager;
1033: }
1034:
1035: /**
1036: * @param idManager The idManager to set.
1037: */
1038: public void setIdManager(IdManager idManager) {
1039: this .idManager = idManager;
1040: }
1041:
1042: /**
1043: * @return Returns the authManager.
1044: */
1045: public AuthenticationManager getAuthnManager() {
1046: return authnManager;
1047: }
1048:
1049: /**
1050: * @param authnManager The authnManager to set.
1051: */
1052: public void setAuthnManager(AuthenticationManager authnManager) {
1053: this .authnManager = authnManager;
1054: }
1055:
1056: /**
1057: * @return Returns the authzManager.
1058: */
1059: public AuthorizationFacade getAuthzManager() {
1060: return authzManager;
1061: }
1062:
1063: /**
1064: * @param authzManager The authzManager to set.
1065: */
1066: public void setAuthzManager(AuthorizationFacade authzManager) {
1067: this .authzManager = authzManager;
1068: }
1069:
1070: /**
1071: * @return Returns the agentManager.
1072: */
1073: public AgentManager getAgentManager() {
1074: return agentManager;
1075: }
1076:
1077: /**
1078: * @param agentManager The agentManager to set.
1079: */
1080: public void setAgentManager(AgentManager agentManager) {
1081: this .agentManager = agentManager;
1082: }
1083:
1084: /* (non-Javadoc)
1085: * @see org.theospi.portfolio.matrix.model.hibernate.impl.MatrixManager#deleteMatrix(org.theospi.portfolio.shared.model.Id)
1086: */
1087: public void deleteMatrix(Id matrixId) {
1088: Matrix matrix = getMatrix(matrixId);
1089: Set cells = matrix.getCells();
1090:
1091: // first unlock all resources associated with this matrix
1092: for (Iterator cellIt = cells.iterator(); cellIt.hasNext();) {
1093: Cell cell = (Cell) cellIt.next();
1094: WizardPage page = cell.getWizardPage();
1095:
1096: for (Iterator iter = page.getAttachments().iterator(); iter
1097: .hasNext();) {
1098: Attachment att = (Attachment) iter.next();
1099: getLockManager().removeLock(
1100: att.getArtifactId().getValue(),
1101: page.getId().getValue());
1102: }
1103:
1104: for (Iterator iter = page.getPageForms().iterator(); iter
1105: .hasNext();) {
1106: WizardPageForm pageForm = (WizardPageForm) iter.next();
1107: getLockManager().removeLock(
1108: pageForm.getArtifactId().getValue(),
1109: page.getId().getValue());
1110: }
1111:
1112: List reviews = getReviewManager().getReviewsByParent(
1113: page.getId().getValue(),
1114: page.getPageDefinition().getSiteId(),
1115: MatrixContentEntityProducer.MATRIX_PRODUCER);
1116: for (Iterator iter = reviews.iterator(); iter.hasNext();) {
1117: Review review = (Review) iter.next();
1118: getLockManager().removeLock(
1119: review.getReviewContent().getValue(),
1120: page.getId().getValue());
1121: }
1122: }
1123:
1124: // Now delete matrix
1125: this .getHibernateTemplate().delete(getMatrix(matrixId));
1126: }
1127:
1128: public void deleteScaffolding(Id scaffoldingId) {
1129: this .getHibernateTemplate().delete(
1130: getScaffolding(scaffoldingId));
1131: }
1132:
1133: public Cell submitCellForEvaluation(Cell cell) {
1134: Date now = new Date(System.currentTimeMillis());
1135: getHibernateTemplate().refresh(cell); //TODO not sure if this is necessary
1136: ScaffoldingCell sCell = cell.getScaffoldingCell();
1137: WizardPage page = cell.getWizardPage();
1138:
1139: // Actions for current cell
1140: processContentLockingWorkflow(true, page);
1141: processStatusChangeWorkflow(
1142: MatrixFunctionConstants.PENDING_STATUS, page);
1143: cell.getWizardPage().setModified(now);
1144:
1145: if (sCell.getScaffolding().getWorkflowOption() > 0)
1146: processWorkflow(sCell.getScaffolding().getWorkflowOption(),
1147: cell.getId());
1148:
1149: return cell;
1150: }
1151:
1152: public WizardPage submitPageForEvaluation(WizardPage page) {
1153: Date now = new Date(System.currentTimeMillis());
1154:
1155: WizardPage thePage = getWizardPage(page.getId());
1156: getHibernateTemplate().refresh(thePage); //TODO not sure if this is necessary
1157:
1158: processContentLockingWorkflow(true, thePage);
1159:
1160: thePage.setStatus(MatrixFunctionConstants.PENDING_STATUS);
1161: thePage.setModified(now);
1162: getHibernateTemplate().merge(thePage);
1163:
1164: return page;
1165: }
1166:
1167: protected List getEvaluatableCells(Agent agent, Agent role,
1168: Id worksiteId) {
1169: List returned = this
1170: .getHibernateTemplate()
1171: .find(
1172: "select distinct new "
1173: + "org.theospi.portfolio.matrix.model.EvaluationContentWrapperForMatrixCell("
1174: + "wp.id, "
1175: + "wp.pageDefinition.title, c.matrix.owner, "
1176: + "c.wizardPage.modified, wp.pageDefinition.siteId) "
1177: + "from WizardPage wp, Authorization auth, Cell c "
1178: + "where wp.pageDefinition.id = auth.qualifier "
1179: + "and wp.id = c.wizardPage.id "
1180: + "and auth.function = ? and wp.status = ? and (auth.agent=? "
1181: + " or auth.agent=?) "
1182: + " and wp.pageDefinition.siteId=?",
1183: new Object[] {
1184: MatrixFunctionConstants.EVALUATE_MATRIX,
1185: MatrixFunctionConstants.PENDING_STATUS,
1186: agent, role, worksiteId.getValue() });
1187:
1188: return returned;
1189: }
1190:
1191: public List getEvaluatableWizardPages(Agent agent, Agent role,
1192: Id worksiteId) {
1193: List wizardPages = this
1194: .getHibernateTemplate()
1195: .find(
1196: "select distinct new "
1197: + "org.theospi.portfolio.wizard.model.EvaluationContentWrapperForWizardPage("
1198: + "cwp.wizardPage.id, "
1199: + "cwp.wizardPage.pageDefinition.title, cwp.category.wizard.owner, "
1200: + "cwp.wizardPage.modified, "
1201: + "cwp.category.wizard.wizard.type, cwp.wizardPage.pageDefinition.siteId) "
1202: + "from CompletedWizardPage cwp, "
1203: + "Authorization auth "
1204: + "where cwp.wizardPage.pageDefinition.id = auth.qualifier "
1205: + "and auth.function = ? and cwp.wizardPage.status = ? and (auth.agent=? "
1206: + " or auth.agent=?) "
1207: + " and cwp.wizardPage.pageDefinition.siteId=?",
1208: new Object[] {
1209: MatrixFunctionConstants.EVALUATE_MATRIX,
1210: MatrixFunctionConstants.PENDING_STATUS,
1211: agent, role, worksiteId.getValue() });
1212:
1213: return wizardPages;
1214: }
1215:
1216: protected List getEvaluatableWizards(Agent agent, Agent role,
1217: Id worksiteId) {
1218:
1219: List wizards = this
1220: .getHibernateTemplate()
1221: .find(
1222: "select distinct new "
1223: + "org.theospi.portfolio.wizard.model.EvaluationContentWrapperForWizard("
1224: + "cw.wizard.id, "
1225: + "cw.wizard.name, cw.owner, "
1226: + "cw.created, cw.wizard.siteId) "
1227: + "from CompletedWizard cw, "
1228: + "Authorization auth "
1229: + "where cw.wizard.id = auth.qualifier "
1230: + "and auth.function = ? and cw.status = ? and (auth.agent=? "
1231: + " or auth.agent=?) "
1232: + " and cw.wizard.siteId=?",
1233: new Object[] {
1234: WizardFunctionConstants.EVALUATE_WIZARD,
1235: MatrixFunctionConstants.PENDING_STATUS,
1236: agent, role, worksiteId.getValue() });
1237: return wizards;
1238: }
1239:
1240: public List getEvaluatableItems(Agent agent) {
1241: //get all sites
1242: List allEvals = new ArrayList();
1243: List sites = getWorksiteManager().getUserSites();
1244: for (Iterator i = sites.iterator(); i.hasNext();) {
1245: Site site = (Site) i.next();
1246: allEvals.addAll(getEvaluatableItems(agent, idManager
1247: .getId(site.getId())));
1248: }
1249:
1250: return allEvals;
1251: }
1252:
1253: /**
1254: * {@inheritDoc}
1255: */
1256: public List getEvaluatableItems(Agent agent, Id worksiteId) {
1257: List roles = agent.getWorksiteRoles(worksiteId.getValue());
1258: Agent role = null;
1259: if (roles.size() > 0)
1260: role = (Agent) roles.get(0);
1261:
1262: List returned = getEvaluatableCells(agent, role, worksiteId);
1263: List wizardPages = getEvaluatableWizardPages(agent, role,
1264: worksiteId);
1265: List wizards = getEvaluatableWizards(agent, role, worksiteId);
1266:
1267: returned.addAll(wizardPages);
1268: returned.addAll(wizards);
1269:
1270: return returned;
1271: }
1272:
1273: public void packageScffoldingForExport(Id scaffoldingId,
1274: OutputStream os) throws IOException {
1275: Scaffolding oldScaffolding = this
1276: .getScaffoldingForExport(scaffoldingId); //, true);
1277:
1278: CheckedOutputStream checksum = new CheckedOutputStream(os,
1279: new Adler32());
1280: ZipOutputStream zos = new ZipOutputStream(
1281: new BufferedOutputStream(checksum));
1282:
1283: List levels = oldScaffolding.getLevels();
1284: List criteria = oldScaffolding.getCriteria();
1285: Set scaffoldingCells = oldScaffolding.getScaffoldingCells();
1286: List guidanceIds = new ArrayList();
1287: Set styleIds = new HashSet();
1288: List formIds = new ArrayList();
1289:
1290: levels.size();
1291: criteria.size();
1292: scaffoldingCells.size();
1293: for (Iterator iter = scaffoldingCells.iterator(); iter
1294: .hasNext();) {
1295: ScaffoldingCell sCell = (ScaffoldingCell) iter.next();
1296: Collection evalWorkflows = sCell.getWizardPageDefinition()
1297: .getEvalWorkflows();
1298: for (Iterator iter2 = evalWorkflows.iterator(); iter2
1299: .hasNext();) {
1300: Workflow wf = (Workflow) iter2.next();
1301: wf.getItems().size();
1302: }
1303: }
1304: removeFromSession(oldScaffolding);
1305:
1306: if (oldScaffolding.getStyle() != null) {
1307: styleIds.add(oldScaffolding.getStyle().getId().getValue());
1308: }
1309:
1310: for (Iterator iter = scaffoldingCells.iterator(); iter
1311: .hasNext();) {
1312: ScaffoldingCell sCell = (ScaffoldingCell) iter.next();
1313: sCell.setCells(new HashSet());
1314: Collection evaluators = sCell.getEvaluators();
1315: sCell.setEvaluators(new HashSet(evaluators));
1316:
1317: sCell.getWizardPageDefinition().setPages(new HashSet());
1318:
1319: Collection forms = sCell.getWizardPageDefinition()
1320: .getAdditionalForms();
1321: sCell.getWizardPageDefinition().setAdditionalForms(
1322: new ArrayList(forms));
1323:
1324: Collection evalWorkflows = sCell.getWizardPageDefinition()
1325: .getEvalWorkflows();
1326: for (Iterator iter2 = evalWorkflows.iterator(); iter2
1327: .hasNext();) {
1328: Workflow wf = (Workflow) iter2.next();
1329: Collection items = wf.getItems();
1330: wf.setItems(new HashSet(items));
1331: }
1332: sCell.getWizardPageDefinition().setEvalWorkflows(
1333: new HashSet(evalWorkflows));
1334: exportCellForms(zos, sCell, formIds);
1335: if (sCell.getGuidance() != null) {
1336: guidanceIds.add(sCell.getGuidance().getId().getValue());
1337: }
1338: if (sCell.getWizardPageDefinition().getStyle() != null) {
1339: styleIds.add(sCell.getWizardPageDefinition().getStyle()
1340: .getId().getValue());
1341: }
1342: }
1343:
1344: if (guidanceIds.size() > 0) {
1345: exportGuidance(zos, guidanceIds);
1346: }
1347:
1348: if (styleIds.size() > 0) {
1349: exportStyle(zos, styleIds);
1350: }
1351:
1352: oldScaffolding.setLevels(new ArrayList(levels));
1353: oldScaffolding.setCriteria(new ArrayList(criteria));
1354: oldScaffolding
1355: .setScaffoldingCells(new HashSet(scaffoldingCells));
1356: oldScaffolding.setMatrix(new HashSet());
1357:
1358: removeFromSession(oldScaffolding);
1359:
1360: //Saving the agent is not necessary and causes a StackOverflowError when XMLEncoder tries
1361: // to serialize. So, we clear out the agents.
1362: oldScaffolding.setOwner(null);
1363: oldScaffolding.setPublishedBy(null);
1364:
1365: ByteArrayOutputStream bos = new ByteArrayOutputStream();
1366: XMLEncoder xenc = new XMLEncoder(bos);
1367: xenc.writeObject(oldScaffolding);
1368: xenc.close();
1369:
1370: removeFromSession(oldScaffolding);
1371:
1372: storeFileInZip(zos,
1373: new ByteArrayInputStream(bos.toByteArray()),
1374: "scaffolding");
1375: this .getHibernateTemplate().clear();
1376: try {
1377: this .getHibernateTemplate().flush();
1378: } catch (AssertionFailure af) {
1379: //TODO There's got to be a better way to catch/prevent this error
1380: logger
1381: .warn("Catching AssertionFailure from Hibernate during a flush");
1382: this .getSession().clear();
1383: }
1384: bos.close();
1385:
1386: zos.finish();
1387: zos.flush();
1388: }
1389:
1390: protected void exportGuidance(ZipOutputStream zos, List guidanceIds)
1391: throws IOException {
1392: ZipEntry newfileEntry = new ZipEntry("guidance/guidanceList");
1393: zos.putNextEntry(newfileEntry);
1394: getGuidanceManager().packageGuidanceForExport(guidanceIds, zos);
1395: zos.closeEntry();
1396: }
1397:
1398: protected void exportStyle(ZipOutputStream zos, Set styleIds)
1399: throws IOException {
1400:
1401: ZipEntry newfileEntry = new ZipEntry("style/styleList");
1402: zos.putNextEntry(newfileEntry);
1403: getStyleManager().packageStyleForExport(styleIds, zos);
1404: zos.closeEntry();
1405: }
1406:
1407: protected void exportCellForms(ZipOutputStream zos,
1408: ScaffoldingCell cell, List formIds) throws IOException {
1409: List forms = cell.getAdditionalForms();
1410: for (Iterator i = forms.iterator(); i.hasNext();) {
1411: String formId = (String) i.next();
1412: if (!formIds.contains(formId)) {
1413: storeFormInZip(zos, formId);
1414: formIds.add(formId);
1415: }
1416: }
1417:
1418: if (cell.getEvaluationDevice() != null) {
1419: String evalDevId = cell.getEvaluationDevice().getValue();
1420: if (!formIds.contains(evalDevId)) {
1421: storeFormInZip(zos, evalDevId);
1422: formIds.add(evalDevId);
1423: }
1424: }
1425:
1426: if (cell.getReflectionDevice() != null) {
1427: String reflDevId = cell.getReflectionDevice().getValue();
1428: if (!formIds.contains(reflDevId)) {
1429: storeFormInZip(zos, reflDevId);
1430: formIds.add(reflDevId);
1431: }
1432: }
1433:
1434: if (cell.getReviewDevice() != null) {
1435: String revDevId = cell.getReviewDevice().getValue();
1436: if (!formIds.contains(revDevId)) {
1437: storeFormInZip(zos, revDevId);
1438: formIds.add(revDevId);
1439: }
1440: }
1441: }
1442:
1443: protected void fixPageForms(WizardPageDefinition wizardPage,
1444: Map formsMap) {
1445: List forms = wizardPage.getAdditionalForms();
1446: List newForms = new ArrayList();
1447: for (Iterator i = forms.iterator(); i.hasNext();) {
1448: String formId = (String) i.next();
1449: newForms.add(formsMap.get(formId));
1450: }
1451: wizardPage.setAdditionalForms(newForms);
1452:
1453: if (wizardPage.getEvaluationDevice() != null) {
1454: wizardPage.setEvaluationDevice(getIdManager().getId(
1455: (String) formsMap.get(wizardPage
1456: .getEvaluationDevice().getValue())));
1457: }
1458:
1459: if (wizardPage.getReflectionDevice() != null) {
1460: wizardPage.setReflectionDevice(getIdManager().getId(
1461: (String) formsMap.get(wizardPage
1462: .getReflectionDevice().getValue())));
1463: }
1464:
1465: if (wizardPage.getReviewDevice() != null) {
1466: wizardPage.setReviewDevice(getIdManager().getId(
1467: (String) formsMap.get(wizardPage.getReviewDevice()
1468: .getValue())));
1469: }
1470: }
1471:
1472: protected void storeFormInZip(ZipOutputStream zos, String formId)
1473: throws IOException {
1474:
1475: ZipEntry newfileEntry = new ZipEntry("forms/" + formId
1476: + ".form");
1477:
1478: zos.putNextEntry(newfileEntry);
1479:
1480: getStructuredArtifactDefinitionManager().packageFormForExport(
1481: formId, zos, false);
1482:
1483: zos.closeEntry();
1484: }
1485:
1486: protected void storeScaffoldingFile(ZipOutputStream zos, Id fileId)
1487: throws IOException {
1488: if (fileId == null) {
1489: return;
1490: }
1491:
1492: Node oldNode = getNode(fileId);
1493:
1494: String newName = oldNode.getName();
1495:
1496: storeFileInZip(zos, oldNode.getInputStream(), oldNode
1497: .getMimeType().getValue()
1498: + File.separator
1499: + fileId.getValue()
1500: + File.separator
1501: + newName);
1502: }
1503:
1504: protected void storeFileInZip(ZipOutputStream zos, InputStream in,
1505: String entryName) throws IOException {
1506:
1507: byte data[] = new byte[1024 * 10];
1508:
1509: if (File.separatorChar == '\\') {
1510: entryName = entryName.replace('\\', '/');
1511: }
1512:
1513: ZipEntry newfileEntry = new ZipEntry(entryName);
1514:
1515: zos.putNextEntry(newfileEntry);
1516:
1517: BufferedInputStream origin = new BufferedInputStream(in,
1518: data.length);
1519:
1520: int count;
1521: while ((count = origin.read(data, 0, data.length)) != -1) {
1522: zos.write(data, 0, count);
1523: }
1524: zos.closeEntry();
1525: in.close();
1526: }
1527:
1528: /*
1529: public Scaffolding uploadScaffolding(String scaffoldingFileName,
1530: String siteId, InputStream zipFileStream) throws IOException {
1531: try {
1532: return uploadScaffolding(scaffoldingFileName, SiteService.findTool(toolId).getId(), zipFileStream);
1533: }
1534: catch (InvalidUploadException exp) {
1535: throw exp;
1536: }
1537: catch (Exception exp) {
1538: throw new InvalidUploadException("Invalid scaffolding file.", exp, "uploadedScaffolding");
1539: }
1540: }
1541: */
1542:
1543: /**
1544: * This unpacks a zipped scaffolding and places it into the siteId. It saves the guidance, styles,
1545: * and forms, resets the ids, and saves the scaffolding. It returns the new unpacked scaffolding.
1546: *
1547: * The owner becomes the current agent.
1548: *
1549: * @param siteId String of the site id
1550: * @param zis ZipInputStream of the packed scaffolding
1551: * @throws IOException
1552: */
1553: protected Scaffolding uploadScaffolding(String siteId,
1554: ZipInputStream zis) throws IOException {
1555:
1556: ZipEntry currentEntry = zis.getNextEntry();
1557: Hashtable fileMap = new Hashtable();
1558: Scaffolding scaffolding = null;
1559:
1560: String tempDirName = getIdManager().createId().getValue();
1561:
1562: boolean itWorked = false;
1563:
1564: Map formsMap = new Hashtable();
1565: Map guidanceMap = null;
1566: Map styleMap = null;
1567:
1568: try {
1569: ContentCollectionEdit fileParent = getFileDir(tempDirName);
1570: boolean gotFile = false;
1571: while (currentEntry != null) {
1572: logger.debug("current entry name: "
1573: + currentEntry.getName());
1574:
1575: if (currentEntry.getName().equals("scaffolding")) {
1576: try {
1577: scaffolding = processScaffolding(zis);
1578: } catch (ClassNotFoundException e) {
1579: logger.error(
1580: "Class not found loading scaffolding",
1581: e);
1582: throw new OspException(e);
1583: }
1584: } else if (!currentEntry.isDirectory()) {
1585: if (currentEntry.getName().startsWith("forms/")) {
1586: processMatrixForm(currentEntry, zis, formsMap,
1587: getIdManager().getId(siteId));
1588: } else if (currentEntry.getName().equals(
1589: "guidance/guidanceList")) {
1590: gotFile = true;
1591: guidanceMap = processMatrixGuidance(fileParent,
1592: siteId, zis);
1593: } else if (currentEntry.getName().equals(
1594: "style/styleList")) {
1595: gotFile = true;
1596: styleMap = processMatrixStyle(fileParent,
1597: siteId, zis);
1598: }
1599: }
1600:
1601: zis.closeEntry();
1602: currentEntry = zis.getNextEntry();
1603: }
1604: if (scaffolding == null)
1605: throw new InvalidUploadException(
1606: "The scaffolding file was not found in the import file");
1607: scaffolding.setId(null);
1608: scaffolding.setPublished(false);
1609: scaffolding.setPublishedBy(null);
1610: scaffolding.setPublishedDate(null);
1611: scaffolding.setOwner(getAuthnManager().getAgent());
1612: scaffolding.setWorksiteId(getIdManager().getId(siteId));
1613:
1614: resetIds(scaffolding, guidanceMap, formsMap, styleMap,
1615: siteId);
1616:
1617: scaffolding = saveNewScaffolding(scaffolding);
1618:
1619: if (gotFile) {
1620: fileParent.getPropertiesEdit().addProperty(
1621: ResourceProperties.PROP_DISPLAY_NAME,
1622: scaffolding.getTitle());
1623: getContentHosting().commitCollection(fileParent);
1624: } else {
1625: getContentHosting().cancelCollection(fileParent);
1626: }
1627:
1628: scaffolding = storeScaffolding(scaffolding);
1629:
1630: createEvaluatorAuthzForImport(scaffolding);
1631:
1632: itWorked = true;
1633: return scaffolding;
1634: } catch (Exception exp) {
1635: throw new RuntimeException(exp);
1636: } finally {
1637: try {
1638: zis.closeEntry();
1639: } catch (IOException e) {
1640: logger.error("", e);
1641: }
1642: }
1643: }
1644:
1645: public Scaffolding uploadScaffolding(
1646: Reference uploadedScaffoldingFile, String siteId)
1647: throws IOException {
1648: Node file = getNode(uploadedScaffoldingFile);
1649:
1650: ZipInputStream zis = new UncloseableZipInputStream(file
1651: .getInputStream());
1652: return uploadScaffolding(siteId, zis);
1653:
1654: }
1655:
1656: protected Map processMatrixGuidance(ContentCollection parent,
1657: String siteId, ZipInputStream zis) throws IOException {
1658: return getGuidanceManager().importGuidanceList(parent, siteId,
1659: zis);
1660: }
1661:
1662: protected Map processMatrixStyle(ContentCollection parent,
1663: String siteId, ZipInputStream zis) throws IOException {
1664: return getStyleManager().importStyleList(parent, siteId, zis);
1665: }
1666:
1667: protected void processMatrixForm(ZipEntry currentEntry,
1668: ZipInputStream zis, Map formMap, Id worksite)
1669: throws IOException {
1670: File file = new File(currentEntry.getName());
1671: String fileName = file.getName();
1672: String oldId = fileName.substring(0, fileName.indexOf(".form"));
1673:
1674: StructuredArtifactDefinitionBean bean;
1675:
1676: try {
1677: //we want the bean even if it exists already
1678: bean = getStructuredArtifactDefinitionManager().importSad(
1679: worksite, zis, true, false, false);
1680: } catch (ImportException ie) {
1681: throw new RuntimeException(
1682: "the structured artifact failed to import", ie);
1683: }
1684:
1685: formMap.put(oldId, bean.getId().getValue());
1686: }
1687:
1688: public void checkPageAccess(String id) {
1689: Id pageId = getIdManager().getId(id);
1690: WizardPage page = getWizardPage(pageId);
1691: // todo need to figure out matrix or wizard authz stuff here
1692:
1693: // this should set the security advisor for the attached artifacts.
1694: //getPageArtifacts(page);
1695: boolean canEval = getAuthzManager().isAuthorized(
1696: MatrixFunctionConstants.EVALUATE_MATRIX,
1697: page.getPageDefinition().getId());
1698: boolean canReview = getAuthzManager().isAuthorized(
1699: MatrixFunctionConstants.REVIEW_MATRIX,
1700: getIdManager().getId(
1701: page.getPageDefinition().getSiteId()));
1702:
1703: if (!canReview) {
1704: canReview = getAuthzManager().isAuthorized(
1705: WizardFunctionConstants.REVIEW_WIZARD,
1706: getIdManager().getId(
1707: page.getPageDefinition().getSiteId()));
1708: }
1709:
1710: boolean owns = page.getOwner().getId().equals(
1711: getAuthnManager().getAgent().getId());
1712:
1713: if (canEval || canReview || owns) {
1714: //can I look at files? - own, review or eval
1715: getPageContents(page);
1716:
1717: //can I look at forms? - own, review or eval
1718: getPageForms(page);
1719:
1720: //can I look at reviews/evals/reflections? - own, review or eval
1721: getReviewManager().getReviewsByParentAndType(id,
1722: Review.REFLECTION_TYPE,
1723: page.getPageDefinition().getSiteId(),
1724: MatrixContentEntityProducer.MATRIX_PRODUCER);
1725: }
1726:
1727: if (canEval || owns) {
1728: //can I look at reviews/evals/reflections? - own or eval
1729: getReviewManager().getReviewsByParentAndType(id,
1730: Review.EVALUATION_TYPE,
1731: page.getPageDefinition().getSiteId(),
1732: MatrixContentEntityProducer.MATRIX_PRODUCER);
1733: }
1734:
1735: if (canEval || canReview || owns) {
1736: //can I look at reviews/evals/reflections? - own or review
1737: getReviewManager().getReviewsByParentAndType(id,
1738: Review.FEEDBACK_TYPE,
1739: page.getPageDefinition().getSiteId(),
1740: MatrixContentEntityProducer.MATRIX_PRODUCER);
1741: }
1742: }
1743:
1744: /**
1745: * this creates authorizations for each cell from the evaluators contained in the cell
1746: * @param scaffolding
1747: */
1748: private void createEvaluatorAuthzForImport(Scaffolding scaffolding) {
1749: for (Iterator iter = scaffolding.getScaffoldingCells()
1750: .iterator(); iter.hasNext();) {
1751: ScaffoldingCell sCell = (ScaffoldingCell) iter.next();
1752: Collection evals = sCell.getEvaluators();
1753: for (Iterator i = evals.iterator(); i.hasNext();) {
1754: Id id = (Id) i.next();
1755: if (id.getValue().startsWith("/site/")) {
1756: // it's a role
1757: String[] agentValues = id.getValue().split("/");
1758:
1759: String newStrId = id.getValue().replaceAll(
1760: agentValues[2],
1761: scaffolding.getWorksiteId().getValue());
1762: id = idManager.getId(newStrId);
1763: }
1764: Agent agent = this .getAgentFromId(id);
1765:
1766: if (agent != null && agent.getId() != null) {
1767: this .getAuthzManager().createAuthorization(agent,
1768: MatrixFunctionConstants.EVALUATE_MATRIX,
1769: sCell.getWizardPageDefinition().getId());
1770: }
1771: }
1772: }
1773: }
1774:
1775: /**
1776: * gets the current user's resource collection
1777: *
1778: * @return ContentCollection
1779: * @throws TypeException
1780: * @throws IdUnusedException
1781: * @throws PermissionException
1782: */
1783: protected ContentCollection getUserCollection()
1784: throws TypeException, IdUnusedException,
1785: PermissionException {
1786: User user = UserDirectoryService.getCurrentUser();
1787: String userId = user.getId();
1788: String wsId = SiteService.getUserSiteId(userId);
1789: String wsCollectionId = getContentHosting().getSiteCollection(
1790: wsId);
1791: ContentCollection collection = getContentHosting()
1792: .getCollection(wsCollectionId);
1793: return collection;
1794: }
1795:
1796: /**
1797: * This gets the directory in which the import places files into.
1798: *
1799: * This method gets the current users base collection, creates an imported directory,
1800: * then uses the param to create a new directory.
1801: *
1802: * this uses the bean property importFolderName to name the
1803: *
1804: * @param origName String
1805: * @return ContentCollectionEdit
1806: * @throws InconsistentException
1807: * @throws PermissionException
1808: * @throws IdUsedException
1809: * @throws IdInvalidException
1810: * @throws IdUnusedException
1811: * @throws TypeException
1812: */
1813: protected ContentCollectionEdit getFileDir(String origName)
1814: throws InconsistentException, PermissionException,
1815: IdUsedException, IdInvalidException, IdUnusedException,
1816: TypeException {
1817: ContentCollection userCollection = getUserCollection();
1818:
1819: try {
1820: //TODO use the bean org.theospi.portfolio.admin.model.IntegrationOption.siteOption
1821: // in common/components to get the name and id for this site.
1822:
1823: ContentCollectionEdit groupCollection = getContentHosting()
1824: .addCollection(
1825: userCollection.getId()
1826: + IMPORT_BASE_FOLDER_ID);
1827: groupCollection.getPropertiesEdit().addProperty(
1828: ResourceProperties.PROP_DISPLAY_NAME,
1829: getImportFolderName());
1830: getContentHosting().commitCollection(groupCollection);
1831: } catch (IdUsedException e) {
1832: // ignore... it is already there.
1833: if (logger.isDebugEnabled()) {
1834: logger.debug(e);
1835: }
1836: } catch (Exception e) {
1837: throw new RuntimeException(e);
1838: }
1839:
1840: ContentCollection collection = getContentHosting()
1841: .getCollection(
1842: userCollection.getId() + IMPORT_BASE_FOLDER_ID
1843: + "/");
1844:
1845: String childId = collection.getId() + origName;
1846: return getContentHosting().addCollection(childId);
1847: }
1848:
1849: /**
1850: * This unpacks the scaffolding in a zip stream and returns it
1851: * @param zis
1852: * @return
1853: * @throws IOException
1854: * @throws ClassNotFoundException
1855: */
1856: protected Scaffolding processScaffolding(ZipInputStream zis)
1857: throws IOException, ClassNotFoundException {
1858: XMLDecoder dec = new XMLDecoder(zis);
1859: return (Scaffolding) dec.readObject();
1860: }
1861:
1862: protected void processFile(ZipEntry currentEntry,
1863: ZipInputStream zis, Hashtable fileMap,
1864: ContentCollection fileParent) throws IOException,
1865: InconsistentException, PermissionException,
1866: IdUsedException, IdInvalidException, OverQuotaException,
1867: ServerOverloadException {
1868: File file = new File(currentEntry.getName());
1869:
1870: MimeType mimeType = new MimeType(file.getParentFile()
1871: .getParentFile().getParentFile().getName(), file
1872: .getParentFile().getParentFile().getName());
1873:
1874: String contentType = mimeType.getValue();
1875:
1876: Id oldId = getIdManager().getId(file.getParentFile().getName());
1877:
1878: //Node newNode = fileParent.persistent().createFile(contentType, file.getName(), zis,
1879: //getFileHome().getType());
1880: ByteArrayOutputStream bos = new ByteArrayOutputStream();
1881: int c = zis.read();
1882:
1883: while (c != -1) {
1884: bos.write(c);
1885: c = zis.read();
1886: }
1887:
1888: String fileId = fileParent.getId() + file.getName();
1889: ContentResourceEdit resource = getContentHosting().addResource(
1890: fileId);
1891: ResourcePropertiesEdit resourceProperties = resource
1892: .getPropertiesEdit();
1893: resourceProperties.addProperty(
1894: ResourceProperties.PROP_DISPLAY_NAME, file.getName());
1895: resource.setContent(bos.toByteArray());
1896: resource.setContentType(contentType);
1897: getContentHosting().commitResource(resource);
1898:
1899: Id newId = getIdManager().getId(
1900: getContentHosting().getUuid(resource.getId()));
1901:
1902: fileMap.put(oldId, newId);
1903: }
1904:
1905: /**
1906: * resets the style, criteria, levels, and scaffolding cells
1907: * @param scaffolding
1908: * @param guidanceMap
1909: * @param formsMap
1910: * @param styleMap
1911: * @param siteId
1912: */
1913: protected void resetIds(Scaffolding scaffolding, Map guidanceMap,
1914: Map formsMap, Map styleMap, String siteId) {
1915:
1916: if (scaffolding.getStyle() != null) {
1917: if (styleMap != null) {
1918: scaffolding.setStyle((Style) styleMap.get(scaffolding
1919: .getStyle().getId().getValue()));
1920: } else {
1921: scaffolding.getStyle().setId(null);
1922: }
1923: }
1924:
1925: substituteCriteria(scaffolding);
1926: substituteLevels(scaffolding);
1927: substituteScaffoldingCells(scaffolding, guidanceMap, formsMap,
1928: styleMap, siteId);
1929: }
1930:
1931: protected void substituteCriteria(Scaffolding scaffolding) {
1932: List newCriteria = new ArrayList();
1933: for (Iterator i = scaffolding.getCriteria().iterator(); i
1934: .hasNext();) {
1935: Criterion criterion = (Criterion) i.next();
1936: criterion.setId(null);
1937: newCriteria.add(criterion);
1938: }
1939: scaffolding.setCriteria(newCriteria);
1940: }
1941:
1942: protected void substituteLevels(Scaffolding scaffolding) {
1943: List newLevels = new ArrayList();
1944: for (Iterator i = scaffolding.getLevels().iterator(); i
1945: .hasNext();) {
1946: Level level = (Level) i.next();
1947:
1948: level.setId(null);
1949: newLevels.add(level);
1950: }
1951: scaffolding.setLevels(newLevels);
1952: }
1953:
1954: protected void substituteScaffoldingCells(Scaffolding scaffolding,
1955: Map guidanceMap, Map formsMap, Map styleMap, String siteId) {
1956: Set sCells = new HashSet();
1957: for (Iterator iter = scaffolding.getScaffoldingCells()
1958: .iterator(); iter.hasNext();) {
1959: ScaffoldingCell scaffoldingCell = (ScaffoldingCell) iter
1960: .next();
1961: scaffoldingCell.setId(null);
1962:
1963: WizardPageDefinition wpd = scaffoldingCell
1964: .getWizardPageDefinition();
1965: wpd.setId(null);
1966: wpd.setSiteId(siteId);
1967: if (wpd.getGuidance() != null) {
1968: if (guidanceMap != null) {
1969: Guidance guidance = (Guidance) guidanceMap.get(wpd
1970: .getGuidance().getId().getValue());
1971: wpd.setNewId(getIdManager().createId());
1972: guidance.setSecurityQualifier(wpd.getNewId());
1973: wpd.setGuidance(guidance);
1974: } else {
1975: wpd.getGuidance().setId(null);
1976: }
1977: }
1978:
1979: if (wpd.getStyle() != null) {
1980: if (styleMap != null) {
1981: wpd.setStyle((Style) styleMap.get(wpd.getStyle()
1982: .getId().getValue()));
1983: } else {
1984: wpd.getStyle().setId(null);
1985: }
1986: }
1987:
1988: fixPageForms(wpd, formsMap);
1989:
1990: Set newWorkflows = new HashSet();
1991: for (Iterator jiter = wpd.getEvalWorkflows().iterator(); jiter
1992: .hasNext();) {
1993: Workflow w = (Workflow) jiter.next();
1994: w.setId(null);
1995: Set newItems = new HashSet();
1996: for (Iterator kiter = w.getItems().iterator(); kiter
1997: .hasNext();) {
1998: WorkflowItem wfi = (WorkflowItem) kiter.next();
1999: wfi.setId(null);
2000: newItems.add(wfi);
2001: }
2002:
2003: newWorkflows.add(w);
2004: }
2005:
2006: //scaffoldingCell.getCells().clear();
2007: scaffoldingCell.setCells(new HashSet());
2008: sCells.add(scaffoldingCell);
2009: //scaffoldingCell.setScaffolding(scaffolding);
2010: }
2011: scaffolding.setScaffoldingCells(sCells);
2012: }
2013:
2014: public void removeExposedMatrixTool(Scaffolding scaffolding) {
2015: String siteId = scaffolding.getWorksiteId().getValue();
2016: try {
2017: Site siteEdit = SiteService.getSite(siteId);
2018:
2019: SitePage page = siteEdit.getPage(scaffolding
2020: .getExposedPageId());
2021: siteEdit.removePage(page);
2022: SiteService.save(siteEdit);
2023: scaffolding.setExposedPageId(null);
2024: } catch (IdUnusedException e) {
2025: // TODO Auto-generated catch block
2026: e.printStackTrace();
2027: } catch (PermissionException e) {
2028: // TODO Auto-generated catch block
2029: e.printStackTrace();
2030: }
2031: }
2032:
2033: public void exposeMatrixTool(Scaffolding scaffolding) {
2034: //TODO add logging errors back
2035: String siteId = scaffolding.getWorksiteId().getValue();
2036: try {
2037: Site siteEdit = SiteService.getSite(siteId);
2038:
2039: SitePage page = siteEdit.addPage();
2040:
2041: page.setTitle(scaffolding.getTitle());
2042: page.setLayout(SitePage.LAYOUT_SINGLE_COL);
2043:
2044: ToolConfiguration tool = page.addTool();
2045:
2046: tool.setTool("osp.exposedmatrix", ToolManager
2047: .getTool("osp.exposedmatrix"));
2048: tool.setTitle(scaffolding.getTitle());
2049: tool.setLayoutHints("0,0");
2050: tool.getPlacementConfig().setProperty(
2051: MatrixManager.EXPOSED_MATRIX_KEY,
2052: scaffolding.getId().getValue());
2053:
2054: //LOG.info(this+": SiteService.commitEdit():" +siteId);
2055:
2056: SiteService.save(siteEdit);
2057: scaffolding.setExposedPageId(page.getId());
2058:
2059: } catch (IdUnusedException e) {
2060: // TODO Auto-generated catch block
2061: e.printStackTrace();
2062: } catch (PermissionException e) {
2063: // TODO Auto-generated catch block
2064: e.printStackTrace();
2065: }
2066: }
2067:
2068: private boolean findInAuthz(Id qualifier, Agent agent, List authzs) {
2069: for (Iterator iter = authzs.iterator(); iter.hasNext();) {
2070: Authorization authz = (Authorization) iter.next();
2071: // Same item, different agent
2072: if (!authz.getAgent().equals(agent)
2073: && authz.getQualifier().equals(qualifier))
2074: return true;
2075: }
2076: return false;
2077: }
2078:
2079: public boolean checkStyleConsumption(Id styleId) {
2080: //Check Scaffolding and WizardPageDef
2081: List scaffolding = getScaffoldingByStyle(styleId);
2082: if (scaffolding != null && !scaffolding.isEmpty()
2083: && scaffolding.size() > 0)
2084: return true;
2085:
2086: //Also check for WizardPageDef
2087: List wizPageDefs = this .getWizardPageDefByStyle(styleId);
2088: if (wizPageDefs != null && !wizPageDefs.isEmpty()
2089: && wizPageDefs.size() > 0)
2090: return true;
2091:
2092: return false;
2093: }
2094:
2095: /* (non-Javadoc)
2096: * @see org.theospi.portfolio.shared.mgt.ReadableObjectHome#getType()
2097: */
2098: public org.sakaiproject.metaobj.shared.model.Type getType() {
2099: return new org.sakaiproject.metaobj.shared.model.Type(idManager
2100: .getId("matrix"), "Matrix");
2101: //return getMatrices(null, null);
2102: }
2103:
2104: public String getExternalType() {
2105: return getType().getId().getValue();
2106: }
2107:
2108: /* (non-Javadoc)
2109: * @see org.theospi.portfolio.shared.mgt.ReadableObjectHome#load(org.theospi.portfolio.shared.model.Id)
2110: */
2111: public Artifact load(Id id) {
2112: Matrix matrix = getMatrix(id);
2113: loadMatrixCellReviews(matrix);
2114: matrix.setHome(this );
2115: return matrix;
2116: }
2117:
2118: private void loadMatrixCellReviews(Matrix matrix) {
2119: for (Iterator cells = matrix.getCells().iterator(); cells
2120: .hasNext();) {
2121: Cell cell = (Cell) cells.next();
2122: WizardPage page = cell.getWizardPage();
2123: List reflections = getReviewManager()
2124: .getReviewsByParentAndType(page.getId().getValue(),
2125: Review.REFLECTION_TYPE,
2126: page.getPageDefinition().getSiteId(),
2127: MatrixContentEntityProducer.MATRIX_PRODUCER);
2128: List evaluations = getReviewManager()
2129: .getReviewsByParentAndType(page.getId().getValue(),
2130: Review.EVALUATION_TYPE,
2131: page.getPageDefinition().getSiteId(),
2132: MatrixContentEntityProducer.MATRIX_PRODUCER);
2133: List feedback = getReviewManager()
2134: .getReviewsByParentAndType(page.getId().getValue(),
2135: Review.FEEDBACK_TYPE,
2136: page.getPageDefinition().getSiteId(),
2137: MatrixContentEntityProducer.MATRIX_PRODUCER);
2138:
2139: page.setReflections(reflections);
2140: page.setEvaluations(evaluations);
2141: page.setFeedback(feedback);
2142: page.getAttachments().size();
2143: page.getPageForms().size();
2144:
2145: //Make sure that the attachments and forms have been added to the security advisor
2146: getPageContents(page);
2147: getPageForms(page);
2148: }
2149: }
2150:
2151: public Collection findByType(String type) {
2152: return getHibernateTemplate().find("from Matrix");
2153: }
2154:
2155: public boolean getLoadArtifacts() {
2156: return loadArtifacts;
2157: }
2158:
2159: public void setLoadArtifacts(boolean loadArtifacts) {
2160: this .loadArtifacts = loadArtifacts;
2161: }
2162:
2163: /* (non-Javadoc)
2164: * @see org.theospi.portfolio.shared.mgt.ReadableObjectHome#createInstance()
2165: */
2166: public Artifact createInstance() {
2167: Artifact instance = new Matrix();
2168: prepareInstance(instance);
2169: return instance;
2170: }
2171:
2172: /* (non-Javadoc)
2173: * @see org.theospi.portfolio.shared.mgt.ReadableObjectHome#prepareInstance(org.theospi.portfolio.shared.model.Artifact)
2174: */
2175: public void prepareInstance(Artifact object) {
2176: object.setHome(this );
2177: //((Matrix) object).setAgentManager(getAgentManager());
2178:
2179: }
2180:
2181: /* (non-Javadoc)
2182: * @see org.theospi.portfolio.shared.mgt.ReadableObjectHome#createSample()
2183: */
2184: public Artifact createSample() {
2185: return createInstance();
2186: }
2187:
2188: /* (non-Javadoc)
2189: * @see org.theospi.portfolio.shared.mgt.ReadableObjectHome#findByOwner(org.theospi.portfolio.shared.model.Agent)
2190: */
2191: public Collection findByOwner(Agent owner) throws FinderException {
2192: return getMatrices(null, owner.getId());
2193: }
2194:
2195: /* (non-Javadoc)
2196: * @see org.theospi.portfolio.shared.mgt.ReadableObjectHome#isInstance(org.theospi.portfolio.shared.model.Artifact)
2197: */
2198: public boolean isInstance(Artifact testObject) {
2199: return (testObject instanceof Matrix);
2200: }
2201:
2202: /* (non-Javadoc)
2203: * @see org.theospi.portfolio.shared.mgt.ReadableObjectHome#refresh()
2204: */
2205: public void refresh() {
2206: // TODO Auto-generated method stub
2207:
2208: }
2209:
2210: public String getExternalUri(Id artifactId, String name) {
2211: throw new UnsupportedOperationException();
2212: }
2213:
2214: public InputStream getStream(Id artifactId) {
2215: throw new UnsupportedOperationException();
2216: }
2217:
2218: public boolean isSystemOnly() {
2219: return false;
2220: }
2221:
2222: public Class getInterface() {
2223: return this .getClass();
2224: }
2225:
2226: /* (non-Javadoc)
2227: * @see org.theospi.portfolio.repository.ArtifactFinder#findByOwnerAndType(org.theospi.portfolio.shared.model.Id, java.lang.String)
2228: */
2229: public Collection findByOwnerAndType(Id owner, String type) {
2230: return findByOwner(owner);
2231: }
2232:
2233: public Collection findByOwnerAndType(Id owner, String type,
2234: MimeType mimeType) {
2235: // not gonna find mime types
2236: return null;
2237: }
2238:
2239: /* (non-Javadoc)
2240: * @see org.theospi.portfolio.repository.ArtifactFinder#findByOwner(org.theospi.portfolio.shared.model.Id)
2241: */
2242: public Collection findByOwner(Id owner) {
2243: try {
2244: return this .findByOwner(agentManager.getAgent(owner));
2245: } catch (FinderException e) {
2246: // TODO Auto-generated catch block
2247: e.printStackTrace();
2248: return null;
2249: }
2250: }
2251:
2252: public Collection findByWorksiteAndType(Id worksiteId, String type) {
2253: //TODO implement this
2254: return new ArrayList();
2255: }
2256:
2257: public Collection findByWorksite(Id worksiteId) {
2258: //TODO implement this
2259: return new ArrayList();
2260: }
2261:
2262: public Element getArtifactAsXml(Artifact artifact) {
2263: return getXmlRenderer().getArtifactAsXml(artifact);
2264: }
2265:
2266: /**
2267: * @return Returns the worksiteManager.
2268: */
2269: public WorksiteManager getWorksiteManager() {
2270: return worksiteManager;
2271: }
2272:
2273: /**
2274: * @param worksiteManager The worksiteManager to set.
2275: */
2276: public void setWorksiteManager(WorksiteManager worksiteManager) {
2277: this .worksiteManager = worksiteManager;
2278: }
2279:
2280: public LockManager getLockManager() {
2281: return lockManager;
2282: }
2283:
2284: public void setLockManager(LockManager lockManager) {
2285: this .lockManager = lockManager;
2286: }
2287:
2288: /**
2289: * This is called by the download manager to package a scaffolding for download as zip
2290: * @param params Map of url parameters
2291: * @param out OutputStream to push the file
2292: */
2293: public String packageForDownload(Map params, OutputStream out)
2294: throws IOException {
2295: packageScffoldingForExport(getIdManager().getId(
2296: ((String[]) params.get(SCAFFOLDING_ID_TAG))[0]), out);
2297:
2298: //Blank filename for now -- no more dangerous, since the request is in the form of a filename
2299: return "";
2300: }
2301:
2302: /**
2303: * This is the method called when duplicating a site. It copies all published scaffolding
2304: * from the fromContext site id to the toContext site id
2305: * @param fromContext String from site id
2306: * @param toContext String to site id
2307: * @param resourceIds List
2308: */
2309: public void importResources(String fromContext, String toContext,
2310: List resourceIds) {
2311: ClassLoader currentLoader = Thread.currentThread()
2312: .getContextClassLoader();
2313: try {
2314: Thread.currentThread().setContextClassLoader(
2315: getClass().getClassLoader());
2316:
2317: List scaffolding = this
2318: .findPublishedScaffolding(fromContext);
2319: if (scaffolding == null) {
2320: return;
2321: }
2322:
2323: for (Iterator iter = scaffolding.iterator(); iter.hasNext();) {
2324: Scaffolding scaffold = (Scaffolding) iter.next();
2325: Id id = scaffold.getId();
2326:
2327: getHibernateTemplate().evict(scaffold);
2328:
2329: ByteArrayOutputStream bos = new ByteArrayOutputStream();
2330:
2331: packageScffoldingForExport(id, bos);
2332:
2333: InputStream is = new ByteArrayInputStream(bos
2334: .toByteArray());
2335: ZipInputStream zis = new UncloseableZipInputStream(is);
2336: bos = null;
2337:
2338: uploadScaffolding(toContext, zis);
2339: is = null;
2340: zis = null;
2341: }
2342: } catch (IOException e) {
2343: logger.error("", e);
2344: throw new OspException(e);
2345: } finally {
2346: Thread.currentThread().setContextClassLoader(currentLoader);
2347: }
2348:
2349: }
2350:
2351: public ContentHostingService getContentHosting() {
2352: return contentHosting;
2353: }
2354:
2355: public void setContentHosting(ContentHostingService contentHosting) {
2356: this .contentHosting = contentHosting;
2357: }
2358:
2359: public PresentableObjectHome getXmlRenderer() {
2360: return xmlRenderer;
2361: }
2362:
2363: public void setXmlRenderer(PresentableObjectHome xmlRenderer) {
2364: this .xmlRenderer = xmlRenderer;
2365: }
2366:
2367: public SecurityService getSecurityService() {
2368: return securityService;
2369: }
2370:
2371: public void setSecurityService(SecurityService securityService) {
2372: this .securityService = securityService;
2373: }
2374:
2375: public EntityContextFinder getContentFinder() {
2376: return contentFinder;
2377: }
2378:
2379: public void setContentFinder(EntityContextFinder contentFinder) {
2380: this .contentFinder = contentFinder;
2381: }
2382:
2383: protected String buildRef(String siteId, String contextId,
2384: ContentResource resource) {
2385: return ContentEntityUtil.getInstance().buildRef(
2386: MatrixContentEntityProducer.MATRIX_PRODUCER, siteId,
2387: contextId, resource.getReference());
2388: }
2389:
2390: public DefaultScaffoldingBean getDefaultScaffoldingBean() {
2391: return defaultScaffoldingBean;
2392: }
2393:
2394: public void setDefaultScaffoldingBean(
2395: DefaultScaffoldingBean defaultScaffoldingBean) {
2396: this .defaultScaffoldingBean = defaultScaffoldingBean;
2397: }
2398:
2399: public void processWorkflow(Id workflowId, Id pageId) {
2400: Workflow workflow = getWorkflowManager()
2401: .getWorkflow(workflowId);
2402: //Cell cell = getCellFromPage(pageId);
2403: WizardPage page = getWizardPage(pageId);
2404:
2405: Collection items = workflow.getItems();
2406: for (Iterator i = items.iterator(); i.hasNext();) {
2407: WorkflowItem wi = (WorkflowItem) i.next();
2408: //Cell actionCell = this.getMatrixCellByWizardPageDef(cell.getMatrix(),
2409: // wi.getActionObjectId());
2410: switch (wi.getActionType()) {
2411: // complete / return part 2
2412: case (WorkflowItem.STATUS_CHANGE_WORKFLOW):
2413: processStatusChangeWorkflow(wi, page);
2414: break;
2415:
2416: case (WorkflowItem.NOTIFICATION_WORKFLOW):
2417: processNotificationWorkflow(wi);
2418: break;
2419:
2420: // Return part 1
2421: case (WorkflowItem.CONTENT_LOCKING_WORKFLOW):
2422: processContentLockingWorkflow(wi, page);
2423: break;
2424: } // end processWorkflow
2425: } // end items.iterator
2426: storePage(page);
2427: } // end processWorkflow
2428:
2429: public void processWorkflow(int workflowOption, Id cellId) {
2430: Cell cell = getCell(cellId);
2431: WizardPage page = cell.getWizardPage();
2432: Date now = new Date(System.currentTimeMillis());
2433:
2434: //Actions for "next" cell
2435: if (workflowOption == Scaffolding.HORIZONTAL_PROGRESSION
2436: || workflowOption == Scaffolding.VERTICAL_PROGRESSION) {
2437:
2438: Cell actionCell = getNextCell(cell, workflowOption);
2439: //If action cell is null, that means we are at the end of the row/column and have no next cell.
2440: if (actionCell != null) {
2441: WizardPage actionPage = actionCell.getWizardPage();
2442: if (actionPage != null) {
2443: processContentLockingWorkflow(false, actionPage);
2444: processStatusChangeWorkflow(
2445: MatrixFunctionConstants.READY_STATUS,
2446: actionPage);
2447: page.setModified(now);
2448: }
2449: }
2450: }
2451: }
2452:
2453: /**
2454: * This method locks and unlocks the page file attachments, the additional filled in forms,
2455: * and the filled in reflection forms. There is other locking in the ReviewHelperController
2456: * which locks the feedback and evaluation.
2457: * @param lock boolean true locks the resources, false unlocks
2458: * @param page WizardPage of the content to lock
2459: */
2460: private void processContentLockingWorkflow(boolean lock,
2461: WizardPage page) {
2462: for (Iterator iter = page.getAttachments().iterator(); iter
2463: .hasNext();) {
2464: Attachment att = (Attachment) iter.next();
2465: if (lock) {
2466: getLockManager().lockObject(
2467: att.getArtifactId().getValue(),
2468: page.getId().getValue(),
2469: "Submitting cell, 4 eval", true);
2470: } else {
2471: getLockManager().removeLock(
2472: att.getArtifactId().getValue(),
2473: page.getId().getValue());
2474: }
2475: }
2476:
2477: //the expectations, additional forms
2478: for (Iterator iter = page.getPageForms().iterator(); iter
2479: .hasNext();) {
2480: WizardPageForm pageForm = (WizardPageForm) iter.next();
2481:
2482: if (lock) {
2483: getLockManager().lockObject(
2484: pageForm.getArtifactId().getValue(),
2485: page.getId().getValue(),
2486: "Submitting cell, 4 eval", true);
2487: } else {
2488: getLockManager().removeLock(
2489: pageForm.getArtifactId().getValue(),
2490: page.getId().getValue());
2491: }
2492: }
2493:
2494: //the reflections
2495: List reflections = getReviewManager()
2496: .getReviewsByParentAndType(page.getId().getValue(),
2497: Review.REFLECTION_TYPE,
2498: page.getPageDefinition().getSiteId(),
2499: MatrixContentEntityProducer.MATRIX_PRODUCER);
2500: for (Iterator iter = reflections.iterator(); iter.hasNext();) {
2501: Review review = (Review) iter.next();
2502:
2503: if (lock) {
2504: getLockManager().lockObject(
2505: review.getReviewContent().getValue(),
2506: page.getId().getValue(),
2507: "Submitting cell, 4 eval", true);
2508: } else {
2509: getLockManager().removeLock(
2510: review.getReviewContent().getValue(),
2511: page.getId().getValue());
2512: }
2513: }
2514: }
2515:
2516: private void processContentLockingWorkflow(WorkflowItem wi,
2517: WizardPage page) {
2518: processContentLockingWorkflow(wi.getActionValue().equals(
2519: WorkflowItem.CONTENT_LOCKING_LOCK), page);
2520: }
2521:
2522: private void processNotificationWorkflow(WorkflowItem wi) {
2523: // TODO implement
2524:
2525: }
2526:
2527: private void processStatusChangeWorkflow(String status,
2528: WizardPage page) {
2529: Date now = new Date(System.currentTimeMillis());
2530: page.setStatus(status);
2531: page.setModified(now);
2532: }
2533:
2534: private void processStatusChangeWorkflow(WorkflowItem wi,
2535: WizardPage page) {
2536: processStatusChangeWorkflow(wi.getActionValue(), page);
2537: }
2538:
2539: /**
2540: * @return Returns the workflowManager.
2541: */
2542: public WorkflowManager getWorkflowManager() {
2543: return workflowManager;
2544: }
2545:
2546: /**
2547: * @param workflowManager The workflowManager to set.
2548: */
2549: public void setWorkflowManager(WorkflowManager workflowManager) {
2550: this .workflowManager = workflowManager;
2551: }
2552:
2553: public StructuredArtifactDefinitionManager getStructuredArtifactDefinitionManager() {
2554: return structuredArtifactDefinitionManager;
2555: }
2556:
2557: public void setStructuredArtifactDefinitionManager(
2558: StructuredArtifactDefinitionManager structuredArtifactDefinitionManager) {
2559: this .structuredArtifactDefinitionManager = structuredArtifactDefinitionManager;
2560: }
2561:
2562: public GuidanceManager getGuidanceManager() {
2563: return guidanceManager;
2564: }
2565:
2566: public void setGuidanceManager(GuidanceManager guidanceManager) {
2567: this .guidanceManager = guidanceManager;
2568: }
2569:
2570: public ReviewManager getReviewManager() {
2571: return reviewManager;
2572: }
2573:
2574: public void setReviewManager(ReviewManager reviewManager) {
2575: this .reviewManager = reviewManager;
2576: }
2577:
2578: public StyleManager getStyleManager() {
2579: return styleManager;
2580: }
2581:
2582: public void setStyleManager(StyleManager styleManager) {
2583: this .styleManager = styleManager;
2584: }
2585:
2586: public String getImportFolderName() {
2587: return importFolderName;
2588: }
2589:
2590: public void setImportFolderName(String importFolderName) {
2591: this .importFolderName = importFolderName;
2592: }
2593:
2594: /**
2595: * @return the useExperimentalMatrix
2596: */
2597: public boolean isUseExperimentalMatrix() {
2598: return useExperimentalMatrix;
2599: }
2600:
2601: /**
2602: * @param useExperimentalMatrix the useExperimentalMatrix to set
2603: */
2604: public void setUseExperimentalMatrix(boolean useExperimentalMatrix) {
2605: this .useExperimentalMatrix = useExperimentalMatrix;
2606: }
2607:
2608: public boolean checkFormConsumption(Id formId) {
2609: Collection objectsWithForms = getHibernateTemplate()
2610: .find(
2611: "from ObjectWithWorkflow where "
2612: + "reflection_device_id = ? or evaluation_device_id = ? or review_device_id = ?",
2613: new Object[] { formId.getValue(),
2614: formId.getValue(), formId.getValue() });
2615:
2616: if (objectsWithForms.size() > 0) {
2617: return true;
2618: }
2619:
2620: String queryString = "from WizardPageDefinition as wpd left join wpd.additionalForms as af where "
2621: + "af = ?";
2622: Collection additionalForms = getHibernateTemplate().find(
2623: queryString, new Object[] { formId.getValue() });
2624:
2625: return additionalForms.size() > 0;
2626: }
2627: }
|