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