001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.util;
018    
019    import java.io.IOException;
020    import java.net.ServerSocket;
021    import java.util.concurrent.atomic.AtomicLong;
022    
023    import org.slf4j.Logger;
024    import org.slf4j.LoggerFactory;
025    
026    /**
027     * Generator for Globally unique Strings.
028     */
029    
030    public class IdGenerator {
031    
032        private static final Logger LOG = LoggerFactory.getLogger(IdGenerator.class);
033        private static final String UNIQUE_STUB;
034        private static int instanceCount;
035        private static String hostName;
036        private String seed;
037        private AtomicLong sequence = new AtomicLong(1);
038        private int length;
039        public static final String PROPERTY_IDGENERATOR_PORT ="activemq.idgenerator.port";
040    
041        static {
042            String stub = "";
043            boolean canAccessSystemProps = true;
044            try {
045                SecurityManager sm = System.getSecurityManager();
046                if (sm != null) {
047                    sm.checkPropertiesAccess();
048                }
049            } catch (SecurityException se) {
050                canAccessSystemProps = false;
051            }
052    
053            if (canAccessSystemProps) {
054                int idGeneratorPort = 0;
055                ServerSocket ss = null;
056                try {
057                    idGeneratorPort = Integer.parseInt(System.getProperty(PROPERTY_IDGENERATOR_PORT, "0"));
058                    LOG.trace("Using port {}", idGeneratorPort);
059                    hostName = InetAddressUtil.getLocalHostName();
060                    ss = new ServerSocket(idGeneratorPort);
061                    stub = "-" + ss.getLocalPort() + "-" + System.currentTimeMillis() + "-";
062                    Thread.sleep(100);
063                } catch (Exception ioe) {
064                    if (LOG.isTraceEnabled()) {
065                        LOG.trace("could not generate unique stub by using DNS and binding to local port", ioe);
066                    } else {
067                        LOG.warn("could not generate unique stub by using DNS and binding to local port: {} {}", ioe.getClass().getCanonicalName(), ioe.getMessage());
068                    }
069                } finally {
070                    if (ss != null) {
071                        try {
072                            // TODO: replace the following line with IOHelper.close(ss) when Java 6 support is dropped
073                            ss.close();
074                        } catch (IOException ioe) {
075                            if (LOG.isTraceEnabled()) {
076                                LOG.trace("Closing the server socket failed", ioe);
077                            } else {
078                                LOG.warn("Closing the server socket failed" + " due " + ioe.getMessage());
079                            }
080                        }
081                    }
082                }
083            }
084            // fallback
085            if (hostName == null) {
086                hostName = "localhost";
087            }
088            if (stub.length() == 0) {
089                stub = "-1-" + System.currentTimeMillis() + "-";
090            }
091            UNIQUE_STUB = stub;
092        }
093    
094        /**
095         * Construct an IdGenerator
096         */
097        public IdGenerator(String prefix) {
098            synchronized (UNIQUE_STUB) {
099                this.seed = prefix + UNIQUE_STUB + (instanceCount++) + ":";
100                this.length = this.seed.length() + ("" + Long.MAX_VALUE).length();
101            }
102        }
103    
104        public IdGenerator() {
105            this("ID:" + hostName);
106        }
107    
108        /**
109         * As we have to find the hostname as a side-affect of generating a unique
110         * stub, we allow it's easy retrevial here
111         *
112         * @return the local host name
113         */
114    
115        public static String getHostName() {
116            return hostName;
117        }
118    
119    
120        /**
121         * Generate a unqiue id
122         *
123         * @return a unique id
124         */
125    
126        public synchronized String generateId() {
127            StringBuilder sb = new StringBuilder(length);
128            sb.append(seed);
129            sb.append(sequence.getAndIncrement());
130            return sb.toString();
131        }
132    
133        /**
134         * Generate a unique ID - that is friendly for a URL or file system
135         *
136         * @return a unique id
137         */
138        public String generateSanitizedId() {
139            String result = generateId();
140            result = result.replace(':', '-');
141            result = result.replace('_', '-');
142            result = result.replace('.', '-');
143            return result;
144        }
145    
146        /**
147         * From a generated id - return the seed (i.e. minus the count)
148         *
149         * @param id the generated identifer
150         * @return the seed
151         */
152        public static String getSeedFromId(String id) {
153            String result = id;
154            if (id != null) {
155                int index = id.lastIndexOf(':');
156                if (index > 0 && (index + 1) < id.length()) {
157                    result = id.substring(0, index);
158                }
159            }
160            return result;
161        }
162    
163        /**
164         * From a generated id - return the generator count
165         *
166         * @param id
167         * @return the count
168         */
169        public static long getSequenceFromId(String id) {
170            long result = -1;
171            if (id != null) {
172                int index = id.lastIndexOf(':');
173    
174                if (index > 0 && (index + 1) < id.length()) {
175                    String numStr = id.substring(index + 1, id.length());
176                    result = Long.parseLong(numStr);
177                }
178            }
179            return result;
180        }
181    
182        /**
183         * Does a proper compare on the ids
184         *
185         * @param id1
186         * @param id2
187         * @return 0 if equal else a positive if id1 is > id2 ...
188         */
189    
190        public static int compare(String id1, String id2) {
191            int result = -1;
192            String seed1 = IdGenerator.getSeedFromId(id1);
193            String seed2 = IdGenerator.getSeedFromId(id2);
194            if (seed1 != null && seed2 != null) {
195                result = seed1.compareTo(seed2);
196                if (result == 0) {
197                    long count1 = IdGenerator.getSequenceFromId(id1);
198                    long count2 = IdGenerator.getSequenceFromId(id2);
199                    result = (int)(count1 - count2);
200                }
201            }
202            return result;
203    
204        }
205    
206    }