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 */
017package org.apache.camel.impl;
018
019import java.net.ServerSocket;
020import java.util.concurrent.atomic.AtomicLong;
021
022import org.apache.camel.spi.UuidGenerator;
023import org.apache.camel.util.IOHelper;
024import org.apache.camel.util.InetAddressUtil;
025import org.apache.camel.util.ObjectHelper;
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029/**
030 * {@link org.apache.camel.spi.UuidGenerator} which is a fast implementation based on
031 * how <a href="http://activemq.apache.org/">Apache ActiveMQ</a> generates its UUID.
032 * <p/>
033 * This implementation is not synchronized but it leverages API which may not be accessible
034 * in the cloud (such as Google App Engine).
035 * <p/>
036 * The JVM system property {@link #PROPERTY_IDGENERATOR_PORT} can be used to set a specific port
037 * number to be used as part of the initialization process to generate unique UUID.
038 */
039public class ActiveMQUuidGenerator implements UuidGenerator {
040
041    // use same JVM property name as ActiveMQ
042    public static final String PROPERTY_IDGENERATOR_HOSTNAME = "activemq.idgenerator.hostname";
043    public static final String PROPERTY_IDGENERATOR_LOCALPORT = "activemq.idgenerator.localport";
044    public static final String PROPERTY_IDGENERATOR_PORT = "activemq.idgenerator.port";
045
046    private static final Logger LOG = LoggerFactory.getLogger(ActiveMQUuidGenerator.class);
047    private static final String UNIQUE_STUB;
048    private static int instanceCount;
049    private static String hostName;
050    private String seed;
051    private final AtomicLong sequence = new AtomicLong(1);
052    private final int length;
053
054    static {
055        String stub = "";
056        boolean canAccessSystemProps = true;
057        try {
058            SecurityManager sm = System.getSecurityManager();
059            if (sm != null) {
060                sm.checkPropertiesAccess();
061            }
062        } catch (SecurityException se) {
063            canAccessSystemProps = false;
064        }
065
066        if (canAccessSystemProps) {
067            hostName = System.getProperty(PROPERTY_IDGENERATOR_HOSTNAME);
068            int localPort = Integer.parseInt(System.getProperty(PROPERTY_IDGENERATOR_LOCALPORT, "0"));
069
070            int idGeneratorPort = 0;
071            ServerSocket ss = null;
072            try {
073                if (hostName == null) {
074                    hostName = InetAddressUtil.getLocalHostName();
075                }
076                if (localPort == 0) {
077                    idGeneratorPort = Integer.parseInt(System.getProperty(PROPERTY_IDGENERATOR_PORT, "0"));
078                    LOG.trace("Using port {}", idGeneratorPort);
079                    ss = new ServerSocket(idGeneratorPort);
080                    localPort = ss.getLocalPort();
081                    stub = "-" + localPort + "-" + System.currentTimeMillis() + "-";
082                    Thread.sleep(100);
083                } else {
084                    stub = "-" + localPort + "-" + System.currentTimeMillis() + "-";
085                }
086            } catch (Exception e) {
087                if (LOG.isTraceEnabled()) {
088                    LOG.trace("Cannot generate unique stub by using DNS and binding to local port: " + idGeneratorPort, e);
089                } else {
090                    LOG.warn("Cannot generate unique stub by using DNS and binding to local port: " + idGeneratorPort + " due " + e.getMessage());
091                }
092                // Restore interrupted state so higher level code can deal with it.
093                if (e instanceof InterruptedException) {
094                    Thread.currentThread().interrupt();
095                }
096            } finally {
097                IOHelper.close(ss);
098            }
099        }
100
101        // fallback to use localhost
102        if (hostName == null) {
103            hostName = "localhost";
104        }
105        hostName = sanitizeHostName(hostName);
106
107        if (ObjectHelper.isEmpty(stub)) {
108            stub = "-1-" + System.currentTimeMillis() + "-";
109        }
110        UNIQUE_STUB = stub;
111    }
112
113    public ActiveMQUuidGenerator(String prefix) {
114        synchronized (UNIQUE_STUB) {
115            this.seed = prefix + UNIQUE_STUB + (instanceCount++) + "-";
116            // let the ID be friendly for URL and file systems
117            this.seed = generateSanitizedId(this.seed);
118            this.length = seed.length() + ("" + Long.MAX_VALUE).length();
119        }
120    }
121
122    public ActiveMQUuidGenerator() {
123        this("ID-" + hostName);
124    }
125
126    /**
127     * As we have to find the hostname as a side-affect of generating a unique
128     * stub, we allow it's easy retrieval here
129     * 
130     * @return the local host name
131     */
132    public static String getHostName() {
133        return hostName;
134    }
135
136    public static String sanitizeHostName(String hostName) {
137        boolean changed = false;
138
139        StringBuilder sb = new StringBuilder();
140        for (char ch : hostName.toCharArray()) {
141            // only include ASCII chars
142            if (ch < 127) {
143                sb.append(ch);
144            } else {
145                changed = true;
146            }
147        }
148
149        if (changed) {
150            String newHost = sb.toString();
151            LOG.info("Sanitized hostname from: {} to: {}", hostName, newHost);
152            return newHost;
153        } else {
154            return hostName;
155        }
156    }
157
158    public String generateUuid() {
159        StringBuilder sb = new StringBuilder(length);
160        sb.append(seed);
161        sb.append(sequence.getAndIncrement());
162        return sb.toString();
163    }
164
165    /**
166     * Generate a unique ID - that is friendly for a URL or file system
167     * 
168     * @return a unique id
169     */
170    public String generateSanitizedId() {
171        return generateSanitizedId(generateUuid());
172    }
173
174    /**
175     * Ensures that the id is friendly for a URL or file system
176     *
177     * @param id the unique id
178     * @return the id as file friendly id
179     */
180    public static String generateSanitizedId(String id) {
181        id = id.replace(':', '-');
182        id = id.replace('_', '-');
183        id = id.replace('.', '-');
184        id = id.replace('/', '-');
185        return id;
186    }
187}