java get uuid_java获取UUID与UUID的校验

Java获取与校验UUID的方法
在开发中,有时需随机生成ID并进行校验。UUID可让分布式系统不借助中心节点生成唯一标识。本文给出Java代码,包含获取随机UUID和校验UUID的方法,还展示了测试结果,能帮助开发者实现相关功能。
部署运行你感兴趣的模型镜像

原标题:java获取UUID与UUID的校验

背景:

我们在开发的过程中可能需要随机生成一个ID,例如数据库中的某个ID

有时候也要对其进行校验。

UUID:

UUID,是Universally Unique Identifier的缩写,UUID出现的目的,是为了让分布式系统可以不借助中心节点,就可以生成UUID来标识一些唯一的信息。

代码:

import java.util.UUID;

public class UUIDTest {

public static void main(String[] args) {

String uuid1 = "e65deb4c-a110-49c8-a4ef-6e69447968d6";

String uuid2 = "ca4a8a92-d4ed-4fc4-8a4f-345c587fbdcb";

String uuid3 = "e1f15f1d-6edb-4f70-8a05465se273eaf95a";

System.out.println("check > " + uuid1 + " > " + isValidUUID(uuid1));

System.out.println("check > " + uuid2 + " > " + isValidUUID(uuid2));

System.out.println("check > " + uuid3 + " > " + isValidUUID(uuid3));

System.out.println("build a uuid> " + getRandomUUID(null));

System.out.println("build a uuid> " + getRandomUUID(null));

System.out.println("build a uuid> " + getRandomUUID("kangyucheng"));

System.out.println("build a uuid> " + getRandomUUID("kangyucheng"));

}

public static boolean isValidUUID(String uuid) {

// UUID校验

if (uuid == null) {

System.out.println("uuid is null");

}

String regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";

if (uuid.matches(regex)) {

return true;

}

return false;

}

public static UUID getRandomUUID(String str) {

// 产生UUID

if (str == null) {

return UUID.randomUUID();

} else {

return UUID.nameUUIDFromBytes(str.getBytes());

}

}

}

测试结果:

check > e65deb4c-a110-49c8-a4ef-6e69447968d6 > true

check > ca4a8a92-d4ed-4fc4-8a4f-345c587fbdcb > true

check > e1f15f1d-6edb-4f70-8a05465se273eaf95a > false

build a uuid>93ce6775-bc89-4849-8ae9-fb305c909700

build a uuid>7a61f2e0-903b-4904-b2bd-a075b19adb8c

build a uuid>8b68aa00-6a79-3cbb-996f-780f464f3aae

build a uuid>8b68aa00-6a79-3cbb-996f-780f464f3aae

---------------------

作者:kangyucheng

原文:https://blog.youkuaiyun.com/Kangyucheng/article/details/86498341

版权声明:本文为博主原创文章,转载请附上博文链接!

责任编辑:

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

package android.os; /** * @hide Only for use within the system server */ interface IUuidService { String getOrCreatePersistentUuid(); } package com.android.server.os; import android.content.Context; import android.os.IUuidService; import android.os.UuidManager; import android.util.Slog; import com.android.internal.os.UuidPersistStorage; public class UuidService extends IUuidService.Stub { private static final String TAG = "UuidService"; private final Context mContext; public UuidService(Context context) { mContext = context; Slog.i(TAG, "UuidService started"); } @Override public String getOrCreatePersistentUuid() { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.READ_DEVICE_UUID, null); return UuidPersistStorage.getOrCreatePersistentUuid(); } } // frameworks/base/core/java/android/os/UuidManager.java package android.os; import android.annotation.NonNull; import android.annotation.SystemApi; import android.os.IBinder; import android.os.Parcel; import android.os.RemoteException; import android.os.ServiceManager; import android.util.Log; /** * Provides access to a persistent unique identifier for the device. * * @hide This class may be promoted to @SystemApi in future. */ @SystemApi public class UuidManager { private static final String TAG = "UuidManager"; private static final String SERVICE_NAME = "uuid"; // 必须 IUuidService.aidl 中的方法顺序一致 private static final int TRANSACTION_getOrCreatePersistentUuid = IBinder.FIRST_CALL_TRANSACTION + 0; private final IBinder mBinder; /** * Private constructor to prevent direct instantiation. * Use getSystemService(UuidManager.class) instead. */ /* package */ UuidManager() { mBinder = ServiceManager.getService(SERVICE_NAME); if (mBinder == null) { Log.e(TAG, "Failed to get UUID service from ServiceManager"); } } /** * Factory method for creating UuidManager instances. * Used by SystemServiceRegistry. * * @hide */ @SystemApi(client = SystemApi.Client.SYSTEM_SERVER) public static UuidManager create() { return new UuidManager(); } /** * Gets or creates a persistent UUID for this device. * * @return the UUID string, never null * @throws IllegalStateException if service is unavailable */ @NonNull public String getOrCreatePersistentUuid() { if (mBinder == null) { throw new IllegalStateException("UUID service not available"); } Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); try { // 必须写入接口标识符(由 AIDL 自动生成) data.writeInterfaceToken("android.os.IUuidService"); // 发起调用(transaction code 由 AIDL 分配) mBinder.transact(TRANSACTION_getOrCreatePersistentUuid, data, reply, 0); // 检查异常 reply.readException(); // 读取返回值 String uuid = reply.readString(); return uuid != null ? uuid : "unknown"; } catch (RemoteException e) { Log.e(TAG, "Remote exception while getting UUID", e); throw e.rethrowFromSystemServer(); } finally { data.recycle(); reply.recycle(); } } } package com.android.internal.os; import android.util.Slog; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; /** * 持久化存储设备唯一 UUID * 路径: /mnt/vendor/persist/device_uuid * 首次开机写入随机 UUID,之后读取已有值 */ public class UuidPersistStorage { private static final String TAG = "UuidPersistStorage"; private static final String UUID_FILE_PATH = "/mnt/vendor/persist/uuid"; private static final String UUID_FILE = "/mnt/vendor/persist/uuid/device_uuid"; private static String sCachedUuid; // 缓存避免重复 IO /** * 获取或创建持久化的设备 UUID * * @return 设备 UUID 字符串 */ public static synchronized String getOrCreatePersistentUuid() { if (sCachedUuid != null) { return sCachedUuid; } File uuidFile = new File(UUID_FILE); // Step 1: 尝试从文件读取已存在的 UUID String existingUuid = readUuidFromFile(uuidFile); if (existingUuid != null && isValidUuid(existingUuid)) { sCachedUuid = existingUuid; Slog.i(TAG, "Loaded existing persistent UUID"); return sCachedUuid; } // Step 2: 生成新 UUID 并写入文件 String newUuid = UUID.randomUUID().toString(); if (writeUuidToFile(uuidFile, newUuid)) { sCachedUuid = newUuid; Slog.i(TAG, "Generated and saved new persistent UUID"); } else { Slog.e(TAG, "Failed to write UUID to persistent storage, using fallback"); // 生产环境中不应返回临时值,但可降级处理(例如抛异常或上报错误) sCachedUuid = "error-generated-" + System.currentTimeMillis(); } return sCachedUuid; } /** * 从文件读取 UUID 内容 */ private static String readUuidFromFile(File file) { if (!file.exists()) { Slog.w(TAG, "UUID file does not exist: " + file.getAbsolutePath()); return null; } try (FileInputStream fis = new FileInputStream(file)) { byte[] buffer = new byte[64]; int len = fis.read(buffer); if (len <= 0) return null; return new String(buffer, 0, len).trim(); } catch (IOException e) { Slog.e(TAG, "Failed to read UUID from file: " + file.getAbsolutePath(), e); return null; } } /** * 写入 UUID 到文件 */ private static boolean writeUuidToFile(File file, String uuid) { try (FileOutputStream fos = new FileOutputStream(file, false)) { fos.write(uuid.getBytes()); fos.flush(); // 强制同步到磁盘,保证写入成功 fos.getFD().sync(); Slog.d(TAG, "Successfully wrote UUID to " + file.getAbsolutePath()); return true; } catch (IOException e) { Slog.e(TAG, "Failed to write UUID to file: " + file.getAbsolutePath(), e); return false; } } /** * 校验字符串是否为合法 UUID 格式(简化版) */ private static boolean isValidUuid(String str) { if (str == null || str.length() < 36) return false; try { UUID.fromString(str.trim()); return true; } catch (IllegalArgumentException e) { return false; } } /** * 清除缓存(用于测试或重启时重新加载) */ public static void clearCache() { sCachedUuid = null; } } try { Slog.i(TAG, "Starting UUID Service"); UuidService uuidService = new UuidService(mSystemContext); ServiceManager.addService(Context.UUID_SERVICE, uuidService); } catch (Throwable e) { reportWtf("starting UUID Service", e); } <!-- caiwenlu add --> <permission android:name="android.permission.READ_DEVICE_UUID" android:protectionLevel="signature|privileged" android:label="@string/permlab_readDeviceUuid" android:description="@string/permdesc_readDeviceUuid" /> <!-- caiwenlu add end --> //caiwenlu add /** * Use with {@link #getSystemService(Class)} to retrieve a {@link UuidManager}. */ public static final String UUID_SERVICE = "uuid"; //caiwenlu add end UuidManager uuidManager = getSystemService(UuidManager.class); if (uuidManager != null) { String uuid = uuidManager.getOrCreatePersistentUuid(); Log.d("UUID", "Device UUID: " + uuid); } else { Log.e("UUID", "UuidManager is null - check if service started"); } SystemServer.java try { Slog.i(TAG, "Starting UUID Service"); UuidService uuidService = new UuidService(mSystemContext); ServiceManager.addService(Context.UUID_SERVICE, uuidService); } catch (Throwable e) { reportWtf("starting UUID Service", e); } SystemServiceRegistry.java registerService(Context.UUID_SERVICE, UuidManager.class, new CachedServiceFetcher<UuidManager>() { @Override public UuidManager createService(ContextImpl ctx) { return UuidManager.create(); //通过公共静态方法创建 } }); WatchHomeActivity.java UuidManager uuidManager = getSystemService(UuidManager.class); if (uuidManager != null) { String uuid = uuidManager.getOrCreatePersistentUuid(); Log.d("UUID", "Device UUID: " + uuid); } else { Log.e("UUID", "UuidManager is null - check if service started"); } file.te type device_uuid_dir, file_type, data_file_type, core_data_file_type; type device_uuid_file, file_type, data_file_type, core_data_file_type; file_contexts ############################# /mnt/vendor/persist/uuid/device_uuid u:object_r:device_uuid_file:s0 /mnt/vendor/persist/uuid(/.*)? u:object_r:device_uuid_dir:s0 system_server.te allow system_server device_uuid_dir:dir { search add_name # 如果需要创建文件 remove_name # 如果需要删除文件 read # 列出目录内容 }; allow system_server device_uuid_file:file { read write open ioctl getattr }; init.qcom.rc # 创建 persist uuid 目录并初始化 device_uuid 文件(如果不存在) on post-fs-data # 创建目录(mkdir 若存在不会报错) mkdir /mnt/vendor/persist/uuid 0770 system system # 设置权限,确保后续操作可以进行 chown system system /mnt/vendor/persist/uuid chmod 0770 /mnt/vendor/persist/uuid # 使用 write 操作写入默认 UUID(仅当文件不存在时) # 注意:write 不会覆盖已有文件,这是安全的 write /mnt/vendor/persist/uuid/device_uuid "00000000-0000-0000-0000-000000000000" # 确保文件可被系统服务读写 on property:ro.product.first_boot=1 chown system system /mnt/vendor/persist/uuid/device_uuid chmod 0660 /mnt/vendor/persist/uuid/device_uuid
最新发布
11-26
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值