001/*
002 *  Copyright 2020 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.web.scripts;
017
018import java.util.HashMap;
019import java.util.Map;
020
021import javax.jcr.Credentials;
022import javax.jcr.Repository;
023import javax.jcr.Session;
024
025import org.apache.avalon.framework.service.ServiceException;
026import org.apache.avalon.framework.service.ServiceManager;
027
028import org.ametys.plugins.core.ui.script.ScriptExecArguments;
029import org.ametys.plugins.core.ui.script.StaticConfigurableScriptBinding;
030import org.ametys.plugins.repositoryapp.RepositoryProvider;
031import org.ametys.web.WebConstants;
032
033/**
034 * Script binding that provides variables
035 */
036public class WebScriptBinding extends StaticConfigurableScriptBinding
037{
038    private RepositoryProvider _repositoryProvider;
039
040    @Override
041    public void service(ServiceManager serviceManager) throws ServiceException
042    {
043        super.service(serviceManager);
044        _repositoryProvider = (RepositoryProvider) serviceManager.lookup(RepositoryProvider.ROLE);
045    }
046    
047    @Override
048    public Map<String, Object> getVariables(ScriptExecArguments execArgs)
049    {
050        Map<String, Object> variables = new HashMap<>();
051        Repository repository = _repositoryProvider.getRepository();
052        Credentials credentials = _repositoryProvider.getCredentials();
053        Session session;
054        
055        try
056        {
057            session = repository.login(credentials, WebConstants.LIVE_WORKSPACE);
058        }
059        catch (Exception e)
060        {
061            getLogger().warn("Unable to provides the JavaScript console with repository variables.", e);
062            session = null;
063        }
064
065        variables.put("__internal_repository_livesession", session);
066        return variables;
067    }
068
069    @Override
070    public void cleanVariables(Map<String, Object> variables)
071    {
072        if (variables.containsKey("__internal_repository_livesession"))
073        {
074            Object session = variables.get("__internal_repository_livesession");
075            if (session != null && session instanceof Session)
076            {
077                ((Session) session).logout();
078                variables.remove("__internal_repository_livesession");
079            }
080        }
081    }
082}