001/**
002 * Copyright 2015 DuraSpace, Inc.
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.modeshape.connector.filesystem;
017
018import org.modeshape.jcr.cache.document.DocumentTranslator;
019
020import java.io.File;
021import java.nio.file.Path;
022
023/**
024 * An extension of JsonSidecarExtraPropertyStore that stores the properties in a
025 * separate configured directory than the filesystem federation itself.  Because
026 * the class we're extending is package protected this class is in the
027 * org.modeshape.connector.filesystem package.
028 *
029 * @author Mike Durbin
030 */
031public class ExternalJsonSidecarExtraPropertyStore extends JsonSidecarExtraPropertyStore {
032
033    private FileSystemConnector connector;
034
035    private File propertyStoreRoot;
036
037    /**
038     * Default constructor.
039     * @param connector the FileSystemConnector for which this class will store properties.
040     * @param propertyStoreRoot the root of a filesystem into which properties will be
041     *                          serialized.
042     */
043    public ExternalJsonSidecarExtraPropertyStore(final FileSystemConnector connector,
044                                                 final DocumentTranslator translator,
045                                                 final File propertyStoreRoot) {
046        super(connector, translator);
047        this.connector = connector;
048        this.propertyStoreRoot = propertyStoreRoot;
049    }
050
051    @Override
052    protected File sidecarFile(final String id) {
053        final File file;
054        if (connector.isRoot(id)) {
055            file = new File(propertyStoreRoot, "federation-root.modeshape.json");
056        } else {
057            final Path propertyFileInFederation = super.sidecarFile(id).getAbsoluteFile().toPath();
058            final Path relativePath
059                    = connector.fileFor("/").getAbsoluteFile().toPath().relativize(propertyFileInFederation);
060            file = propertyStoreRoot.toPath().resolve(relativePath).toFile();
061        }
062        if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
063            throw new RuntimeException("Unable to create directories " + file.getParentFile() + ".");
064        }
065        return file;
066    }
067}