001/*
002 *  Copyright 2018 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.scripts;
017
018import java.util.Collection;
019import java.util.HashMap;
020import java.util.List;
021import java.util.Map;
022import java.util.Optional;
023import java.util.stream.Collectors;
024
025import org.apache.avalon.framework.service.ServiceException;
026import org.apache.avalon.framework.service.ServiceManager;
027
028import org.ametys.cms.repository.Content;
029import org.ametys.plugins.core.ui.script.ScriptExecArguments;
030import org.ametys.plugins.core.ui.script.StaticConfigurableScriptBinding;
031import org.ametys.plugins.repository.AmetysObjectResolver;
032
033/**
034 * CMS script binding, provides variables to the script tool, and a configuration file for the functions. 
035 */
036public class CmsScriptBinding extends StaticConfigurableScriptBinding
037{
038    private AmetysObjectResolver _resolver;
039    
040    @Override
041    public void service(ServiceManager manager) throws ServiceException
042    {
043        super.service(manager);
044        _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
045    }
046    
047    @Override
048    public Map<String, Object> getVariables(ScriptExecArguments execArgs)
049    {
050        Map<String, Object> variables = new HashMap<>();
051
052        Collection<String> selection = Optional.of(execArgs)
053                .filter(CmsScriptExecArguments.class::isInstance)
054                .map(CmsScriptExecArguments.class::cast)
055                .flatMap(CmsScriptExecArguments::selection)
056                .orElse(null);
057
058        List<Content> contents = null;
059        if (selection != null)
060        {
061            contents = selection.stream()
062                      .map(id -> _resolver.resolveById(id))
063                      .filter(Content.class::isInstance)
064                      .map(Content.class::cast)
065                      .collect(Collectors.toList());
066        }
067        variables.put("__internal_content_selection", contents);
068        
069        return variables;
070    }
071}