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.fcrepo.mint;
017
018import static com.codahale.metrics.MetricRegistry.name;
019import static java.util.UUID.randomUUID;
020
021import java.util.stream.IntStream;
022import java.util.StringJoiner;
023
024import org.fcrepo.metrics.RegistryService;
025import org.fcrepo.kernel.api.services.functions.HierarchicalIdentifierSupplier;
026
027import com.codahale.metrics.Timer;
028
029/**
030 * PID minter that creates hierarchical IDs for a UUID
031 *
032 * @author awoods
033 */
034public class UUIDPathMinter implements HierarchicalIdentifierSupplier {
035
036    static final Timer timer = RegistryService.getInstance().getMetrics().timer(
037            name(UUIDPathMinter.class, "mint"));
038
039    private final int length;
040
041    private final int count;
042
043    /**
044     * Configure the path minter using some reasonable defaults for the length
045     * and count of the branch nodes
046     */
047    public UUIDPathMinter() {
048        this(DEFAULT_LENGTH, DEFAULT_COUNT);
049    }
050
051    /**
052     * Configure the path minter for the length of the keys and depth of the
053     * branch node prefix
054     *
055     * @param length how long the branch node identifiers should be
056     * @param count how many branch nodes should be inserted
057     */
058    public UUIDPathMinter(final int length, final int count) {
059        super();
060        this.length = length;
061        this.count = count;
062    }
063
064    /**
065     * Mint a unique identifier as a UUID
066     *
067     * @return uuid
068     */
069    @Override
070    public String get() {
071
072        try (final Timer.Context context = timer.time()) {
073            final String s = randomUUID().toString();
074
075            if (length == 0 || count == 0) {
076                return s;
077            }
078
079            final StringJoiner joiner = new StringJoiner("/", "", "/" + s);
080            IntStream.rangeClosed(0, count - 1)
081                     .forEach(x -> joiner.add(s.substring(x * length, (x + 1) * length)));
082
083            return joiner.toString();
084        }
085    }
086}