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.plugins.workspaces.members;
017
018import org.apache.avalon.framework.service.ServiceException;
019
020import org.ametys.cms.model.properties.AbstractProperty;
021import org.ametys.cms.model.properties.Property;
022import org.ametys.cms.repository.Content;
023import org.ametys.core.user.UserIdentity;
024import org.ametys.plugins.workspaces.project.ProjectManager;
025import org.ametys.plugins.workspaces.project.objects.Project;
026import org.ametys.runtime.model.type.ModelItemTypeConstants;
027
028/**
029 * {@link Property} for member's projects
030 */
031public class MemberProjectProperty extends AbstractProperty<String, Content>
032{
033    private ProjectManager _projectManager;
034    
035    public Object getValue(Content content)
036    {
037        UserIdentity identity = content.getValue("user");
038
039        if (identity != null)
040        {
041            return _getProjectManager().getUserProjects(identity)
042                    .keySet()
043                    .stream()
044                    .map(Project::getId)
045                    .toArray(String[]::new);
046        }
047        else
048        {
049            return new String[0];
050        }
051    }
052    
053    @Override
054    public boolean isMultiple()
055    {
056        return true;
057    }
058
059    /**
060     * Retrieves the project manager
061     * @return the project manager
062     * @throws IllegalStateException if an error occurs
063     */
064    protected ProjectManager _getProjectManager() throws IllegalStateException
065    {
066        if (_projectManager == null)
067        {
068            try
069            {
070                _projectManager = (ProjectManager) __serviceManager.lookup(ProjectManager.ROLE);
071            }
072            catch (ServiceException e)
073            {
074                throw new IllegalStateException("Unable to lookup after the project manager component", e);
075            }
076        }
077        return _projectManager;
078    }
079
080    @Override
081    protected String _getTypeId()
082    {
083        return ModelItemTypeConstants.STRING_TYPE_ID;
084    }
085}