001/*
002 *  Copyright 2011 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.odf.workflow;
017
018import java.util.Map;
019import java.util.Optional;
020
021import org.apache.commons.lang3.StringUtils;
022
023import org.ametys.cms.repository.ModifiableContent;
024import org.ametys.cms.workflow.EditContentFunction;
025import org.ametys.odf.ProgramItem;
026
027import com.opensymphony.workflow.WorkflowException;
028
029/**
030 * Abstract OSWorkflow function for creating a {@link ProgramItem} content
031 * Populate catalog and code metadata.
032 */
033public abstract class AbstractCreateODFProgramItemFunction extends AbstractCreateODFContentFunction
034{
035    @Override
036    protected void _populateAdditionalData(Map transientVars, ModifiableContent content) throws WorkflowException
037    {
038        super._populateAdditionalData(transientVars, content);
039        
040        if (content instanceof ProgramItem)
041        {
042            Optional<String> catalog = Optional.ofNullable(transientVars.get(CONTENT_CATALOG_KEY))
043                    .map(String.class::cast)
044                    .filter(StringUtils::isNotEmpty);
045            
046            if (!catalog.isPresent())
047            {
048                catalog = Optional.ofNullable(getContextParameters(transientVars))
049                        .map(params -> params.get(EditContentFunction.FORM_RAW_VALUES))
050                        .map(Map.class::cast)
051                        .map(rawValues -> rawValues.get(EditContentFunction.FORM_ELEMENTS_PREFIX + ProgramItem.METADATA_CATALOG))
052                        .map(String.class::cast)
053                        .filter(StringUtils::isNotEmpty);
054            }
055            
056            catalog.ifPresent(c -> ((ProgramItem) content).setCatalog(c));
057        }
058        
059        String code = content.getMetadataHolder().getString(ProgramItem.METADATA_CODE, null);
060        if (org.apache.commons.lang.StringUtils.isEmpty(code))
061        {
062            content.getMetadataHolder().setMetadata(ProgramItem.METADATA_CODE, org.ametys.core.util.StringUtils.generateKey().toUpperCase());
063        }
064    }
065
066}