001/*
002 * (C) Copyright 2006-2014 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.opencmis.impl.server;
020
021import java.util.ArrayList;
022import java.util.List;
023import java.util.Map;
024import java.util.concurrent.ConcurrentHashMap;
025
026import org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException;
027import org.nuxeo.ecm.core.api.CoreInstance;
028import org.nuxeo.ecm.core.api.CoreSession;
029import org.nuxeo.ecm.core.api.repository.RepositoryManager;
030import org.nuxeo.runtime.api.Framework;
031import org.nuxeo.runtime.model.ComponentContext;
032import org.nuxeo.runtime.model.DefaultComponent;
033
034/**
035 * Information about all Nuxeo repositories.
036 * <p>
037 * Information is cached, and an initial connection to the repository is needed to get the root folder id.
038 */
039public class NuxeoRepositories extends DefaultComponent {
040
041    protected Map<String, NuxeoRepository> repositories;
042
043    @Override
044    public void activate(ComponentContext context) {
045        repositories = new ConcurrentHashMap<String, NuxeoRepository>();
046    }
047
048    @Override
049    public void deactivate(ComponentContext context) {
050        repositories = null;
051    }
052
053    public NuxeoRepository getRepository(String repositoryId) {
054        initRepositories();
055        return repositories.get(repositoryId);
056    }
057
058    public List<NuxeoRepository> getRepositories() {
059        initRepositories();
060        return new ArrayList<NuxeoRepository>(repositories.values());
061    }
062
063    protected void initRepositories() {
064        if (!repositories.isEmpty()) {
065            return;
066        }
067        RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class);
068        for (String repositoryName : repositoryManager.getRepositoryNames()) {
069            try (CoreSession coreSession = CoreInstance.openCoreSession(repositoryName)) {
070                String rootFolderId = coreSession.getRootDocument().getId();
071                repositories.put(repositoryName, new NuxeoRepository(repositoryName, rootFolderId));
072            }
073        }
074    }
075
076}