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