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