下面列出了怎么用java.util.UUID的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Gets all the mappings that exist for the given shard.
*
* @param shard
* Shard for which the mappings will be returned.
* @param lookupOptions
* Whether to search in the cache and/or store.
* @return Read-only collection of mappings that satisfy the given shard constraint.
*/
public List<PointMapping> getMappings(Shard shard,
LookupOptions lookupOptions) {
ExceptionUtils.disallowNullArgument(shard, "shard");
try (ActivityIdScope activityIdScope = new ActivityIdScope(UUID.randomUUID())) {
log.info("GetPointMappings", "Start; Shard:{}; Lookup Options: {}", shard.getLocation(), lookupOptions);
Stopwatch stopwatch = Stopwatch.createStarted();
List<PointMapping> pointMappings = lsm.getMappingsForRange(null, shard, lookupOptions);
stopwatch.stop();
log.info("GetPointMappings", "Complete; Shard: {}; Lookup Options: {}; Duration:{}", shard.getLocation(), lookupOptions,
stopwatch.elapsed(TimeUnit.MILLISECONDS));
return pointMappings;
}
}
/**
* Close communication clients. It will lead that sendMessage method will be trying to create new ones.
*/
private void closeTcpConnections() {
final ConcurrentMap<UUID, GridCommunicationClient[]> clients = U.field(this, "clients");
Set<UUID> ids = clients.keySet();
if (!ids.isEmpty()) {
log.info("Close TCP clients: " + ids);
for (UUID nodeId : ids) {
GridCommunicationClient[] clients0 = clients.remove(nodeId);
if (clients0 != null) {
for (GridCommunicationClient client : clients0) {
if (client != null)
client.forceClose();
}
}
}
log.info("TCP clients are closed.");
}
}
private ClientAuthorizationRequestProvider getClientAuthorizationRequestProvider() throws Exception {
String prefix = UUID.randomUUID().toString();
File file = File.createTempFile(prefix, null);
file.deleteOnExit();
byte[] bytes = ("here.token.endpoint.url="+url+"\n"
+ "here.client.id="+clientId+"\n"
+ "here.access.key.id="+accessKeyId+"\n"
+ "here.access.key.secret="+accessKeySecret+"\n"
+ "here.token.scope="+TEST_PROJECT)
.getBytes(StandardCharsets.UTF_8);
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(bytes);
outputStream.flush();
}
return new FromDefaultHereCredentialsPropertiesFile(file);
}
/**
* Start the FTP server, create & clean home directory
*/
@Before
public void initialize() throws FtpException, IOException {
File tempDir = new File(System.getProperty("java.io.tmpdir"));
ftpRoot = new File(tempDir,
"ftp");
if (ftpRoot.exists()) {
FileUtils.deleteDirectory(ftpRoot);
}
boolean created = ftpRoot.mkdir();
if (!created) {
throw new IllegalArgumentException("FTP root directory has not been created, " + "check system property java.io.tmpdir");
}
String fileName = "test_file_" + CamelFtpTest.class.getName() + "_" + UUID.randomUUID().toString();
File testDir = new File(ftpRoot,
"testDirectory");
testFile = new File(testDir,
fileName);
server = configureFtpServer(new FtpServerBuilder());
server.start();
}
@DataProvider(value = {
"NULL",
"EMPTY",
"NOT_EMPTY"
}, splitBy = "\\|")
@Test
public void constructor_with_Error_object_arg_should_pull_values_from_Error_object(MetadataArgOption metadataArgOption) {
// given
DefaultErrorDTO copyError = new DefaultErrorDTO(UUID.randomUUID().toString(), UUID.randomUUID().toString(), generateMetadata(metadataArgOption));
// when
DefaultErrorDTO error = new DefaultErrorDTO(copyError);
// then
assertThat(error.code).isEqualTo(copyError.code);
assertThat(error.message).isEqualTo(copyError.message);
verifyMetadata(error, metadataArgOption, copyError.metadata);
}
/**
* @param nodeId Node ID.
* @param checkReq Request.
*/
private void processCheckUpdateRequest(UUID nodeId, GridNearAtomicCheckUpdateRequest checkReq) {
/*
* Message is processed in the same stripe, so primary already processed update request. It is possible
* response was not sent if operation result was empty. Near node will get original response or this one.
*/
GridNearAtomicUpdateResponse res = new GridNearAtomicUpdateResponse(ctx.cacheId(),
nodeId,
checkReq.futureId(),
checkReq.partition(),
false,
false);
GridCacheReturn ret = new GridCacheReturn(false, true);
res.returnValue(ret);
sendNearUpdateReply(nodeId, res);
}
/**
* 替换sql中的变量
* @param sql
* @return
*/
public String replaceVal(String sql,TSSmsEntity t){
sql = sql.replace("#{id}",String.valueOf(t.getId()));
sql = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
sql = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
sql = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
sql = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
sql = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
sql = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
sql = sql.replace("#{es_title}",String.valueOf(t.getEsTitle()));
sql = sql.replace("#{es_type}",String.valueOf(t.getEsType()));
sql = sql.replace("#{es_sender}",String.valueOf(t.getEsSender()));
sql = sql.replace("#{es_receiver}",String.valueOf(t.getEsReceiver()));
sql = sql.replace("#{es_content}",String.valueOf(t.getEsContent()));
sql = sql.replace("#{es_sendtime}",String.valueOf(t.getEsSendtime()));
sql = sql.replace("#{es_status}",String.valueOf(t.getEsStatus()));
sql = sql.replace("#{UUID}",UUID.randomUUID().toString());
return sql;
}
@Test
public void testBucketUUIDInclusive() {
UUID value = new UUID(123L, 456L);
Schema schema = new Schema(optional(1, "value", Types.UUIDType.get()));
PartitionSpec spec = PartitionSpec.builderFor(schema).bucket("value", 10).build();
// the bucket number of the value (i.e. UUID(123L, 456L)) is 4
assertProjectionInclusive(spec, equal("value", value), Expression.Operation.EQ, "4");
assertProjectionInclusiveValue(spec, notEqual("value", value), Expression.Operation.TRUE);
assertProjectionInclusiveValue(spec, lessThan("value", value), Expression.Operation.TRUE);
assertProjectionInclusiveValue(spec, lessThanOrEqual("value", value), Expression.Operation.TRUE);
assertProjectionInclusiveValue(spec, greaterThan("value", value), Expression.Operation.TRUE);
assertProjectionInclusiveValue(spec, greaterThanOrEqual("value", value), Expression.Operation.TRUE);
UUID anotherValue = new UUID(456L, 123L);
assertProjectionInclusive(spec, in("value", value, anotherValue),
Expression.Operation.IN, "[4, 6]");
assertProjectionInclusiveValue(spec, notIn("value", value, anotherValue), Expression.Operation.TRUE);
}
@Test
public void testEqualsMax() throws Exception {
agg.reset();
List<String> savedUUIDs = new ArrayList<>();
Collection<Value> values = Lists.newArrayList();
for (int i = 0; i < GlobalIndexUidAggregator.MAX; i++) {
Builder b = createNewUidList();
b.setIGNORE(false);
String uuid = UUID.randomUUID().toString();
savedUUIDs.add(uuid);
b.setCOUNT(1);
b.addUID(uuid);
Uid.List uidList = b.build();
Value val = new Value(uidList.toByteArray());
values.add(val);
}
Value result = agg.reduce(new Key("key"), values.iterator());
Uid.List resultList = Uid.List.parseFrom(result.get());
assertNotNull(resultList);
assertEquals(false, resultList.getIGNORE());
assertEquals(resultList.getUIDCount(), (GlobalIndexUidAggregator.MAX));
List<String> resultListUUIDs = resultList.getUIDList();
for (String s : savedUUIDs)
assertTrue(resultListUUIDs.contains(s));
}
@Test
public void shouldBeInvalidatedToken()
{
ServiceResponse<String> response = _tokenService.generateToken(
TokenService.Purpose.RESET_PASSWORD, _user, Duration.ofDays(1L));
Assert.assertTrue(_tokenService.invalidateToken(response.getResult()).isOk());
Assert.assertTrue(_tokenService.invalidateToken(null).getStatus() == ServiceResponse.Status.ERROR);
Assert.assertTrue(_tokenService.invalidateToken(
UUID.randomUUID().toString()).getStatus() == ServiceResponse.Status.ERROR);
response = _tokenService.generateToken(
TokenService.Purpose.RESET_PASSWORD, _user, Duration.ofDays(1L));
_tokenService.invalidateToken(response.getResult());
Assert.assertTrue(_tokenService.invalidateToken(response.getResult()).getStatus() == ServiceResponse.Status.ERROR);
}
public void execute(ExecutionContext context, boolean autoRollback) throws CommandExecutionException {
Session session = context.getSession();
PreparedStatement update = session.prepare(UPDATE_STATES);
BoundStatement select = session.prepare(SELECT).bind();
select.setConsistencyLevel(ConsistencyLevel.ALL);
ResultSet rs = context.getSession().execute(select);
for(Row row: rs) {
String protocolAddress = row.getString("protocoladdress");
UUID placeId = row.getUUID("placeid");
BoundStatement bs = new BoundStatement(update);
bs.setString("connState", "ONLINE");
bs.setString("registrationState", placeId == null ? "UNREGISTERED" : "REGISTERED");
bs.setString("protocolAddress", protocolAddress);
session.execute(bs);
}
}
static public byte[] encryptAESWithAnyKey(byte[] data, String encKey) {
if (encKey != null) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
UUID uuid = UUID.fromString(encKey);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
try {
return CryptoUtils.encryptAES(data, bb.array());
} catch (Exception ignored) {
}
}
return data;
}
@Nullable
@Override
public PlaceEnvironmentExecutor load(UUID placeId) {
RuleEnvironment environment = ruleEnvDao.findByPlace(placeId);
if(environment == null) {
return null;
}
if(environment.getRules() == null || environment.getRules().isEmpty()) {
return new InactivePlaceExecutor(() -> this.doLoad(placeId), placeId);
}
else {
return this.doLoad(placeId);
}
}
private void createExpressionObserverJob(
JobKey jobKey, UUID triggerKey, String configExpression, String cronExpression) throws SchedulerException
{
if (!ClassDeactivationUtils.isActivated(DynamicExpressionObserverJob.class))
{
return;
}
JobKey observerJobKey =
new JobKey(jobKey.getName() + DynamicExpressionObserverJob.OBSERVER_POSTFIX, jobKey.getGroup());
JobDetail jobDetail = JobBuilder.newJob(DynamicExpressionObserverJob.class)
.usingJobData(DynamicExpressionObserverJob.CONFIG_EXPRESSION_KEY, configExpression)
.usingJobData(DynamicExpressionObserverJob.TRIGGER_ID_KEY, triggerKey.toString())
.usingJobData(DynamicExpressionObserverJob.ACTIVE_CRON_EXPRESSION_KEY, cronExpression)
.withDescription("Config observer for: " + jobKey)
.withIdentity(observerJobKey)
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.forJob(observerJobKey)
.withSchedule(CronScheduleBuilder.cronSchedule(
SchedulerBaseConfig.JobCustomization.DYNAMIC_EXPRESSION_OBSERVER_INTERVAL))
.build();
this.scheduler.scheduleJob(jobDetail, trigger);
}
@Test
public void testCreatedNestedObjects() throws Exception
{
_store.init(_parent);
_store.openConfigurationStore(mock(ConfiguredObjectRecordHandler.class));
createRootRecord();
final UUID queueId = new UUID(0, 1);
final UUID queue2Id = new UUID(1, 1);
final UUID exchangeId = new UUID(0, 2);
Map<String, UUID> parents = getRootAsParentMap();
Map<String, Object> queueAttr = Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "queue");
final ConfiguredObjectRecordImpl queueRecord =
new ConfiguredObjectRecordImpl(queueId, "Queue",
queueAttr,
parents);
_store.create(queueRecord);
Map<String, Object> queue2Attr = Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "queue2");
final ConfiguredObjectRecordImpl queue2Record =
new ConfiguredObjectRecordImpl(queue2Id, "Queue",
queue2Attr,
parents);
_store.create(queue2Record);
Map<String, Object> exchangeAttr = Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "exchange");
final ConfiguredObjectRecordImpl exchangeRecord =
new ConfiguredObjectRecordImpl(exchangeId, "Exchange",
exchangeAttr,
parents);
_store.create(exchangeRecord);
_store.closeConfigurationStore();
_store.init(_parent);
_store.openConfigurationStore(_handler);
verify(_handler).handle(matchesRecord(queueId, "Queue", queueAttr));
verify(_handler).handle(matchesRecord(queue2Id, "Queue", queue2Attr));
verify(_handler).handle(matchesRecord(exchangeId, "Exchange", exchangeAttr));
_store.closeConfigurationStore();
}
@Override
public double getRentBalance(UUID uuid) {
final Double balance = this.rentBalances.get(uuid);
if (balance == null) {
return 0;
}
return balance;
}
private static void setTenantSecurityContext(final String tenantId) {
final AnonymousAuthenticationToken authenticationToken = new AnonymousAuthenticationToken(
UUID.randomUUID().toString(), "AMQP-Controller",
Collections.singletonList(new SimpleGrantedAuthority(SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS)));
authenticationToken.setDetails(new TenantAwareAuthenticationDetails(tenantId, true));
setSecurityContext(authenticationToken);
}
/**
* Partition initialization - loads schema entries from the files on classpath.
*
* @see org.apache.directory.server.core.partition.impl.avl.AvlPartition#doInit()
*/
@Override
protected void doInit() throws InvalidNameException, Exception {
if (initialized) {
return;
}
LOG.debug("Initializing schema partition " + getId());
suffixDn.apply(schemaManager);
super.doInit();
// load schema
final Map<String, Boolean> resMap = ResourceMap.getResources(Pattern.compile("schema[/\\Q\\\\E]ou=schema.*"));
for (String resourcePath : new TreeSet<>(resMap.keySet())) {
if (resourcePath.endsWith(".ldif")) {
URL resource = DefaultSchemaLdifExtractor.getUniqueResource(resourcePath, "Schema LDIF file");
LdifEntry ldifEntry;
try (LdifReader reader = new LdifReader(resource.openStream())) {
ldifEntry = reader.next();
}
Entry entry = new DefaultEntry(schemaManager, ldifEntry.getEntry());
// add mandatory attributes
if (entry.get(SchemaConstants.ENTRY_CSN_AT) == null) {
entry.add(SchemaConstants.ENTRY_CSN_AT, defaultCSNFactory.newInstance().toString());
}
if (entry.get(SchemaConstants.ENTRY_UUID_AT) == null) {
entry.add(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString());
}
AddOperationContext addContext = new AddOperationContext(null, entry);
super.add(addContext);
}
}
}
@Test(expected = WebApplicationException.class)
public void testGetEndpointsByServiceXML_NULL() {
System.out.println("getEndpointsByServiceXML_NULL");
String id = UUID.randomUUID().toString();
UriContainer expResult = null;
UriContainer result = instance.getEndpointsByServiceXML(id);
}
@Test
public void getRelationTypesReturnsAllTheRelationTypesInTheDatabase() {
UUID id1 = UUID.randomUUID();
UUID id2 = UUID.randomUUID();
TinkerPopGraphManager graphManager = newGraph()
.withVertex(v -> v
.withTimId(id1)
.withType("relationtype")
.withProperty("rdfUri", "http://example.com/entity1")
.withProperty("rev", 2)
.isLatest(true)
.withLabel("relationtype")
)
.withVertex(v -> v
.withTimId(id2)
.withType("relationstype")
.withVre("test")
.withProperty("rdfUri", "http://example.com/entity1")
.isLatest(false)
.withProperty("rev", 1)
.withLabel("relationtype")
)
.withVertex(v -> v
.withTimId(UUID.randomUUID())
.withType("othertype")
.withVre("test")
.withProperty("rdfUri", "http://example.com/entity1")
.isLatest(false)
.withProperty("rev", 1)
.withLabel("othertype")
)
.wrap();
Vres vres = createConfiguration();
TinkerPopOperations instance = forGraphWrapperAndMappings(graphManager, vres);
List<RelationType> relationTypes = instance.getRelationTypes();
assertThat(relationTypes, hasSize(2));
}
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
if (!ctx.<String>getOne("player").isPresent())
{
src.sendMessage(Text.of(TextColors.YELLOW, "/na forceleave <player>"));
return CommandResult.success();
}
String playerName = ctx.<String>getOne("player").get();
UUID uuid = DataHandler.getPlayerUUID(playerName);
if (uuid == null)
{
src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADPLAYERNAME));
return CommandResult.success();
}
Nation nation = DataHandler.getNationOfPlayer(uuid);
if (nation == null)
{
src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PLAYERNOTINNATION));
return CommandResult.success();
}
if (nation.isPresident(uuid))
{
src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_PLAYERISPRES));
return CommandResult.success();
}
nation.removeCitizen(uuid);
DataHandler.saveNation(nation.getUUID());
Sponge.getServer().getPlayer(uuid).ifPresent(p ->
p.sendMessage(Text.of(TextColors.AQUA, LanguageHandler.SUCCESS_LEAVENATION)));
src.sendMessage(Text.of(TextColors.GREEN, LanguageHandler.SUCCESS_GENERAL));
return CommandResult.success();
}
@Override
public ScheduledFuture<?> schedule(final ActorMessage<?> message, final UUID dest, long initalDelay, long period, TimeUnit unit) {
return schedule(new Supplier<ActorMessage<?>>() {
@Override
public ActorMessage<?> get() {
return message;
}
}, dest, initalDelay, period, unit);
}
public static Cmmn.UUID convert(UUID uuid) {
return Cmmn.UUID
.newBuilder()
.setMsb(uuid.getMostSignificantBits())
.setLsb(uuid.getLeastSignificantBits())
.build();
}
public static String[] uploadFile(MultipartFile file){
log.info("成功获取文件");
//获取文件名
String fileName = file.getOriginalFilename();
String separator = "/";
String[] suffixName = {".jpg",".png",".mp3"};
//判断类型
String type = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf("."), fileName.length()):"";
log.info("文件初始名称为:" + fileName + " 类型为:" + type);
// 2. 使用随机生成的字符串+源图片扩展名组成新的图片名称,防止图片重名
String newfileName = UUID.randomUUID().toString().replaceAll("-","") + fileName.substring(fileName.lastIndexOf("."));
//存放磁盘的路径以及判断有没有
String suffix = "//" + Calendar.getInstance().get(Calendar.YEAR) + "-" + (Calendar.getInstance().get(Calendar.MONTH) + 1);
File filePath = suffixName[2].equals(type)? new File(SAVE_PATH + "//data//" +"image" + suffix): new File(SAVE_PATH + "//data//" +"audio" + suffix);
if (!filePath.exists() && !filePath.isDirectory()) {
if (separator.equals(File.separator)) {
log.info("Liunx下创建");
filePath.setWritable(true, false);
filePath.mkdirs();
} else {
log.info("windows下创建");
filePath.mkdirs();
}
}
//transferto()方法,是springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘
log.info("存储地址:" + filePath.getPath());
try {
file.transferTo(new File(filePath.getPath()+ "//" + newfileName));
String[] response= new String[2];
response[0] = filePath.getPath()+ "//" + newfileName;
response[1] = type;
return response;
} catch (IOException e) {
e.printStackTrace();
throw MyExceptionUtil.mxe("上传文件失败!",e);
}
}
private static Optional<RelationType> getRelationDescription(GraphTraversalSource traversal, UUID typeId) {
return getFirst(traversal
.V()
//.has(T.label, LabelP.of("relationtype"))
.has("tim_id", typeId.toString())
)
.map(RelationType::relationType);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, O msg) throws Exception {
UUID uuid = CHANNEL_UUID.get(ctx.channel());
if (null != uuid) {
Session session = SESSIONS.get(uuid);
if (null != session) {
this.processor.addRequest(newExecutor(session, msg));
}
}
}
private PlayerContext(UUID playerUuid, int width, int height, boolean forceUnicode, TextUtils utils) {
this.playerUUID = playerUuid;
this.width = width;
this.height = height;
this.forceUnicode = forceUnicode;
this.utils = utils;
}
@Test
void should_return_409_when_no_need_to_publish() {
UUID createdBlogId = createBlogAndGetId("Test Blog", "Something...", authorId);
publishBlog(createdBlogId);
publishBlog(createdBlogId)
.then()
.spec(CONFLICT_SPEC)
.body("message", is("no need to publish"));
}
/**
* Constructs an instance. Call {@link #release()} when the instance is no longer required.
*
* @param uuid The UUID of the drm scheme.
* @param mediaDrm An underlying {@link ExoMediaDrm} for use by the manager.
* @param callback Performs key and provisioning requests.
* @param optionalKeyRequestParameters An optional map of parameters to pass as the last argument
* to {@link MediaDrm#getKeyRequest(byte[], byte[], String, int, HashMap)}. May be null.
* @see DefaultDrmSessionManager#DefaultDrmSessionManager(java.util.UUID, ExoMediaDrm,
* MediaDrmCallback, HashMap)
*/
public OfflineLicenseHelper(
UUID uuid,
ExoMediaDrm<T> mediaDrm,
MediaDrmCallback callback,
@Nullable HashMap<String, String> optionalKeyRequestParameters) {
handlerThread = new HandlerThread("OfflineLicenseHelper");
handlerThread.start();
conditionVariable = new ConditionVariable();
DefaultDrmSessionEventListener eventListener =
new DefaultDrmSessionEventListener() {
@Override
public void onDrmKeysLoaded() {
conditionVariable.open();
}
@Override
public void onDrmSessionManagerError(Exception e) {
conditionVariable.open();
}
@Override
public void onDrmKeysRestored() {
conditionVariable.open();
}
@Override
public void onDrmKeysRemoved() {
conditionVariable.open();
}
};
drmSessionManager =
new DefaultDrmSessionManager<>(uuid, mediaDrm, callback, optionalKeyRequestParameters);
drmSessionManager.addListener(new Handler(handlerThread.getLooper()), eventListener);
}
/**
* Adds the specified {@code amount}.
*
* @param uuid the uuid
* @param amount the amount to add
* @return a promise encapsulating the operation
*/
public Promise<Void> add(UUID uuid, BigDecimal amount) {
Objects.requireNonNull(uuid, "uuid");
if (amount.equals(BigDecimal.ZERO)) {
return Promise.completed(null);
}
if (amount.signum() == -1) {
throw new IllegalArgumentException("amount < 0");
}
return doAdd(uuid, amount);
}