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