/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see .
*/
package org.alfresco.web.bean.wcm;
import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import org.springframework.extensions.config.Config;
import org.springframework.extensions.config.ConfigElement;
import org.springframework.extensions.config.ConfigService;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.model.WCMAppModel;
import org.alfresco.repo.avm.AVMNodeConverter;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.domain.PropertyValue;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.repo.web.scripts.FileTypeImageUtils;
import org.alfresco.service.cmr.avm.AVMExistsException;
import org.alfresco.service.cmr.avm.AVMNodeDescriptor;
import org.alfresco.service.cmr.avm.AVMService;
import org.alfresco.service.cmr.avm.locking.AVMLock;
import org.alfresco.service.cmr.avm.locking.AVMLockingService;
import org.alfresco.service.cmr.avmsync.AVMDifference;
import org.alfresco.service.cmr.avmsync.AVMSyncService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.web.app.AlfrescoNavigationHandler;
import org.alfresco.web.app.Application;
import org.alfresco.web.app.servlet.FacesHelper;
import org.alfresco.web.bean.content.CreateContentWizard;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.data.IDataContainer;
import org.alfresco.web.data.QuickSort;
import org.alfresco.web.forms.Form;
import org.alfresco.web.forms.FormInstanceData;
import org.alfresco.web.forms.FormNotFoundException;
import org.alfresco.web.forms.FormsService;
import org.alfresco.web.forms.RenderingEngineTemplate;
import org.alfresco.web.forms.Rendition;
import org.alfresco.web.forms.XMLUtil;
import org.alfresco.web.ui.common.Utils;
import org.alfresco.web.ui.common.component.UIListItem;
import org.alfresco.web.ui.wcm.component.UIUserSandboxes;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
/**
* Bean implementation for the "Create Web Content Wizard" dialog
*/
public class CreateWebContentWizard extends CreateContentWizard
{
private static final long serialVersionUID = -4090370304405270047L;
private static final Log logger = LogFactory.getLog(CreateWebContentWizard.class);
transient private List formChoices;
protected String createdPath = null;
protected List renditions = null;
protected FormInstanceData formInstanceData = null;
protected boolean formSelectDisabled = false;
protected boolean startWorkflow = false;
protected List locksToReturnToMainStoreOnCancel = null;
protected String formDescriptionAttribute;
transient private AVMLockingService avmLockingService;
transient private AVMService avmService;
transient private AVMSyncService avmSyncService;
protected AVMBrowseBean avmBrowseBean;
protected FilePickerBean filePickerBean;
/**
* @param avmService The AVMService to set.
*/
public void setAvmService(final AVMService avmService)
{
this.avmService = avmService;
}
protected AVMService getAvmService()
{
if (avmService == null)
{
avmService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAVMLockingAwareService();
}
return avmService;
}
/**
* @param avmLockingService The AVMLockingService to set.
*/
public void setAvmLockingService(final AVMLockingService avmLockingService)
{
this.avmLockingService = avmLockingService;
}
protected AVMLockingService getAvmLockingService()
{
if (avmLockingService == null)
{
avmLockingService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAVMLockingService();
}
return avmLockingService;
}
/**
* @param avmSyncService The AVMSyncService to set.
*/
public void setAvmSyncService(final AVMSyncService avmSyncService)
{
this.avmSyncService = avmSyncService;
}
protected AVMSyncService getAvmSyncService()
{
if (avmSyncService == null)
{
avmSyncService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAVMSyncService();
}
return avmSyncService;
}
/**
* @param avmBrowseBean The AVMBrowseBean to set.
*/
public void setAvmBrowseBean(final AVMBrowseBean avmBrowseBean)
{
this.avmBrowseBean = avmBrowseBean;
}
/**
* @param filePickerBean The FilePickerBean to set.
*/
public void setFilePickerBean(final FilePickerBean filePickerBean)
{
this.filePickerBean = filePickerBean;
}
/**
* @param formsService The FormsService to set.
*/
public void setFormsService(final FormsService formsService)
{
this.formsService = formsService;
}
protected FormsService getFormsService()
{
if (formsService == null)
{
formsService = (FormsService) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "FormsService");
}
return formsService;
}
// ------------------------------------------------------------------------------
// Wizard implementation
@Override
public void init(Map parameters)
{
super.init(parameters);
this.content = null;
this.inlineEdit = true;
this.formName = null;
this.mimeType = MimetypeMap.MIMETYPE_XML;
this.formInstanceData = null;
this.renditions = null;
this.startWorkflow = false;
this.formSelectDisabled = false;
this.createMimeTypes = null;
this.formChoices = null;
this.filePickerBean.clearUploadedFiles();
this.locksToReturnToMainStoreOnCancel = new ArrayList(4);
// check for a form ID being passed in as a parameter
if (this.parameters.get(UIUserSandboxes.PARAM_FORM_NAME) != null)
{
// it is used to init the dialog to a specific template
final String formName = parameters.get(UIUserSandboxes.PARAM_FORM_NAME);
try
{
final Form form = this.avmBrowseBean.getWebProject().getForm(formName);
if (form != null)
{
this.formName = form.getName();
this.formSelectDisabled = true;
}
}
catch (FormNotFoundException fnfe)
{
Utils.addErrorMessage(fnfe.getMessage(), fnfe);
}
}
// this.formDescriptionAttribute = buildFormDescriptionAttribute();
// reset the preview layer
String storeName = AVMUtil.getStoreName(this.avmBrowseBean.getCurrentPath());
storeName = AVMUtil.getCorrespondingPreviewStoreName(storeName);
final String path = AVMUtil.buildStoreRootPath(storeName);
FacesContext context = FacesContext.getCurrentInstance();
RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context);
RetryingTransactionCallback callback = new RetryingTransactionCallback()
{
public String execute() throws Throwable
{
if (logger.isDebugEnabled())
logger.debug("reseting layer " + path);
// call the actual implementation
getAvmSyncService().resetLayer(path);
return null;
}
};
try
{
// Execute
txnHelper.doInTransaction(callback);
}
catch (Exception e)
{
Utils.addErrorMessage(e.getMessage(), e);
}
}
@Override
public String next()
{
if ("summary".equals(Application.getWizardManager().getCurrentStepName()))
{
// if rendering a form, then save the content now to generate the renditions
if (MimetypeMap.MIMETYPE_XML.equals(this.mimeType))
{
FacesContext context = FacesContext.getCurrentInstance();
RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context);
RetryingTransactionCallback callback = new RetryingTransactionCallback()
{
public String execute() throws Throwable
{
// call the actual implementation
saveContent();
return null;
}
};
try
{
// Execute
txnHelper.doInTransaction(callback);
}
catch (Exception e)
{
Application.getWizardManager().getState().setCurrentStep(Application.getWizardManager().getCurrentStep() - 1);
Utils.addErrorMessage(e.getMessage(), e);
}
}
}
return super.next();
}
@Override
public String back()
{
if ("content".equals(Application.getWizardManager().getCurrentStepName()))
{
FacesContext context = FacesContext.getCurrentInstance();
RetryingTransactionHelper txnHelper = Repository.getRetryingTransactionHelper(context);
RetryingTransactionCallback callback = new RetryingTransactionCallback()
{
public String execute() throws Throwable
{
if (formInstanceData != null)
{
if (logger.isDebugEnabled())
logger.debug("clearing form instance data: " + formInstanceData.getPath());
getAvmService().removeNode(formInstanceData.getPath());
}
if (renditions != null)
{
for (Rendition r : renditions)
{
getAvmService().removeNode(r.getPath());
}
}
return null;
}
};
try
{
// Execute
txnHelper.doInTransaction(callback);
}
catch (Exception e)
{
Utils.addErrorMessage(e.getMessage(), e);
}
this.formInstanceData = null;
this.renditions = null;
}
return super.back();
}
@Override
public String cancel()
{
if (this.formInstanceData != null && this.renditions != null)
{
if (this.locksToReturnToMainStoreOnCancel.size() > 0)
{
for (String path : this.locksToReturnToMainStoreOnCancel)
{
String storeId = AVMUtil.getStoreId(path);
String storePath = AVMUtil.getStoreRelativePath(path);
String storeName = AVMUtil.getStoreName(path);
String mainStore = AVMUtil.getCorrespondingMainStoreName(storeName);
if (logger.isDebugEnabled())
logger.debug("transferring lock from " + storeName + " to " + mainStore +
" for path: " + path + " as user chose to cancel");
this.getAvmLockingService().modifyLock(storeId, storePath, null, mainStore, null, null);
}
}
}
// remove any locks created as a result of uploading files
final NodeRef[] uploadedFiles = this.filePickerBean.getUploadedFiles();
if (uploadedFiles != null && uploadedFiles.length > 0)
{
for (NodeRef uploadedFile : uploadedFiles)
{
String path = AVMNodeConverter.ToAVMVersionPath(uploadedFile).getSecond();
String storeId = AVMUtil.getStoreId(path);
String storePath = AVMUtil.getStoreRelativePath(path);
if (logger.isDebugEnabled())
logger.debug("Removing lock for uploaded file: " + path);
this.getAvmLockingService().removeLock(storeId, storePath);
}
}
return super.cancel();
}
@Override
protected String finishImpl(final FacesContext context, String outcome)
throws Exception
{
if (this.formInstanceData == null || this.renditions == null)
{
this.saveContent();
}
final NodeRef[] uploadedFiles = this.filePickerBean.getUploadedFiles();
final List diffList = new ArrayList(1 + this.renditions.size() + uploadedFiles.length);
diffList.add(new AVMDifference(-1, this.createdPath, -1, AVMUtil.getCorrespondingPathInMainStore(this.createdPath), AVMDifference.NEWER));
for (Rendition rendition : this.renditions)
{
final String path = rendition.getPath();
diffList.add(new AVMDifference(-1, path, -1, AVMUtil.getCorrespondingPathInMainStore(path), AVMDifference.NEWER));
}
for (NodeRef uploadedFile : uploadedFiles)
{
final String path = AVMNodeConverter.ToAVMVersionPath(uploadedFile).getSecond();
diffList.add(new AVMDifference(-1, path, -1, AVMUtil.getCorrespondingPathInMainStore(path), AVMDifference.NEWER));
}
if (logger.isDebugEnabled())
{
for (final AVMDifference diff : diffList)
{
logger.debug("updating main store with " + diff.getSourcePath());
}
}
this.getAvmSyncService().update(diffList, null, true, true, true, true, null, null);
for (final AVMDifference diff : diffList)
{
final String path = diff.getDestinationPath();
if (logger.isDebugEnabled())
{
logger.debug("modifying lock on " + path +
". chaging store from " +
this.getAvmLockingService().getLock(AVMUtil.getStoreId(path),
AVMUtil.getStoreRelativePath(path)).getStore() +
" to " + AVMUtil.getStoreName(path));
}
this.getAvmLockingService().modifyLock(AVMUtil.getStoreId(path), AVMUtil.getStoreRelativePath(path), null, AVMUtil.getStoreName(path), null, null);
}
if (this.startWorkflow)
{
final List submitNodes = new ArrayList(1 + this.getUploadedFiles().size() + this.getRenditions().size());
for (final AVMDifference d : diffList)
{
submitNodes.add(getAvmService().lookup(-1, d.getDestinationPath()));
}
this.avmBrowseBean.setNodesForSubmit(submitNodes);
final Map dialogParams = new HashMap(1);
dialogParams.put(SubmitDialog.PARAM_LOAD_SELECTED_NODES_FROM_BROWSE_BEAN, Boolean.TRUE.toString());
Application.getDialogManager().setupParameters(dialogParams);
outcome = (outcome + AlfrescoNavigationHandler.OUTCOME_SEPARATOR + AlfrescoNavigationHandler.DIALOG_PREFIX + "submitSandboxItems");
}
if (this.formProcessorSession != null)
{
this.formProcessorSession.destroy();
}
this.filePickerBean.clearUploadedFiles();
// return the default outcome
return outcome;
}
@Override
protected String doPostCommitProcessing(final FacesContext facesContext, final String outcome)
{
// reset all paths and structures to the main store
this.createdPath = AVMUtil.getCorrespondingPathInMainStore(this.createdPath);
if (logger.isDebugEnabled())
logger.debug("reset path " + this.createdPath + " to main store");
if (MimetypeMap.MIMETYPE_XML.equals(this.mimeType) && this.formName != null)
{
this.formInstanceData = getFormsService().getFormInstanceData(-1, this.createdPath);
this.renditions = this.formInstanceData.getRenditions();
if (logger.isDebugEnabled())
logger.debug("reset form instance data " + this.formInstanceData.getName() +
" and " + this.renditions.size() + " rendition(s) to main store");
}
this.avmBrowseBean.setAvmActionNode(new AVMNode(this.getAvmService().lookup(-1, this.createdPath)));
return outcome;
}
@Override
public boolean getNextButtonDisabled()
{
// TODO: Allow the next button state to be configured so that
// wizard implementations don't have to worry about
// checking step numbers
boolean disabled = false;
if ("details".equals(Application.getWizardManager().getCurrentStepName()))
{
disabled = (this.fileName == null || this.fileName.length() == 0);
}
return disabled;
}
/**
* Save the specified content using the currently set wizard attributes
*/
@SuppressWarnings("unchecked")
protected void saveContent() throws Exception
{
// get the parent path of the location to save the content
String fileName = this.getFileName();
String contentName = fileName;
if (logger.isDebugEnabled())
logger.debug("saving file content to " + fileName);
final String cwd = AVMUtil.getCorrespondingPathInPreviewStore(this.avmBrowseBean.getCurrentPath());
final Form form = (MimetypeMap.MIMETYPE_XML.equals(this.mimeType) ? this.getForm() : null);
String path = cwd;
final Map props = new HashMap(1, 1.0f);
final List aspects = new ArrayList(4);
if (form != null)
{
path = form.getOutputPathForFormInstanceData(this.getInstanceDataDocument(), fileName, cwd, this.avmBrowseBean.getWebapp());
this.content = XMLUtil.toString(this.getInstanceDataDocument(), false);
final String[] sb = AVMNodeConverter.SplitBase(path);
path = sb[0];
fileName = sb[1];
props.put(WCMAppModel.PROP_PARENT_FORM_NAME, new PropertyValue(null, form.getName()));
props.put(WCMAppModel.PROP_ORIGINAL_PARENT_PATH, new PropertyValue(null, cwd));
aspects.add(WCMAppModel.ASPECT_FORM_INSTANCE_DATA);
}
props.put(ContentModel.PROP_TITLE, new PropertyValue(null, fileName));
aspects.add(ContentModel.ASPECT_TITLED);
if (logger.isDebugEnabled())
logger.debug("creating all directories in path " + path);
AVMUtil.makeAllDirectories(path);
if (logger.isDebugEnabled())
logger.debug("creating file " + fileName + " in " + path);
// get current username for lock checks
String username = Application.getCurrentUser(FacesContext.getCurrentInstance()).getUserName();
// put the content of the file into the AVM store
String filePath = AVMNodeConverter.ExtendAVMPath(path, fileName);
try
{
String storeId = AVMUtil.getStoreId(filePath);
String storePath = AVMUtil.getStoreRelativePath(filePath);
String storeName = AVMUtil.getStoreName(filePath);
AVMLock lock = this.getAvmLockingService().getLock(storeId, storePath);
if (lock != null && lock.getStore().equals(storeName) == false)
{
if (lock.getOwners().contains(username))
{
// lock already exists on path, check it's owned by the current user
if (logger.isDebugEnabled())
logger.debug("transferring lock from " + lock.getStore() + " to " + storeName + " for path: " + filePath);
// add the path to the list of locks to return to the preview store if cancel is pressed
this.locksToReturnToMainStoreOnCancel.add(filePath);
this.getAvmLockingService().modifyLock(storeId, storePath, null, storeName, null, null);
}
}
/**
* create the new file
*/
getAvmService().createFile(path, fileName,
new ByteArrayInputStream((this.content == null ? "" : this.content).getBytes("UTF-8")),
aspects,
props);
}
catch (AVMExistsException avmee)
{
String msg = Application.getMessage(FacesContext.getCurrentInstance(), "error_exists");
msg = MessageFormat.format(msg, fileName);
throw new AlfrescoRuntimeException(msg, avmee);
}
// remember the created path
this.createdPath = filePath;
// add titled aspect for the read/edit properties screens
final NodeRef formInstanceDataNodeRef = AVMNodeConverter.ToNodeRef(-1, this.createdPath);
/**
* Generate form renditions.
*/
if (form != null)
{
this.formInstanceData = getFormsService().getFormInstanceData(formInstanceDataNodeRef);
this.renditions = new LinkedList();
for (RenderingEngineTemplate ret : form.getRenderingEngineTemplates())
{
try
{
path = ret.getOutputPathForRendition(this.formInstanceData, cwd, contentName);
if (logger.isDebugEnabled())
logger.debug("About to render path: " + path);
String storeId = AVMUtil.getStoreId(path);
String storePath = AVMUtil.getStoreRelativePath(path);
String storeName = AVMUtil.getStoreName(path);
AVMLock lock = this.getAvmLockingService().getLock(storeId, storePath);
if (lock != null && lock.getStore().equals(storeName) == false)
{
// see if the lock belongs to the current user, if it does modify the lock to point to the preview store
if (lock.getOwners().contains(username))
{
if (logger.isDebugEnabled())
logger.debug("transferring lock from " + lock.getStore() + " to " + storeName + " for path: " + path);
// add the path to the list of locks to return to the main store if cancel is pressed
this.locksToReturnToMainStoreOnCancel.add(path);
this.getAvmLockingService().modifyLock(storeId, storePath, null, storeName, null, null);
}
}
// generate the rendition
this.renditions.add(ret.render(this.formInstanceData, path));
}
catch (Exception e)
{
// TODO - improve error handling, e.g. render could return list of errors rather than splitting on newline character
StringTokenizer st = new StringTokenizer(e.getMessage(), "\n");
if (st.hasMoreElements())
{
Utils.addErrorMessage("Error generating rendition using " + ret.getName() + ": " + st.nextToken(), e);
while (st.hasMoreElements())
{
Utils.addErrorMessage(st.nextToken(), e);
}
}
else
{
Utils.addErrorMessage("Error generating rendition using " + ret.getName() +
": " + e.getMessage(), e);
}
}
}
}
else
{
this.renditions = Collections.EMPTY_LIST;
}
}
// ------------------------------------------------------------------------------
// Bean Getters and Setters
/** Overrides in order to strip an xml extension if the user entered it */
@Override
public String getFileName()
{
final String result = super.getFileName();
return (result != null && MimetypeMap.MIMETYPE_XML.equals(this.mimeType) && this.getFormName() != null && "xml".equals(FilenameUtils.getExtension(result).toLowerCase()) ? FilenameUtils
.removeExtension(result)
: result);
}
/**
* @return Returns the content from the edited form.
*/
public String getContent()
{
return this.content;
}
/**
* @param content The content to edit (should be clear initially)
*/
public void setContent(String content)
{
this.content = content;
}
/**
* @return the available forms from this web project that can be created.
*/
public List getFormChoices()
{
if (this.formChoices == null)
{
final List