001/*
002 * Copyright (c) 2006-2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Florent Guillaume
011 */
012package org.nuxeo.ecm.core.opencmis.impl.server;
013
014import java.util.ArrayList;
015import java.util.List;
016import java.util.Map;
017import java.util.concurrent.ConcurrentHashMap;
018
019import org.apache.chemistry.opencmis.commons.exceptions.CmisRuntimeException;
020import org.nuxeo.ecm.core.api.CoreInstance;
021import org.nuxeo.ecm.core.api.CoreSession;
022import org.nuxeo.ecm.core.api.repository.RepositoryManager;
023import org.nuxeo.runtime.api.Framework;
024import org.nuxeo.runtime.model.ComponentContext;
025import org.nuxeo.runtime.model.DefaultComponent;
026
027/**
028 * Information about all Nuxeo repositories.
029 * <p>
030 * Information is cached, and an initial connection to the repository is needed to get the root folder id.
031 */
032public class NuxeoRepositories extends DefaultComponent {
033
034    protected Map<String, NuxeoRepository> repositories;
035
036    @Override
037    public void activate(ComponentContext context) {
038        repositories = new ConcurrentHashMap<String, NuxeoRepository>();
039    }
040
041    @Override
042    public void deactivate(ComponentContext context) {
043        repositories = null;
044    }
045
046    public NuxeoRepository getRepository(String repositoryId) {
047        initRepositories();
048        return repositories.get(repositoryId);
049    }
050
051    public List<NuxeoRepository> getRepositories() {
052        initRepositories();
053        return new ArrayList<NuxeoRepository>(repositories.values());
054    }
055
056    protected void initRepositories() {
057        if (!repositories.isEmpty()) {
058            return;
059        }
060        RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class);
061        for (String repositoryName : repositoryManager.getRepositoryNames()) {
062            try (CoreSession coreSession = CoreInstance.openCoreSession(repositoryName)) {
063                String rootFolderId = coreSession.getRootDocument().getId();
064                repositories.put(repositoryName, new NuxeoRepository(repositoryName, rootFolderId));
065            }
066        }
067    }
068
069}