View Javadoc
1   /**
2    * Copyright (C) 2014-2015 Philip Helger (www.helger.com)
3    * philip[at]helger[dot]com
4    *
5    * Licensed under the Apache License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    *         http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package com.helger.schematron.pure.preprocess;
18  
19  import java.util.HashSet;
20  import java.util.Set;
21  
22  import javax.annotation.Nullable;
23  import javax.annotation.concurrent.NotThreadSafe;
24  
25  import com.helger.commons.string.ToStringGenerator;
26  
27  /**
28   * Utility lookup cache for all used IDs within a schema.
29   * 
30   * @author Philip Helger
31   */
32  @NotThreadSafe
33  final class PreprocessorIDPool
34  {
35    private final Set <String> m_aUsedIDs = new HashSet <String> ();
36  
37    public PreprocessorIDPool ()
38    {}
39  
40    /**
41     * Create a unique ID based on the passed one. If the passed ID is not yet
42     * contained, than a numeric index is appended until the ID is unique.
43     * 
44     * @param sID
45     *        The source ID. May be <code>null</code>.
46     * @return <code>null</code> if the passed ID is <code>null</code> indicating
47     *         that no ID is present. Otherwise a unique ID is returned.
48     */
49    @Nullable
50    public String getUniqueID (@Nullable final String sID)
51    {
52      if (sID == null)
53        return null;
54  
55      if (m_aUsedIDs.add (sID))
56      {
57        // Unique ID
58        return sID;
59      }
60  
61      // Non-unique ID
62      int nIndex = 0;
63      String sNewID = sID + nIndex;
64      do
65      {
66        if (m_aUsedIDs.add (sNewID))
67        {
68          // Now it's unique
69          return sNewID;
70        }
71        ++nIndex;
72        sNewID = sID + nIndex;
73      } while (true);
74    }
75  
76    @Override
77    public String toString ()
78    {
79      return new ToStringGenerator (this).append ("usedIDs", m_aUsedIDs).toString ();
80    }
81  }