001/*
002 *  Copyright 2010 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.cms.workflow;
017
018import java.util.Collections;
019import java.util.Enumeration;
020import java.util.HashMap;
021import java.util.Map;
022
023import org.apache.avalon.framework.parameters.Parameters;
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.cocoon.environment.ObjectModelHelper;
027import org.apache.cocoon.environment.Redirector;
028import org.apache.cocoon.environment.Request;
029import org.apache.commons.lang3.StringUtils;
030
031import org.ametys.cms.contenttype.ContentType;
032import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
033import org.ametys.core.cocoon.ActionResultGenerator;
034import org.ametys.core.util.JSONUtils;
035import org.ametys.plugins.workflow.AbstractWorkflowComponent;
036import org.ametys.plugins.workflow.cocoon.InitializeWorkflowAction;
037import org.ametys.plugins.workflow.support.WorkflowProvider.AmetysObjectWorkflow;
038
039import com.opensymphony.workflow.InvalidInputException;
040import com.opensymphony.workflow.WorkflowException;
041
042/**
043 * Action for initializing a transition on a content's workflow.<p>
044 * The following parameters are supported:
045 * <dl>
046 *  <dt>workflowName
047 *  <dd>the name of the workflow to instantiate
048 *  <dt>actionId
049 *  <dd>the id of the action to fire
050 * </dl>
051 */
052public class InitializeContentWorkflowAction extends InitializeWorkflowAction
053{
054    /** Constant for storing the content type to use into the transient variables map. */
055    private static final String __CONTENT_TYPE_KEY = CreateContentFunction.class.getName() + "$contentType";
056    /** Constant for storing the content type to use into the transient variables map. */
057    private static final String _CONTENT_MIXINS_KEY = CreateContentFunction.class.getName() + "$mixins";
058    /** Constant for storing the content title variant to use into the transient variables map. */
059    private static final String __CONTENT_TITLE_VARIANTS_KEY = CreateContentFunction.class.getName() + "$contentTitleVariants";
060    
061    private static final String REQUEST_PARAMETER_PREFIX = "workflow-";
062    
063    private static final String __DEFAULT_WORKFLOW_NAME = "content";
064    
065    /** The JSON utils */
066    protected JSONUtils _jsonUtils;
067    /** The content type extension point */
068    protected ContentTypeExtensionPoint _cTypeEP;
069    
070    @Override
071    public void service(ServiceManager smanager) throws ServiceException
072    {
073        super.service(smanager);
074        _jsonUtils = (JSONUtils) smanager.lookup(JSONUtils.ROLE);
075        _cTypeEP = (ContentTypeExtensionPoint) smanager.lookup(ContentTypeExtensionPoint.ROLE);
076    }
077    
078    @Override
079    protected Map _act(Redirector redirector, Map objectModel, String source, Parameters parameters, int actionId, Map inputs) throws InvalidInputException, WorkflowException
080    {
081        AmetysObjectWorkflow workflow = _workflowProvider.getAmetysObjectWorkflow();
082        long workflowId = workflow.initialize(_getWorkflowName(objectModel, source, parameters), actionId, inputs);
083        return _getActionResult(redirector, objectModel, source, parameters, workflowId);
084    }
085    
086    @Override
087    protected Map<String, Object> _getInputs(Redirector redirector, Map objectModel, String source, Parameters parameters) throws Exception
088    {
089        Map<String, Object> inputs =  super._getInputs(redirector, objectModel, source, parameters);
090
091        // Provide the parameters
092        inputs.putAll(_getParameters(objectModel));
093        
094        // Provide a map for providing data to the generator
095        Request request = ObjectModelHelper.getRequest(objectModel);
096        Map<String, Object> result = new HashMap<>();
097        request.setAttribute(ActionResultGenerator.MAP_REQUEST_ATTR, result);
098        inputs.put(AbstractWorkflowComponent.RESULT_MAP_KEY, result);
099        
100        return inputs;
101    }
102    
103    @Override
104    protected String _getWorkflowName(Map objectModel, String source, Parameters parameters)
105    {
106        String workflowName = ObjectModelHelper.getRequest(objectModel).getParameter(REQUEST_PARAMETER_PREFIX + "workflowName");
107        
108        if (StringUtils.isEmpty(workflowName))
109        {
110            // Get default workflow from content type
111            String cTypeId = ObjectModelHelper.getRequest(objectModel).getParameter(REQUEST_PARAMETER_PREFIX + __CONTENT_TYPE_KEY);
112            ContentType contentType = _cTypeEP.getExtension(cTypeId);
113            
114            workflowName = contentType.getDefaultWorkflowName().orElse(__DEFAULT_WORKFLOW_NAME);
115        }
116        
117        return workflowName;
118    }
119    
120    /**
121     * Return a map of parameters needed by the workflow that will create the content
122     * @param objectModel The cocoon object model
123     * @return the map with parameters
124     */
125    protected Map<String, Object> _getParameters(Map objectModel)
126    {
127        Map<String, Object> parameters = new HashMap<>();
128        
129        Request request = ObjectModelHelper.getRequest(objectModel);
130        Enumeration<String> parameterNames = request.getParameterNames();
131        
132        while (parameterNames.hasMoreElements())
133        {
134            String parameterName = parameterNames.nextElement();
135            if (parameterName.startsWith(REQUEST_PARAMETER_PREFIX))
136            {
137                String name = parameterName.substring(REQUEST_PARAMETER_PREFIX.length());
138                String value = request.getParameter(parameterName);
139                
140                if (name.equals(__CONTENT_TYPE_KEY))
141                {
142                    parameters.put(CreateContentFunction.CONTENT_TYPES_KEY, new String[] {value});
143                }
144                else if (name.equals(_CONTENT_MIXINS_KEY))
145                {
146                    parameters.put(CreateContentFunction.CONTENT_MIXINS_KEY, new String[] {value});
147                }
148                else if (name.equals(__CONTENT_TITLE_VARIANTS_KEY))
149                {
150                    parameters.put(CreateContentFunction.CONTENT_TITLE_VARIANTS_KEY, _jsonUtils.convertJsonToMap(value));
151                }
152                else
153                {
154                    parameters.put(name, value);
155                }
156            }
157        }
158        
159        return parameters;
160    }
161    
162    @Override
163    protected Map _processWorkflowException(Redirector redirector, Map objectModel, String source, Parameters parameters, long actionId, WorkflowException e) throws Exception
164    {
165        if (e instanceof InvalidInputWorkflowException)
166        {
167            // Validation error
168            if (getLogger().isDebugEnabled())
169            {
170                getLogger().debug("Validation error while executing workflow action", e);
171            }
172            
173            return Collections.EMPTY_MAP;
174        }
175        else
176        {
177            // Real error
178            return super._processWorkflowException(redirector, objectModel, source, parameters, actionId, e);
179        }
180    }
181}