| 1 | package org.jtoolkit.essence.utils; |
| 2 | |
| 3 | import org.jetbrains.annotations.NotNull; |
| 4 | import org.jetbrains.annotations.Nullable; |
| 5 | import org.jtoolkit.essence.utils.impl.OneToManyMap; |
| 6 | |
| 7 | import java.util.Set; |
| 8 | |
| 9 | /* |
| 10 | Copyright 2006 Peter Lawrey |
| 11 | |
| 12 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 13 | you may not use this file except in compliance with the License. |
| 14 | You may obtain a copy of the License at |
| 15 | |
| 16 | http://www.apache.org/licenses/LICENSE-2.0 |
| 17 | |
| 18 | Unless required by applicable law or agreed to in writing, software |
| 19 | distributed under the License is distributed on an "AS IS" BASIS, |
| 20 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 21 | See the License for the specific language governing permissions and |
| 22 | limitations under the License. |
| 23 | */ |
| 24 | |
| 25 | /** |
| 26 | * Every N requests a new file name is created. |
| 27 | * |
| 28 | * @author Peter Lawrey |
| 29 | */ |
| 30 | public class FilenameMap<K> { |
| 31 | // private static final Log LOG = LogFactory.getLog(FilenameMap.class); |
| 32 | |
| 33 | private final OneToManyMap<String, K> filenameToKey = new OneToManyMap<String, K>(); |
| 34 | |
| 35 | @SuppressWarnings({"FieldHasSetterButNoGetter"}) |
| 36 | private int targetCount = 1; |
| 37 | |
| 38 | private String lastFilename = null; |
| 39 | private int keyCount = 0; |
| 40 | |
| 41 | public void setTargetCount(int targetCount) { |
| 42 | this.targetCount = targetCount; |
| 43 | } |
| 44 | |
| 45 | @NotNull public String acquireFilenameForKey(@NotNull K key) { |
| 46 | String filenameForKey = filenameToKey.getKey(key); |
| 47 | if (filenameForKey != null) |
| 48 | return filenameForKey; |
| 49 | |
| 50 | if (lastFilename == null || keyCount++ > targetCount) { |
| 51 | lastFilename = 'D' + Long.toString(System.nanoTime(), Character.MAX_RADIX) + ".dat"; |
| 52 | keyCount = 0; |
| 53 | } |
| 54 | filenameToKey.put(lastFilename, key); |
| 55 | return lastFilename; |
| 56 | } |
| 57 | |
| 58 | public void put(@NotNull String filename, @NotNull K key) { |
| 59 | filenameToKey.put(filename, key); |
| 60 | } |
| 61 | |
| 62 | public void clear() { |
| 63 | filenameToKey.clear(); |
| 64 | } |
| 65 | |
| 66 | @Nullable public Set<K> getKeysForFilename(String filename) { |
| 67 | return filenameToKey.getValues(filename); |
| 68 | } |
| 69 | |
| 70 | public void removeFilename(String filename) { |
| 71 | filenameToKey.removeKey(filename); |
| 72 | } |
| 73 | } |