001/*
002 * (C) Copyright 2016 Nuxeo SA (http://nuxeo.com/) and others.
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 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.ecm.core.api;
020
021import java.util.ArrayList;
022import java.util.List;
023import java.util.Map;
024import java.util.concurrent.ConcurrentHashMap;
025
026import org.nuxeo.ecm.core.api.local.LocalSession;
027import org.nuxeo.runtime.model.DefaultComponent;
028
029/**
030 * Implementation for the service managing the acquisition/release of {@link CoreSession} instances.
031 *
032 * @since 8.4
033 */
034public class CoreSessionServiceImpl extends DefaultComponent implements CoreSessionService {
035
036    /**
037     * All open {@link CoreSessionRegistrationInfo}, keyed by session id.
038     */
039    private final Map<String, CoreSessionRegistrationInfo> sessions = new ConcurrentHashMap<String, CoreSessionRegistrationInfo>();
040
041    @Override
042    public CoreSession createCoreSession(String repositoryName, NuxeoPrincipal principal) {
043        LocalSession session = new LocalSession(repositoryName, principal);
044        sessions.put(session.getSessionId(), new CoreSessionRegistrationInfo(session));
045        return session;
046    }
047
048    @Override
049    public void releaseCoreSession(CoreSession session) {
050        String sessionId = session.getSessionId();
051        CoreSessionRegistrationInfo info = sessions.remove(sessionId);
052        if (info == null) {
053            throw new RuntimeException("Closing unknown CoreSession: " + sessionId, info);
054        }
055        session.destroy();
056    }
057
058    @Override
059    public CoreSession getCoreSession(String sessionId) {
060        if (sessionId == null) {
061            throw new NullPointerException("null sessionId");
062        }
063        CoreSessionRegistrationInfo info = sessions.get(sessionId);
064        return info == null ? null : info.getCoreSession();
065    }
066
067    @Override
068    public int getNumberOfOpenCoreSessions() {
069        return sessions.size();
070    }
071
072    @Override
073    public List<CoreSessionRegistrationInfo> getCoreSessionRegistrationInfos() {
074        return new ArrayList<>(sessions.values());
075    }
076
077}