Java UUID Create generateRandomUUID()

Here you can find the source of generateRandomUUID()

Description

generate Random UUID

License

Apache License

Declaration

public static String generateRandomUUID() 

Method Source Code

//package com.java2s;
/*// ww w.  jav  a  2 s .co  m
 * Copyright 2007-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    private final static String __chars64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789^~abcdefghijklmnopqrstuvwxyz";

    public static String generateRandomUUID() {
        long id1 = System.currentTimeMillis() & 0x3FFFFFFFL;
        long id3 = randomLong(-0x80000000L, 0x80000000L) & 0x3FFFFFFFL;
        return __convert(id1, 6, __chars64) + __convert(id3, 6, __chars64).replaceAll(" ", "o");
    }

    /**
     * Generates pseudo-random long from specific range. Generated number is
     * great or equals to min parameter value and less then max parameter value.
     *
     * @param min lower (inclusive) boundary
     * @param max higher (exclusive) boundary
     * @return pseudo-random value
     */
    public static long randomLong(long min, long max) {
        return min + (long) (Math.random() * (max - min));
    }

    /**
     * Converts number to string
     *
     * @param x value to convert
     * @param n conversion base
     * @param d string with characters for conversion.
     * @return converted number as string
     */
    private static String __convert(long x, int n, String d) {
        if (x == 0) {
            return "0";
        }
        String r = "";
        int m = 1 << n;
        m--;
        while (x != 0) {
            r = d.charAt((int) (x & m)) + r;
            x = x >>> n;
        }
        return r;
    }
}

Related

  1. generateRandomMap(int count)
  2. generateRandomName()
  3. GenerateRandomSlug()
  4. generateRandomString(int length)
  5. generateRandomTableName()
  6. generateRandomUUID(final int length)
  7. generateRawUUID()
  8. generateRequestId()
  9. generateRequestId()