0001: /**********************************************************************************
0002: * $URL: https://source.sakaiproject.org/svn/metaobj/tags/sakai_2-4-1/metaobj-impl/api-impl/src/java/org/sakaiproject/metaobj/shared/mgt/impl/StructuredArtifactDefinitionManagerImpl.java $
0003: * $Id: StructuredArtifactDefinitionManagerImpl.java 28717 2007-04-12 00:33:40Z ajpoland@iupui.edu $
0004: ***********************************************************************************
0005: *
0006: * Copyright (c) 2004, 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.sakaiproject.metaobj.shared.mgt.impl;
0021:
0022: import org.jdom.CDATA;
0023: import org.jdom.Document;
0024: import org.jdom.Element;
0025: import org.jdom.JDOMException;
0026: import org.jdom.input.SAXBuilder;
0027: import org.jdom.output.XMLOutputter;
0028: import org.sakaiproject.authz.cover.FunctionManager;
0029: import org.sakaiproject.authz.api.SecurityAdvisor;
0030: import org.sakaiproject.authz.api.SecurityService;
0031: import org.sakaiproject.component.cover.ComponentManager;
0032: import org.sakaiproject.component.cover.ServerConfigurationService;
0033: import org.sakaiproject.content.api.ContentHostingService;
0034: import org.sakaiproject.content.api.ContentResource;
0035: import org.sakaiproject.content.api.ContentCollectionEdit;
0036: import org.sakaiproject.exception.*;
0037: import org.sakaiproject.metaobj.security.AuthenticationManager;
0038: import org.sakaiproject.metaobj.security.AuthorizationFacade;
0039: import org.sakaiproject.metaobj.shared.ArtifactFinder;
0040: import org.sakaiproject.metaobj.shared.DownloadableManager;
0041: import org.sakaiproject.metaobj.shared.SharedFunctionConstants;
0042: import org.sakaiproject.metaobj.shared.mgt.*;
0043: import org.sakaiproject.metaobj.shared.mgt.home.StructuredArtifactDefinition;
0044: import org.sakaiproject.metaobj.shared.mgt.home.StructuredArtifactHomeInterface;
0045: import org.sakaiproject.metaobj.shared.model.*;
0046: import org.sakaiproject.metaobj.utils.xml.SchemaFactory;
0047: import org.sakaiproject.metaobj.utils.xml.SchemaNode;
0048: import org.sakaiproject.metaobj.worksite.mgt.WorksiteManager;
0049: import org.sakaiproject.service.legacy.resource.DuplicatableToolService;
0050: import org.sakaiproject.site.api.Site;
0051: import org.sakaiproject.tool.api.Placement;
0052: import org.sakaiproject.tool.api.ToolManager;
0053: import org.sakaiproject.tool.cover.SessionManager;
0054: import org.sakaiproject.event.cover.NotificationService;
0055: import org.sakaiproject.entity.api.ResourcePropertiesEdit;
0056: import org.sakaiproject.entity.api.ResourceProperties;
0057: import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
0058:
0059: import javax.xml.transform.TransformerException;
0060: import java.io.*;
0061: import java.util.*;
0062: import java.util.zip.*;
0063:
0064: /**
0065: * @author chmaurer
0066: * @author jbush
0067: */
0068: public class StructuredArtifactDefinitionManagerImpl extends
0069: HibernateDaoSupport implements
0070: StructuredArtifactDefinitionManager, DuplicatableToolService,
0071: DownloadableManager, FormConsumer {
0072:
0073: static final private String DOWNLOAD_FORM_ID_PARAM = "formId";
0074: private static final String SYSTEM_COLLECTION_ID = "/system/";
0075:
0076: private AuthorizationFacade authzManager = null;
0077: private IdManager idManager;
0078: private WorksiteManager worksiteManager;
0079: private ContentHostingService contentHosting;
0080: private ToolManager toolManager;
0081: private List globalSites;
0082: private List globalSiteTypes;
0083: private ArtifactFinder artifactFinder;
0084: private ArtifactFinder structuredArtifactFinder;
0085: private int expressionMax = 999;
0086: private boolean replaceViews = true;
0087: private List formConsumers;
0088: private SecurityService securityService;
0089: private boolean autoDdl = true;
0090:
0091: public StructuredArtifactDefinitionManagerImpl() {
0092: }
0093:
0094: public Map getHomes() {
0095: Map<String, StructuredArtifactDefinitionBean> returnMap = new HashMap<String, StructuredArtifactDefinitionBean>();
0096: List list = findHomes();
0097: for (Iterator iter = list.iterator(); iter.hasNext();) {
0098: StructuredArtifactDefinitionBean sad = (StructuredArtifactDefinitionBean) iter
0099: .next();
0100: returnMap.put(sad.getId().getValue(), sad);
0101: }
0102:
0103: return returnMap;
0104: }
0105:
0106: /**
0107: * @param worksiteId
0108: * @return a map with all worksite and global homes
0109: */
0110: public Map getWorksiteHomes(Id worksiteId) {
0111: return getWorksiteHomes(worksiteId, false);
0112: }
0113:
0114: public Map getWorksiteHomes(Id worksiteId, boolean includeHidden) {
0115: Map<String, StructuredArtifactDefinitionBean> returnMap = new HashMap<String, StructuredArtifactDefinitionBean>();
0116: List<StructuredArtifactDefinitionBean> list = findGlobalHomes();
0117: list.addAll(findHomes(worksiteId, includeHidden));
0118: for (Iterator iter = list.iterator(); iter.hasNext();) {
0119: StructuredArtifactDefinitionBean sad = (StructuredArtifactDefinitionBean) iter
0120: .next();
0121: returnMap.put(sad.getId().getValue(), sad);
0122: }
0123:
0124: return returnMap;
0125: }
0126:
0127: /**
0128: * @return list of published sads or sads owned by current user
0129: */
0130: public List findHomes() {
0131: return findHomes(true);
0132: }
0133:
0134: public List findHomes(boolean includeHidden) {
0135: return findHomes(true, includeHidden);
0136: }
0137:
0138: public List findHomes(boolean includeGlobal, boolean includeHidden) {
0139: // only for the appropriate worksites
0140: List sites = getWorksiteManager().getUserSites();
0141: List<StructuredArtifactDefinitionBean> returned = new ArrayList<StructuredArtifactDefinitionBean>();
0142: while (sites.size() > getExpressionMax()) {
0143: returned.addAll(findHomes(sites.subList(0,
0144: getExpressionMax() - 1), false, includeHidden));
0145: sites.subList(0, getExpressionMax() - 1).clear();
0146: }
0147: returned.addAll(findHomes(sites, includeGlobal, includeHidden));
0148: return returned;
0149: }
0150:
0151: public Map findCategorizedHomes(boolean includeHidden) {
0152: List homes = findHomes(false, includeHidden);
0153:
0154: Map<String, List> catHomes = new Hashtable<String, List>();
0155:
0156: for (Iterator<StructuredArtifactDefinitionBean> i = homes
0157: .iterator(); i.hasNext();) {
0158: StructuredArtifactDefinitionBean bean = i.next();
0159:
0160: List beanList = catHomes.get(bean.getSiteId());
0161:
0162: if (beanList == null) {
0163: beanList = new ArrayList();
0164: catHomes.put(bean.getSiteId(), beanList);
0165: }
0166:
0167: beanList.add(bean);
0168: }
0169:
0170: return catHomes;
0171: }
0172:
0173: protected List findHomes(List sites, boolean includeGlobal,
0174: boolean includeHidden) {
0175: String query;
0176: Object[] params;
0177:
0178: if (includeGlobal) {
0179: query = "from StructuredArtifactDefinitionBean where ((globalState = ? or (owner = ? and siteId = null)) or "
0180: + "((owner = ? or siteState = ?) and siteId in (";
0181: params = new Object[] {
0182: new Integer(
0183: StructuredArtifactDefinitionBean.STATE_PUBLISHED),
0184: getAuthManager().getAgent(),
0185: getAuthManager().getAgent(),
0186: new Integer(
0187: StructuredArtifactDefinitionBean.STATE_PUBLISHED) };
0188: } else {
0189: query = "from StructuredArtifactDefinitionBean where ((globalState != ? and (owner = ? or siteState = ?) and siteId in (";
0190: params = new Object[] {
0191: new Integer(
0192: StructuredArtifactDefinitionBean.STATE_PUBLISHED),
0193: getAuthManager().getAgent(),
0194: new Integer(
0195: StructuredArtifactDefinitionBean.STATE_PUBLISHED) };
0196: }
0197:
0198: for (Iterator i = sites.iterator(); i.hasNext();) {
0199: Site site = (Site) i.next();
0200: query += "'" + site.getId() + "'";
0201: query += ",";
0202: }
0203:
0204: query += "''))";
0205:
0206: if (includeHidden) {
0207: query += ")";
0208: } else {
0209: query += ") and systemOnly != true";
0210: }
0211:
0212: return getHibernateTemplate().find(query, params);
0213: }
0214:
0215: public List findBySchema(ContentResource resource) {
0216: try {
0217: //String id = getContentHosting().resolveUuid(fileId.getValue());
0218: //ContentResource resource = getContentHosting().getResource(id);
0219:
0220: Object[] params = new Object[] { resource.getContent() };
0221: return getHibernateTemplate().findByNamedQuery(
0222: "findBySchema", params);
0223: } catch (ServerOverloadException e) {
0224:
0225: }
0226: return new ArrayList();
0227: }
0228:
0229: /**
0230: * @return list of all published globals or global sad owned by current user or waiting for approval
0231: */
0232: public List findGlobalHomes() {
0233: Object[] params = new Object[] {
0234: new Integer(
0235: StructuredArtifactDefinitionBean.STATE_PUBLISHED),
0236: getAuthManager().getAgent() };
0237: return getHibernateTemplate().findByNamedQuery(
0238: "findGlobalHomes", params);
0239: }
0240:
0241: /**
0242: * @param currentWorksiteId
0243: * @return list of globally published sads or published sad in currentWorksiteId or sads in
0244: * currentWorksiteId owned by current user
0245: */
0246: public List findHomes(Id currentWorksiteId) {
0247: String queryName = "findHomes";
0248: return findHomes(currentWorksiteId, queryName);
0249: }
0250:
0251: protected List findHomes(Id currentWorksiteId, String queryName) {
0252: Object[] params = new Object[] {
0253: new Integer(
0254: StructuredArtifactDefinitionBean.STATE_PUBLISHED),
0255: currentWorksiteId.getValue(),
0256: getAuthManager().getAgent(),
0257: new Integer(
0258: StructuredArtifactDefinitionBean.STATE_PUBLISHED) };
0259: return getHibernateTemplate().findByNamedQuery(queryName,
0260: params);
0261: }
0262:
0263: public List findHomes(Id currentWorksiteId, boolean includeHidden) {
0264: return findHomes(currentWorksiteId, includeHidden, true);
0265: }
0266:
0267: public List findHomes(Id currentWorksiteId, boolean includeHidden,
0268: boolean includeGlobal) {
0269: if (includeGlobal) {
0270: return findHomes(currentWorksiteId,
0271: includeHidden ? "findHomesIncludeHidden"
0272: : "findHomes");
0273: } else {
0274: return findHomes(currentWorksiteId,
0275: includeHidden ? "findWorksiteHomesIncludeHidden"
0276: : "findWorksiteHomes");
0277: }
0278: }
0279:
0280: public StructuredArtifactDefinitionBean loadHome(String type) {
0281: return loadHome(getIdManager().getId(type));
0282: }
0283:
0284: public StructuredArtifactDefinitionBean loadHome(Id id) {
0285: return (StructuredArtifactDefinitionBean) getHibernateTemplate()
0286: .get(StructuredArtifactDefinitionBean.class, id);
0287: }
0288:
0289: public StructuredArtifactDefinitionBean loadHomeByExternalType(
0290: String externalType, Id worksiteId) {
0291: List homes = (List) getHibernateTemplate()
0292: .findByNamedQuery(
0293: "loadHomeByExternalType",
0294: new Object[] {
0295: externalType,
0296: new Integer(
0297: StructuredArtifactDefinitionBean.STATE_PUBLISHED),
0298: worksiteId.getValue() });
0299:
0300: if (homes.size() == 0) {
0301: return null;
0302: }
0303:
0304: if (homes.size() == 1) {
0305: return (StructuredArtifactDefinitionBean) homes.get(0);
0306: } else {
0307: for (Iterator i = homes.iterator(); i.hasNext();) {
0308: StructuredArtifactDefinitionBean def = (StructuredArtifactDefinitionBean) i
0309: .next();
0310: if (def.getSiteId() != null) {
0311: if (def.getSiteId().equals(worksiteId.getValue())) {
0312: return def;
0313: }
0314: }
0315: }
0316: return (StructuredArtifactDefinitionBean) homes.get(0);
0317: }
0318: }
0319:
0320: public StructuredArtifactDefinitionBean save(
0321: StructuredArtifactDefinitionBean bean) {
0322: return save(bean, true);
0323: }
0324:
0325: public StructuredArtifactDefinitionBean save(
0326: StructuredArtifactDefinitionBean bean, boolean updateModTime) {
0327: if (!sadExists(bean)) {
0328: if (updateModTime) {
0329: bean.setModified(new Date(System.currentTimeMillis()));
0330: }
0331:
0332: StructuredArtifactDefinition sad = null;
0333: try {
0334: if (bean.getId() == null) {
0335: loadNode(bean);
0336: bean
0337: .setCreated(new Date(System
0338: .currentTimeMillis()));
0339: } else if (bean.getSchemaFile() != null) {
0340: loadNode(bean);
0341: sad = new StructuredArtifactDefinition(bean);
0342: updateExistingArtifacts(sad);
0343: }
0344: } catch (Exception e) {
0345: throw new OspException("Invlaid schema", e);
0346: }
0347: sad = new StructuredArtifactDefinition(bean);
0348: bean.setExternalType(sad.getExternalType());
0349: bean.setSchemaHash(calculateSchemaHash(bean));
0350: getHibernateTemplate().saveOrUpdate(bean);
0351: // getHibernateTemplate().saveOrUpdateCopy(bean);
0352: } else {
0353: throw new PersistenceException("Form name {0} exists",
0354: new Object[] { bean.getDescription() },
0355: "description");
0356: }
0357: return bean;
0358: }
0359:
0360: public void delete(StructuredArtifactDefinitionBean sad) {
0361:
0362: for (Iterator<FormConsumer> i = getFormConsumers().iterator(); i
0363: .hasNext();) {
0364: if (i.next().checkFormConsumption(sad.getId())) {
0365: throw new PersistenceException(
0366: "unable_to_delete_published", new Object[] {},
0367: "siteState");
0368: }
0369: }
0370:
0371: getHibernateTemplate().delete(sad);
0372: }
0373:
0374: /**
0375: * @return Returns the idManager.
0376: */
0377: public IdManager getIdManager() {
0378: return idManager;
0379: }
0380:
0381: /**
0382: * @param idManager The idManager to set.
0383: */
0384: public void setIdManager(IdManager idManager) {
0385: this .idManager = idManager;
0386: }
0387:
0388: public boolean isGlobal() {
0389: String siteId = getWorksiteManager().getCurrentWorksiteId()
0390: .getValue();
0391: return isGlobal(siteId);
0392: }
0393:
0394: protected boolean isGlobal(String siteId) {
0395:
0396: if (getGlobalSites().contains(siteId)) {
0397: return true;
0398: }
0399:
0400: Site site = getWorksiteManager().getSite(siteId);
0401: if (site.getType() != null
0402: && getGlobalSiteTypes().contains(site.getType())) {
0403: return true;
0404: }
0405:
0406: return false;
0407: }
0408:
0409: protected Site getCurrentSite() {
0410: String siteId = getWorksiteManager().getCurrentWorksiteId()
0411: .getValue();
0412: return getWorksiteManager().getSite(siteId);
0413: }
0414:
0415: public Collection getRootElements(
0416: StructuredArtifactDefinitionBean sad) {
0417: try {
0418: SchemaNode node = loadNode(sad);
0419: return node.getRootChildren();
0420: } catch (Exception e) {
0421: throw new OspException("Invalid schema.", e);
0422: }
0423: }
0424:
0425: public void validateSchema(StructuredArtifactDefinitionBean sad) {
0426: SchemaNode node = null;
0427:
0428: try {
0429: node = loadNode(sad);
0430: } catch (Exception e) {
0431: throw new OspException("Invlid schema file.", e);
0432: }
0433:
0434: if (node == null) {
0435: throw new OspException("Invlid schema file.");
0436: }
0437: }
0438:
0439: public StructuredArtifactHomeInterface convertToHome(
0440: StructuredArtifactDefinitionBean sad) {
0441: return new StructuredArtifactDefinition(sad);
0442: }
0443:
0444: protected SchemaNode loadNode(StructuredArtifactDefinitionBean sad)
0445: throws TypeException, IdUnusedException,
0446: PermissionException, ServerOverloadException {
0447: if (sad.getSchemaFile() != null) {
0448: ContentResource resource = getContentHosting().getResource(
0449: sad.getSchemaFile().getValue());
0450: sad.setSchema(resource.getContent());
0451: }
0452:
0453: if (sad.getSchema() == null) {
0454: return null;
0455: }
0456:
0457: SchemaFactory schemaFactory = SchemaFactory.getInstance();
0458: return schemaFactory.getSchema(new ByteArrayInputStream(sad
0459: .getSchema()));
0460: }
0461:
0462: protected boolean sadExists(StructuredArtifactDefinitionBean sad)
0463: throws PersistenceException {
0464: String query = "from StructuredArtifactDefinitionBean where description = ? ";
0465: List<Object> params = new ArrayList<Object>();
0466: params.add(sad.getDescription());
0467:
0468: if (sad.getId() != null) {
0469: query += " and id != ? ";
0470: params.add(sad.getId());
0471: }
0472:
0473: if (sad.getSiteId() != null) {
0474: query += " and siteId = ? ";
0475: params.add(sad.getSiteId());
0476: } else {
0477: query += " and siteId is null";
0478: }
0479:
0480: List sads = getHibernateTemplate()
0481: .find(query, params.toArray());
0482:
0483: return sads.size() > 0;
0484: }
0485:
0486: /**
0487: * @param sad
0488: * @param artifact
0489: * @throws OspException if artifact doesn't validate
0490: */
0491: protected void validateAfterTransform(
0492: StructuredArtifactDefinition sad,
0493: StructuredArtifact artifact) throws OspException {
0494: //TODO figure out how to do the validator
0495: // StructuredArtifactValidator validator = new StructuredArtifactValidator();
0496: // artifact.setHome(sad);
0497: // Errors artifactErrors = new BindExceptionBase(artifact, "bean");
0498: // validator.validate(artifact, artifactErrors);
0499: // if (artifactErrors.getErrorCount() > 0) {
0500: // StringBuffer buf = new StringBuffer();
0501: // for (Iterator i=artifactErrors.getAllErrors().iterator();i.hasNext();){
0502: // ObjectError error = (ObjectError) i.next();
0503: // buf.append(error.toString() + " ");
0504: // }
0505: // throw new OspException(buf.toString());
0506: // }
0507: }
0508:
0509: protected void saveAll(StructuredArtifactDefinition sad,
0510: Collection artifacts) {
0511: for (Iterator i = artifacts.iterator(); i.hasNext();) {
0512: StructuredArtifact artifact = (StructuredArtifact) i.next();
0513: try {
0514: sad.store(artifact);
0515: } catch (PersistenceException e) {
0516: logger.error("problem saving artifact with id "
0517: + artifact.getId().getValue() + ":" + e);
0518: }
0519: }
0520: }
0521:
0522: /**
0523: * Uses the submitted xsl file to transform the existing artifacts into the schema.
0524: * This process puts the artifact home into system only start while is does its work.
0525: * This is necessary so that users won't be able to update artifacts while this is going on.
0526: * The system transforms every object in memory and validates before writing any artifact back out.
0527: * This way if something fails the existing data will stay intact.
0528: * <p/>
0529: * TODO possible memory issues
0530: * TODO all this work need to be atomic
0531: *
0532: * @param sad
0533: * @throws OspException
0534: */
0535: protected void updateExistingArtifacts(
0536: StructuredArtifactDefinition sad) throws OspException {
0537:
0538: //if we don't have an xsl file and don't need one, return
0539: if (!sad.getRequiresXslFile()) {
0540: return;
0541: }
0542:
0543: if (sad.getRequiresXslFile()
0544: && (sad.getXslConversionFileId() == null || sad
0545: .getXslConversionFileId().getValue().length() == 0)) {
0546: throw new OspException("xsl conversion file required");
0547: }
0548:
0549: // put artifact home in system only state while we do this work.
0550: // this along with repository authz prevents someone from updating an artifact
0551: // while this is going on
0552: StructuredArtifactDefinitionBean currentHome = this
0553: .loadHome(sad.getId());
0554: boolean originalSystemOnlyState = currentHome.isSystemOnly();
0555: currentHome.setSystemOnly(true);
0556: getHibernateTemplate().saveOrUpdate(currentHome);
0557:
0558: boolean finished = false;
0559: String type = sad.getType().getId().getValue();
0560: //ArtifactFinder artifactFinder = getArtifactFinderManager().getArtifactFinderByType(type);
0561: Collection artifacts = getArtifactFinder().findByType(type);
0562: Collection<StructuredArtifact> modifiedArtifacts = new ArrayList<StructuredArtifact>();
0563:
0564: // perform xsl transformations on existing artifacts
0565: try {
0566: for (Iterator i = artifacts.iterator(); i.hasNext();) {
0567: StructuredArtifact artifact = (StructuredArtifact) i
0568: .next();
0569: try {
0570: transform(sad, artifact);
0571: validateAfterTransform(sad, artifact);
0572: // don't persist yet, in case error is found in some other artifact
0573: modifiedArtifacts.add(artifact);
0574: } catch (TransformerException e) {
0575: throw new OspException(
0576: "problem transforming item with id="
0577: + artifact.getId().getValue(), e);
0578: } catch (IOException e) {
0579: throw new OspException(e);
0580: } catch (JDOMException e) {
0581: throw new OspException("problem with xsl file: "
0582: + e.getMessage(), e);
0583: }
0584: }
0585: finished = true;
0586: } finally {
0587: // reset systemOnly state back to whatever if was
0588: // but only if there was an error
0589: if (!originalSystemOnlyState && !finished) {
0590: currentHome.setSystemOnly(false);
0591: getHibernateTemplate().saveOrUpdate(currentHome);
0592: }
0593: }
0594:
0595: // since all artifacts validated go ahead and persist changes
0596: saveAll(sad, modifiedArtifacts);
0597: }
0598:
0599: protected Element getStructuredArtifactRootElement(
0600: StructuredArtifactDefinition sad,
0601: StructuredArtifact artifact) {
0602: return sad.getArtifactAsXml(artifact)
0603: .getChild("structuredData").getChild(sad.getRootNode());
0604: }
0605:
0606: protected void transform(StructuredArtifactDefinition sad,
0607: StructuredArtifact artifact) throws IOException,
0608: TransformerException, JDOMException {
0609: /* todo transform
0610: logger.debug("transforming artifact " + artifact.getId().getValue() + " owned by " + artifact.getOwner().getDisplayName());
0611: JDOMResult result = new JDOMResult();
0612: SAXBuilder builder = new SAXBuilder();
0613: Document xslDoc = builder.build(sad.getXslConversionFileStream());
0614: Transformer transformer = TransformerFactory.newInstance().newTransformer(new JDOMSource(xslDoc));
0615: Element rootElement = getStructuredArtifactRootElement(sad, artifact);
0616:
0617: transformer.transform(new JDOMSource(rootElement), result);
0618:
0619: artifact.setBaseElement((Element) result.getResult().get(0));
0620: */
0621: }
0622:
0623: public AuthenticationManager getAuthManager() {
0624: return (AuthenticationManager) ComponentManager.getInstance()
0625: .get("authManager");
0626: }
0627:
0628: public AuthorizationFacade getAuthzManager() {
0629: return authzManager;
0630: }
0631:
0632: public void setAuthzManager(AuthorizationFacade authzManager) {
0633: this .authzManager = authzManager;
0634: }
0635:
0636: public WorksiteManager getWorksiteManager() {
0637: return worksiteManager;
0638: }
0639:
0640: public void setWorksiteManager(WorksiteManager worksiteManager) {
0641: this .worksiteManager = worksiteManager;
0642: }
0643:
0644: public ToolManager getToolManager() {
0645: return toolManager;
0646: }
0647:
0648: public void setToolManager(ToolManager toolManager) {
0649: this .toolManager = toolManager;
0650: }
0651:
0652: protected Id getToolId() {
0653: Placement placement = toolManager.getCurrentPlacement();
0654: return idManager.getId(placement.getId());
0655: }
0656:
0657: public void importResources(String fromContext, String toContext,
0658: List resourceIds) {
0659: // select all this worksites forms and create them for the new worksite
0660: Map homes = getWorksiteHomes(getIdManager().getId(fromContext),
0661: true);
0662:
0663: for (Iterator i = homes.entrySet().iterator(); i.hasNext();) {
0664: Map.Entry entry = (Map.Entry) i.next();
0665: StructuredArtifactDefinitionBean bean = (StructuredArtifactDefinitionBean) entry
0666: .getValue();
0667:
0668: if (fromContext.equals(bean.getSiteId())) {
0669: getHibernateTemplate().evict(bean);
0670: bean.setSiteId(toContext);
0671: bean.setId(null);
0672: bean
0673: .setSiteState(StructuredArtifactDefinitionBean.STATE_UNPUBLISHED);
0674:
0675: //Check for an existing form
0676: if (findBean(bean) == null) {
0677: getHibernateTemplate().save(bean);
0678: }
0679:
0680: // getHibernateTemplate().saveOrUpdateCopy(bean);
0681: }
0682: }
0683: }
0684:
0685: public ContentHostingService getContentHosting() {
0686: return contentHosting;
0687: }
0688:
0689: public void setContentHosting(ContentHostingService contentHosting) {
0690: this .contentHosting = contentHosting;
0691: }
0692:
0693: protected void init() throws Exception {
0694: logger.info("init()");
0695: // register functions
0696: FunctionManager
0697: .registerFunction(SharedFunctionConstants.CREATE_ARTIFACT_DEF);
0698: FunctionManager
0699: .registerFunction(SharedFunctionConstants.EDIT_ARTIFACT_DEF);
0700: FunctionManager
0701: .registerFunction(SharedFunctionConstants.EXPORT_ARTIFACT_DEF);
0702: FunctionManager
0703: .registerFunction(SharedFunctionConstants.DELETE_ARTIFACT_DEF);
0704: FunctionManager
0705: .registerFunction(SharedFunctionConstants.PUBLISH_ARTIFACT_DEF);
0706: FunctionManager
0707: .registerFunction(SharedFunctionConstants.SUGGEST_GLOBAL_PUBLISH_ARTIFACT_DEF);
0708:
0709: addConsumer(this );
0710:
0711: if (isAutoDdl()) {
0712:
0713: updateSchemaHash();
0714: org.sakaiproject.tool.api.Session sakaiSession = SessionManager
0715: .getCurrentSession();
0716: String userId = sakaiSession.getUserId();
0717: sakaiSession.setUserId("admin");
0718: sakaiSession.setUserEid("admin");
0719:
0720: try {
0721: createResource(
0722: "/org/sakaiproject/metaobj/shared/control/formCreate.xslt",
0723: "formCreate.xslt",
0724: "used for default rendering of form add and update",
0725: "text/xml", isReplaceViews(), true);
0726:
0727: createResource(
0728: "/org/sakaiproject/metaobj/shared/control/formFieldTemplate.xslt",
0729: "formFieldTemplate.xslt",
0730: "used for default rendering of form fields",
0731: "text/xml", isReplaceViews(), true);
0732:
0733: createResource(
0734: "/org/sakaiproject/metaobj/shared/control/formView.xslt",
0735: "formView.xslt",
0736: "used for default rendering of form viewing",
0737: "text/xml", isReplaceViews(), true);
0738: } finally {
0739: sakaiSession.setUserEid(userId);
0740: sakaiSession.setUserId(userId);
0741: }
0742: }
0743:
0744: }
0745:
0746: protected void updateSchemaHash() {
0747: List forms = getHibernateTemplate().findByNamedQuery(
0748: "findByNullSchemaHash");
0749:
0750: for (Iterator i = forms.iterator(); i.hasNext();) {
0751: StructuredArtifactDefinitionBean bean = (StructuredArtifactDefinitionBean) i
0752: .next();
0753: bean.setSchemaHash(calculateSchemaHash(bean));
0754: getHibernateTemplate().saveOrUpdate(bean);
0755:
0756: // getHibernateTemplate().saveOrUpdateCopy(bean);
0757: }
0758: }
0759:
0760: protected String calculateSchemaHash(
0761: StructuredArtifactDefinitionBean bean) {
0762: String hashString = "";
0763: if (bean.getSchema() != null) {
0764: hashString += new String(bean.getSchema());
0765: }
0766: hashString += bean.getDocumentRoot();
0767: hashString += bean.getDescription();
0768: hashString += bean.getInstruction();
0769: return hashString.hashCode() + "";
0770: }
0771:
0772: public String packageForDownload(Map params, OutputStream out)
0773: throws IOException {
0774:
0775: String[] formIdObj = (String[]) params
0776: .get(DOWNLOAD_FORM_ID_PARAM);
0777: packageFormForExport(formIdObj[0], out);
0778:
0779: //Blank filename for now -- no more dangerous, since the request is in the form of a filename
0780: return "";
0781: }
0782:
0783: /**
0784: * This is the default method for exporting a form into a stream. This method does check the
0785: * form export permission.
0786: * @param formId String
0787: * @param os OutputStream
0788: * @throws IOException
0789: */
0790: public void packageFormForExport(String formId, OutputStream os)
0791: throws IOException {
0792: packageFormForExport(formId, os, true);
0793: }
0794:
0795: /**
0796: * This method will export a form into a stream. It has the ability to turn off checking
0797: * for the export form permission.
0798: * @param formId String
0799: * @param os OutputStream
0800: * @param checkPermission boolean
0801: * @throws IOException
0802: */
0803: public void packageFormForExport(String formId, OutputStream os,
0804: boolean checkPermission) throws IOException {
0805: if (checkPermission) {
0806: getAuthzManager().checkPermission(
0807: SharedFunctionConstants.EXPORT_ARTIFACT_DEF,
0808: getToolId());
0809: }
0810:
0811: CheckedOutputStream checksum = new CheckedOutputStream(os,
0812: new Adler32());
0813: ZipOutputStream zos = new ZipOutputStream(
0814: new BufferedOutputStream(checksum));
0815:
0816: StructuredArtifactDefinitionBean bean = loadHome(formId);
0817: writeSADtoZip(bean, zos, "");
0818:
0819: zos.finish();
0820: zos.flush();
0821: }
0822:
0823: /**
0824: * Given a bean this method will convert it into a new XML document.
0825: * This does not put the schema into XML
0826: * @param bean StructuredArtifactDefinitionBean
0827: * @return Document - XML
0828: */
0829: public Document exportSADAsXML(StructuredArtifactDefinitionBean bean) {
0830: Element rootNode = new Element("metaobjForm");
0831:
0832: rootNode.setAttribute("formatVersion", "2.1");
0833:
0834: Element attrNode = new Element("description");
0835: attrNode.addContent(new CDATA(bean.getDescription()));
0836: rootNode.addContent(attrNode);
0837:
0838: attrNode = new Element("instruction");
0839: attrNode.addContent(new CDATA(bean.getInstruction()));
0840: rootNode.addContent(attrNode);
0841:
0842: attrNode = new Element("documentRootNode");
0843: attrNode.addContent(new CDATA(bean.getDocumentRoot()));
0844: rootNode.addContent(attrNode);
0845:
0846: return new Document(rootNode);
0847: }
0848:
0849: /**
0850: * Given a bean, this method puts it into a stream via UTF-8 encoding
0851: * @param bean StructuredArtifactDefinitionBean
0852: * @param os OutputStream
0853: * @throws IOException
0854: */
0855: public void writeSADasXMLtoStream(
0856: StructuredArtifactDefinitionBean bean, OutputStream os)
0857: throws IOException {
0858: Document doc = exportSADAsXML(bean);
0859: String docStr = (new XMLOutputter()).outputString(doc);
0860: os.write(docStr.getBytes("UTF-8"));
0861: }
0862:
0863: public void writeSADtoZip(StructuredArtifactDefinitionBean bean,
0864: ZipOutputStream zos) throws IOException {
0865: writeSADtoZip(bean, zos, "");
0866: }
0867:
0868: public void writeSADtoZip(StructuredArtifactDefinitionBean bean,
0869: ZipOutputStream zos, String path) throws IOException {
0870: // if the path is a directory without an end slash, then add one
0871: if (!path.endsWith("/") && path.length() > 0) {
0872: path += "/";
0873: }
0874: ZipEntry definitionFile = new ZipEntry(path
0875: + "formDefinition.xml");
0876:
0877: zos.putNextEntry(definitionFile);
0878: writeSADasXMLtoStream(bean, zos);
0879: zos.closeEntry();
0880:
0881: ZipEntry schemeFile = new ZipEntry(path + "schema.xsd");
0882:
0883: zos.putNextEntry(schemeFile);
0884: zos.write(bean.getSchema());
0885: zos.closeEntry();
0886:
0887: }
0888:
0889: /**
0890: * Given a resource id, this parses out the Form from its input stream.
0891: * Once the enties are found, they are inserted into the given worksite.
0892: *
0893: * @param worksiteId Id
0894: * @param resourceId an String
0895: * @param findExisting
0896: */
0897: public boolean importSADResource(Id worksiteId, String resourceId,
0898: boolean findExisting) throws IOException,
0899: ServerOverloadException, PermissionException,
0900: IdUnusedException, ImportException,
0901: UnsupportedFileTypeException {
0902: String id = getContentHosting().resolveUuid(resourceId);
0903:
0904: try {
0905: ContentResource resource = getContentHosting().getResource(
0906: id);
0907: MimeType mimeType = new MimeType(resource.getContentType());
0908:
0909: if (mimeType.equals(new MimeType("application/zip"))
0910: || mimeType.equals(new MimeType(
0911: "application/x-zip-compressed"))) {
0912: InputStream zipContent = resource.streamContent();
0913: StructuredArtifactDefinitionBean bean = importSad(
0914: worksiteId, zipContent, findExisting, false);
0915:
0916: return bean != null;
0917: } else {
0918: throw new UnsupportedFileTypeException(
0919: "The import file must be a zip file.");
0920: }
0921: } catch (TypeException te) {
0922: logger.error(te);
0923: }
0924: return false;
0925: }
0926:
0927: public StructuredArtifactDefinitionBean importSad(Id worksiteId,
0928: InputStream in, boolean findExisting, boolean publish)
0929: throws IOException, ImportException {
0930: return importSad(worksiteId, in, findExisting, publish, true);
0931: }
0932:
0933: public StructuredArtifactDefinitionBean importSad(Id worksiteId,
0934: InputStream in, boolean findExisting, boolean publish,
0935: boolean foundThrowsException) throws IOException,
0936: ImportException {
0937: ZipInputStream zis = new ZipInputStream(in);
0938:
0939: StructuredArtifactDefinitionBean bean = readSADfromZip(zis,
0940: worksiteId.getValue(), publish);
0941: if (bean != null) {
0942: if (findExisting) {
0943: StructuredArtifactDefinitionBean found = findBean(bean);
0944: if (found != null) {
0945: if (foundThrowsException) {
0946: throw new ImportException(
0947: "The Form being imported already exists and has been published");
0948: } else {
0949: return found;
0950: }
0951: }
0952: }
0953:
0954: String origTitle = bean.getDescription();
0955: int index = 0;
0956: while (sadExists(bean)) {
0957: index++;
0958: bean.setDescription(origTitle + " " + index);
0959: }
0960:
0961: save(bean);
0962: // doesn't like imported beans in batch mode???
0963: getHibernateTemplate().flush();
0964: }
0965: return bean;
0966: }
0967:
0968: /**
0969: *
0970: * @param bean
0971: * @return
0972: */
0973: protected StructuredArtifactDefinitionBean findBean(
0974: StructuredArtifactDefinitionBean bean) {
0975: Object[] params = new Object[] {
0976: new Integer(
0977: StructuredArtifactDefinitionBean.STATE_PUBLISHED),
0978: bean.getSiteId(), bean.getSchemaHash() };
0979: List beans = getHibernateTemplate().findByNamedQuery(
0980: "findBean", params);
0981:
0982: if (beans.size() > 0) {
0983: return (StructuredArtifactDefinitionBean) beans.get(0);
0984: }
0985: return null;
0986: }
0987:
0988: public StructuredArtifactDefinitionBean readSADfromZip(
0989: ZipInputStream zis, String worksite, boolean publish)
0990: throws IOException {
0991: StructuredArtifactDefinitionBean bean = new StructuredArtifactDefinitionBean();
0992: boolean hasXML = false, hasXSD = false;
0993:
0994: bean.setCreated(new Date(System.currentTimeMillis()));
0995: bean.setModified(bean.getCreated());
0996:
0997: bean.setOwner(getAuthManager().getAgent());
0998: bean.setSiteId(worksite);
0999: bean
1000: .setSiteState(publish ? StructuredArtifactDefinitionBean.STATE_PUBLISHED
1001: : StructuredArtifactDefinitionBean.STATE_UNPUBLISHED);
1002:
1003: if (isGlobal(worksite)) {
1004: bean
1005: .setGlobalState(publish ? StructuredArtifactDefinitionBean.STATE_PUBLISHED
1006: : StructuredArtifactDefinitionBean.STATE_UNPUBLISHED);
1007: bean.setSiteId(null);
1008: }
1009:
1010: ZipEntry currentEntry = zis.getNextEntry();
1011:
1012: if (currentEntry == null) {
1013: return null;
1014: }
1015:
1016: // If the zip was opened and re-zipped, then the directory was
1017: // compressed with the files. we need to deal with
1018: // the directory
1019: if (currentEntry.getName().endsWith("/")) {
1020: zis.closeEntry();
1021: currentEntry = zis.getNextEntry();
1022: }
1023:
1024: if (currentEntry != null) {
1025: if (currentEntry.getName().endsWith("xml")) {
1026: readSADfromXML(bean, zis);
1027: hasXML = true;
1028: }
1029: if (currentEntry.getName().endsWith("xsd")) {
1030: readSADSchemaFromXML(bean, zis);
1031: hasXSD = true;
1032: }
1033: zis.closeEntry();
1034: }
1035: currentEntry = zis.getNextEntry();
1036: if (currentEntry != null) {
1037: if (currentEntry.getName().endsWith("xml")) {
1038: readSADfromXML(bean, zis);
1039: hasXML = true;
1040: }
1041: if (currentEntry.getName().endsWith("xsd")) {
1042: readSADSchemaFromXML(bean, zis);
1043: hasXSD = true;
1044: }
1045: zis.closeEntry();
1046: }
1047: if (!hasXML || !hasXSD) {
1048: return null;
1049: }
1050:
1051: bean.setSchemaHash(calculateSchemaHash(bean));
1052: return bean;
1053: }
1054:
1055: private StructuredArtifactDefinitionBean readSADfromXML(
1056: StructuredArtifactDefinitionBean bean, InputStream inStream) {
1057: SAXBuilder builder = new SAXBuilder();
1058:
1059: try {
1060: byte[] bytes = readStreamToBytes(inStream);
1061: // for some reason the SAX Builder sometimes won't recognize
1062: //these bytes as correct utf-8 characters. So we want to read it in
1063: //as utf-8 and spot it back out as utf-8 and this will correct the
1064: //bytes. In my test, it added two bytes somewhere in the string.
1065: //and adding those two bytes made the string work for saxbuilder.
1066: //
1067: bytes = (new String(bytes, "UTF-8")).getBytes("UTF-8");
1068: Document document = builder.build(new ByteArrayInputStream(
1069: bytes));
1070:
1071: Element topNode = document.getRootElement();
1072:
1073: bean.setDescription(new String(topNode.getChildTextTrim(
1074: "description").getBytes(), "UTF-8"));
1075: bean.setInstruction(new String(topNode.getChildTextTrim(
1076: "instruction").getBytes(), "UTF-8"));
1077: bean.setDocumentRoot(new String(topNode.getChildTextTrim(
1078: "documentRootNode").getBytes(), "UTF-8"));
1079: } catch (Exception jdome) {
1080: logger.error(jdome);
1081: throw new RuntimeException(jdome);
1082: }
1083: return bean;
1084: }
1085:
1086: private byte[] readStreamToBytes(InputStream inStream)
1087: throws IOException {
1088: ByteArrayOutputStream bytes = new ByteArrayOutputStream();
1089: byte data[] = new byte[10 * 1024];
1090:
1091: int count;
1092: while ((count = inStream.read(data, 0, 10 * 1024)) != -1) {
1093: bytes.write(data, 0, count);
1094: }
1095: byte[] tmp = bytes.toByteArray();
1096: bytes.close();
1097: return tmp;
1098: }
1099:
1100: private StructuredArtifactDefinitionBean readSADSchemaFromXML(
1101: StructuredArtifactDefinitionBean bean, InputStream inStream)
1102: throws IOException {
1103: bean.setSchema(readStreamToBytes(inStream));
1104: return bean;
1105: }
1106:
1107: public List getGlobalSites() {
1108: return globalSites;
1109: }
1110:
1111: public void setGlobalSites(List globalSites) {
1112: this .globalSites = globalSites;
1113: }
1114:
1115: public List getGlobalSiteTypes() {
1116: return globalSiteTypes;
1117: }
1118:
1119: public void setGlobalSiteTypes(List globalSiteTypes) {
1120: this .globalSiteTypes = globalSiteTypes;
1121: }
1122:
1123: public Element createFormViewXml(String formId, String returnUrl) {
1124: formId = getContentHosting().getUuid(formId);
1125: Artifact art = getArtifactFinder().load(
1126: getIdManager().getId(formId));
1127: return createFormViewXml(art, returnUrl);
1128: }
1129:
1130: public Element createFormViewXml(Artifact art, String returnUrl) {
1131: Element root = new Element("formView");
1132: Element data = new Element("formData");
1133:
1134: ReadableObjectHome home = (ReadableObjectHome) art.getHome();
1135: if (home instanceof PresentableObjectHome) {
1136: data.addContent(((PresentableObjectHome) home)
1137: .getArtifactAsXml(art));
1138: }
1139:
1140: root.addContent(data);
1141:
1142: if (returnUrl != null) {
1143: Element returnUrlElement = new Element("returnUrl");
1144: returnUrlElement.addContent(new CDATA(returnUrl));
1145: root.addContent(returnUrlElement);
1146: }
1147:
1148: Element css = new Element("css");
1149: String skin = null;
1150: try {
1151: skin = getCurrentSite().getSkin();
1152: } catch (NullPointerException npe) {
1153: //Couldn't find the site, just use default skin
1154: }
1155: if (skin == null || skin.length() == 0) {
1156: skin = ServerConfigurationService.getString("skin.default");
1157: }
1158: String skinRepo = ServerConfigurationService
1159: .getString("skin.repo");
1160: Element uri = new Element("uri");
1161: uri.setText(skinRepo + "/tool_base.css");
1162: css.addContent(uri);
1163: uri = new Element("uri");
1164: uri.setText(skinRepo + "/" + skin + "/tool.css");
1165: css.addContent(uri);
1166: root.addContent(css);
1167: return root;
1168: }
1169:
1170: public Element createFormViewXml(ElementBean bean, String returnUrl) {
1171: Element root = new Element("formView");
1172: Element data = new Element("formData");
1173:
1174: //data.addContent(((PresentableObjectHome) home).getArtifactAsXml(art));
1175:
1176: root.addContent(data);
1177:
1178: if (returnUrl != null) {
1179: Element returnUrlElement = new Element("returnUrl");
1180: returnUrlElement.addContent(new CDATA(returnUrl));
1181: root.addContent(returnUrlElement);
1182: }
1183:
1184: Element css = new Element("css");
1185: String skin = null;
1186: try {
1187: skin = getCurrentSite().getSkin();
1188: } catch (NullPointerException npe) {
1189: //Couldn't find the site, just use default skin
1190: }
1191: if (skin == null || skin.length() == 0) {
1192: skin = ServerConfigurationService.getString("skin.default");
1193: }
1194: String skinRepo = ServerConfigurationService
1195: .getString("skin.repo");
1196: Element uri = new Element("uri");
1197: uri.setText(skinRepo + "/tool_base.css");
1198: css.addContent(uri);
1199: uri = new Element("uri");
1200: uri.setText(skinRepo + "/" + skin + "/tool.css");
1201: css.addContent(uri);
1202: root.addContent(css);
1203: return root;
1204: }
1205:
1206: public InputStream getTransformer(String type, boolean readOnly) {
1207: try {
1208: String viewLocation = "/group/PortfolioAdmin/system/formCreate.xslt";
1209: if (readOnly) {
1210: viewLocation = "/group/PortfolioAdmin/system/formView.xslt";
1211: }
1212: return getContentHosting().getResource(viewLocation)
1213: .streamContent();
1214: } catch (ServerOverloadException e) {
1215: throw new RuntimeException(e);
1216: } catch (PermissionException e) {
1217: throw new RuntimeException(e);
1218: } catch (IdUnusedException e) {
1219: throw new RuntimeException(e);
1220: } catch (TypeException e) {
1221: throw new RuntimeException(e);
1222: }
1223: }
1224:
1225: public boolean hasHomes() {
1226: return findHomes(false).size() > 0;
1227: }
1228:
1229: public void addConsumer(FormConsumer consumer) {
1230: getFormConsumers().add(consumer);
1231: }
1232:
1233: public ArtifactFinder getArtifactFinder() {
1234: return artifactFinder;
1235: }
1236:
1237: public void setArtifactFinder(ArtifactFinder artifactFinder) {
1238: this .artifactFinder = artifactFinder;
1239: }
1240:
1241: public int getExpressionMax() {
1242: return expressionMax;
1243: }
1244:
1245: public void setExpressionMax(int expressionMax) {
1246: this .expressionMax = expressionMax;
1247: }
1248:
1249: protected ByteArrayOutputStream loadResource(String name) {
1250: ByteArrayOutputStream bos = new ByteArrayOutputStream();
1251: InputStream is = getClass().getResourceAsStream(name);
1252:
1253: try {
1254: int c = is.read();
1255: while (c != -1) {
1256: bos.write(c);
1257: c = is.read();
1258: }
1259: bos.flush();
1260: } catch (IOException e) {
1261: throw new RuntimeException(e);
1262: } finally {
1263: try {
1264: is.close();
1265: } catch (IOException e) {
1266: //can't do anything now..
1267: if (logger.isDebugEnabled()) {
1268: logger.debug(e);
1269: }
1270: }
1271: }
1272: return bos;
1273: }
1274:
1275: protected String createResource(String resourceLocation,
1276: String name, String description, String type,
1277: boolean replace, boolean pubview) {
1278: ByteArrayOutputStream bos = loadResource(resourceLocation);
1279: ContentResource resource;
1280: ResourcePropertiesEdit resourceProperties = getContentHosting()
1281: .newResourceProperties();
1282: resourceProperties.addProperty(
1283: ResourceProperties.PROP_DISPLAY_NAME, name);
1284: resourceProperties.addProperty(
1285: ResourceProperties.PROP_DESCRIPTION, description);
1286: resourceProperties.addProperty(
1287: ResourceProperties.PROP_CONTENT_ENCODING, "UTF-8");
1288:
1289: String folder = "/group/PortfolioAdmin" + SYSTEM_COLLECTION_ID;
1290:
1291: try {
1292: //TODO use the bean org.theospi.portfolio.admin.model.IntegrationOption.siteOption
1293: // in common/components to get the name and id for this site.
1294:
1295: ContentCollectionEdit groupCollection = getContentHosting()
1296: .addCollection("/group/PortfolioAdmin");
1297: groupCollection.getPropertiesEdit().addProperty(
1298: ResourceProperties.PROP_DISPLAY_NAME,
1299: "Portfolio Admin");
1300: getContentHosting().commitCollection(groupCollection);
1301: } catch (IdUsedException e) {
1302: // ignore... it is already there.
1303: if (logger.isDebugEnabled()) {
1304: logger.debug(e);
1305: }
1306: } catch (Exception e) {
1307: throw new RuntimeException(e);
1308: }
1309:
1310: try {
1311: ContentCollectionEdit collection = getContentHosting()
1312: .addCollection(folder);
1313: collection.getPropertiesEdit().addProperty(
1314: ResourceProperties.PROP_DISPLAY_NAME, "system");
1315: getContentHosting().commitCollection(collection);
1316:
1317: } catch (IdUsedException e) {
1318: // ignore... it is already there.
1319: if (logger.isDebugEnabled()) {
1320: logger.debug(e);
1321: }
1322: } catch (Exception e) {
1323: throw new RuntimeException(e);
1324: }
1325:
1326: try {
1327: String id = folder + name;
1328: if (!replace) {
1329: ContentResource testResource = getContentHosting()
1330: .getResource(id);
1331: if (testResource != null) {
1332: return testResource.getId();
1333: }
1334: }
1335: getContentHosting().removeResource(id);
1336: } catch (TypeException e) {
1337: // ignore, must be new
1338: if (logger.isDebugEnabled()) {
1339: logger.debug(e);
1340: }
1341: } catch (IdUnusedException e) {
1342: // ignore, must be new
1343: if (logger.isDebugEnabled()) {
1344: logger.debug(e);
1345: }
1346: } catch (PermissionException e) {
1347: // ignore, must be new
1348: if (logger.isDebugEnabled()) {
1349: logger.debug(e);
1350: }
1351: } catch (InUseException e) {
1352: // ignore, must be new
1353: if (logger.isDebugEnabled()) {
1354: logger.debug(e);
1355: }
1356: }
1357:
1358: try {
1359: resource = getContentHosting().addResource(name, folder,
1360: 100, type, bos.toByteArray(), resourceProperties,
1361: NotificationService.NOTI_NONE);
1362: getContentHosting().setPubView(resource.getId(), pubview);
1363: } catch (Exception e) {
1364: throw new RuntimeException(e);
1365: }
1366: return resource.getId();
1367: }
1368:
1369: public boolean isReplaceViews() {
1370: return replaceViews;
1371: }
1372:
1373: public void setReplaceViews(boolean replaceViews) {
1374: this .replaceViews = replaceViews;
1375: }
1376:
1377: public List getFormConsumers() {
1378: return formConsumers;
1379: }
1380:
1381: public void setFormConsumers(List formConsumers) {
1382: this .formConsumers = formConsumers;
1383: }
1384:
1385: public boolean checkFormConsumption(Id formId) {
1386: String type = formId.getValue();
1387:
1388: getSecurityService().pushAdvisor(new SecurityAdvisor() {
1389: public SecurityAdvice isAllowed(String userId,
1390: String function, String reference) {
1391: return SecurityAdvice.ALLOWED;
1392: }
1393: });
1394:
1395: try {
1396: Collection arts = getStructuredArtifactFinder().findByType(
1397: type);
1398:
1399: return arts != null && arts.size() > 0;
1400: } finally {
1401: getSecurityService().popAdvisor();
1402: }
1403: }
1404:
1405: public SecurityService getSecurityService() {
1406: return securityService;
1407: }
1408:
1409: public void setSecurityService(SecurityService securityService) {
1410: this .securityService = securityService;
1411: }
1412:
1413: public ArtifactFinder getStructuredArtifactFinder() {
1414: return structuredArtifactFinder;
1415: }
1416:
1417: public void setStructuredArtifactFinder(
1418: ArtifactFinder structuredArtifactFinder) {
1419: this .structuredArtifactFinder = structuredArtifactFinder;
1420: }
1421:
1422: public boolean isAutoDdl() {
1423: return autoDdl;
1424: }
1425:
1426: public void setAutoDdl(boolean autoDdl) {
1427: this.autoDdl = autoDdl;
1428: }
1429: }
|