| 1 | |
package com.ctrip.framework.apollo.biz.utils; |
| 2 | |
|
| 3 | |
import com.google.common.base.Joiner; |
| 4 | |
|
| 5 | |
import com.ctrip.framework.apollo.biz.entity.Namespace; |
| 6 | |
import com.ctrip.framework.apollo.core.utils.ByteUtil; |
| 7 | |
import com.ctrip.framework.apollo.core.utils.MachineUtil; |
| 8 | |
|
| 9 | |
import java.security.SecureRandom; |
| 10 | |
import java.text.DateFormat; |
| 11 | |
import java.text.SimpleDateFormat; |
| 12 | |
import java.util.Date; |
| 13 | |
import java.util.Objects; |
| 14 | |
import java.util.concurrent.atomic.AtomicInteger; |
| 15 | |
|
| 16 | |
|
| 17 | |
|
| 18 | |
|
| 19 | 0 | public class ReleaseKeyGenerator { |
| 20 | 1 | private static final DateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); |
| 21 | 1 | private static final AtomicInteger releaseCounter = new AtomicInteger(new SecureRandom().nextInt()); |
| 22 | 1 | private static final Joiner KEY_JOINER = Joiner.on("-"); |
| 23 | |
|
| 24 | |
|
| 25 | |
|
| 26 | |
|
| 27 | |
|
| 28 | |
|
| 29 | |
|
| 30 | |
public static String generateReleaseKey(Namespace namespace) { |
| 31 | 99975 | String hexIdString = |
| 32 | 99842 | ByteUtil.toHexString( |
| 33 | 299827 | toByteArray(Objects.hash(namespace.getAppId(), namespace.getClusterName(), |
| 34 | 199736 | namespace.getNamespaceName()), MachineUtil.getMachineIdentifier(), |
| 35 | 99833 | releaseCounter.incrementAndGet())); |
| 36 | |
|
| 37 | 99971 | return KEY_JOINER.join(TIMESTAMP_FORMAT.format(new Date()), hexIdString); |
| 38 | |
} |
| 39 | |
|
| 40 | |
|
| 41 | |
|
| 42 | |
|
| 43 | |
|
| 44 | |
private static byte[] toByteArray(int keyHashCode, int machineIdentifier, int counter) { |
| 45 | 99949 | byte[] bytes = new byte[8]; |
| 46 | 99931 | bytes[0] = ByteUtil.int1(keyHashCode); |
| 47 | 99928 | bytes[1] = ByteUtil.int0(keyHashCode); |
| 48 | 99926 | bytes[2] = ByteUtil.int2(machineIdentifier); |
| 49 | 99937 | bytes[3] = ByteUtil.int1(machineIdentifier); |
| 50 | 99936 | bytes[4] = ByteUtil.int0(machineIdentifier); |
| 51 | 99929 | bytes[5] = ByteUtil.int2(counter); |
| 52 | 99855 | bytes[6] = ByteUtil.int1(counter); |
| 53 | 99834 | bytes[7] = ByteUtil.int0(counter); |
| 54 | 99840 | return bytes; |
| 55 | |
} |
| 56 | |
} |