List of usage examples for java.util UUID UUID
public UUID(long mostSigBits, long leastSigBits)
From source file:org.apache.usergrid.persistence.cassandra.EntityManagerFactoryImplIT.java
@Test public void testCreateAndGet() throws Exception { TraceTag traceTag = traceTagManager.create("testCreateAndGet"); traceTagManager.attach(traceTag);// ww w.ja va2 s. co m logger.info("EntityDaoTest.testCreateAndGet"); UUID applicationId = createApplication("EntityManagerFactoryImplIT", "testCreateAndGet" + UUIDGenerator.newTimeUUID()); logger.info("Application id " + applicationId); EntityManager em = emf.getEntityManager(applicationId); int i; List<Entity> things = new ArrayList<Entity>(); for (i = 0; i < 10; i++) { Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("name", "thing" + i); Entity thing = em.create("thing", properties); assertNotNull("thing should not be null", thing); assertFalse("thing id not valid", thing.getUuid().equals(new UUID(0, 0))); assertEquals("name not expected value", "thing" + i, thing.getProperty("name")); things.add(thing); } assertEquals("should be ten entities", 10, things.size()); i = 0; for (Entity entity : things) { Entity thing = em.get(new SimpleEntityRef("thing", entity.getUuid())); assertNotNull("thing should not be null", thing); assertFalse("thing id not valid", thing.getUuid().equals(new UUID(0, 0))); assertEquals("name not expected value", "thing" + i, thing.getProperty("name")); i++; } List<UUID> ids = new ArrayList<UUID>(); for (Entity entity : things) { ids.add(entity.getUuid()); Entity en = em.get(new SimpleEntityRef("thing", entity.getUuid())); String type = en.getType(); assertEquals("type not expected value", "thing", type); Object property = en.getProperty("name"); assertNotNull("thing name property should not be null", property); assertTrue("thing name should start with \"thing\"", property.toString().startsWith("thing")); Map<String, Object> properties = en.getProperties(); assertEquals("number of properties wrong", 6, properties.size()); } i = 0; Results results = em.getEntities(ids, "thing"); for (Entity thing : results) { assertNotNull("thing should not be null", thing); assertFalse("thing id not valid", thing.getUuid().equals(new UUID(0, 0))); assertEquals("wrong type", "thing", thing.getType()); assertNotNull("thing name should not be null", thing.getProperty("name")); String name = thing.getProperty("name").toString(); assertEquals("unexpected name", "thing" + i, name); i++; } assertEquals("entities unfound entity name count incorrect", 10, i); /* * List<UUID> entities = emf.findEntityIds(applicationId, "thing", null, * null, 100); assertNotNull("entities list should not be null", * entities); assertEquals("entities count incorrect", 10, * entities.size()); */ traceTagReporter.report(traceTagManager.detach()); }
From source file:com.palantir.atlasdb.ptobject.EncodingUtils.java
public static UUID decodeFlippedUUID(byte[] bytes, int offset) { ByteBuffer buf = ByteBuffer.wrap(bytes, offset, 2 * Longs.BYTES).order(ByteOrder.BIG_ENDIAN); long mostSigBits = -1L ^ buf.getLong(); long leastSigBits = -1L ^ buf.getLong(); return new UUID(mostSigBits, leastSigBits); }
From source file:info.archinnov.achilles.it.TestDSLEntityWithClusterings.java
@Test public void should_dsl_select_slice_with_clustering_IN_same_partition() throws Exception { //Given/*from ww w. ja v a 2 s. c o m*/ final Map<String, Object> values = new HashMap<>(); final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE); values.put("id1", id); values.put("id2", id); values.put("id3", id); values.put("id4", id); values.put("id5", id); final UUID uuid1 = new UUID(0L, 0L); final UUID uuid2 = new UUID(0L, 1L); values.put("uuid1", uuid1); values.put("uuid2", uuid1); values.put("uuid3", uuid1); values.put("uuid4", uuid2); values.put("uuid5", uuid2); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); final Date date3 = dateFormat.parse("2015-10-03 00:00:00 GMT"); final Date date5 = dateFormat.parse("2015-10-05 00:00:00 GMT"); values.put("date1", "'2015-10-01 00:00:00+0000'"); values.put("date2", "'2015-10-02 00:00:00+0000'"); values.put("date3", "'2015-10-03 00:00:00+0000'"); values.put("date4", "'2015-10-04 00:00:00+0000'"); values.put("date5", "'2015-10-05 00:00:00+0000'"); scriptExecutor.executeScriptTemplate("EntityWithClusteringColumns/insert_many_rows.cql", values); /* Data are ordered as: uuid1, date3, uuid1, date2, uuid1, date1, uuid2, date5, uuid2, date4 because date is ORDERED BY DESC natively */ //When final List<EntityWithClusteringColumns> list = manager.dsl().select().uuid().date().value().fromBaseTable() .where().id_Eq(id).uuid_IN(uuid1, uuid2).date_Gte_And_Lte(date3, date5).getList(); //Then assertThat(list).hasSize(3); assertThat(list.stream().map(EntityWithClusteringColumns::getValue).sorted().collect(toList())) .containsExactly("val3", "val4", "val5"); }
From source file:org.pidome.client.phone.services.SystemService.java
/** * Generate an unique id for this device. * @param context/*w ww .j a v a 2s. com*/ * @return */ private String generateDeviceId(Context context) { final String macAddr, androidId; WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInf = wifiMan.getConnectionInfo(); macAddr = wifiInf.getMacAddress(); androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); UUID deviceUuid; try { deviceUuid = new UUID(androidId.hashCode(), macAddr.hashCode()); } catch (NullPointerException ex) { deviceUuid = new UUID(androidId.hashCode(), androidId.hashCode()); } return deviceUuid.toString(); }
From source file:com.strategicgains.docussandra.controller.QueryControllerTest.java
/** * Tests that the POST /{databases}/{table}/query endpoint properly runs a * query with limits.//from ww w . j a v a2 s . c o m */ @Test public void postQueryTestWithLimitAndOffset2() { Query q = new Query(); q.setWhere("field1 = 'this is my data'"); q.setTable("mytable"); //act given().header("limit", "2").header("offset", "2").body("{\"where\":\"" + q.getWhere() + "\"}").expect() .statusCode(206) //.header("Location", startsWith(RestAssured.basePath + "/")) .body("", notNullValue()).body("id", notNullValue()) .body("id[0]", equalTo(new UUID(Long.MAX_VALUE - 31, 1l).toString())) .body("object[0]", notNullValue()) .body("object[0]", containsString("this is some more random data30")) .body("id[1]", equalTo(new UUID(Long.MAX_VALUE - 30, 1l).toString())) .body("object[1]", notNullValue()) .body("object[1]", containsString("this is some more random data29")).when().post(""); }
From source file:io.lavagna.service.CalendarService.java
public Calendar getUserCalendar(String userToken) throws URISyntaxException, ParseException { UserWithPermission user;// w ww . jav a 2s . co m try { user = findUserFromCalendarToken(userToken); } catch (EmptyResultDataAccessException ex) { throw new SecurityException("Invalid token"); } if (userRepository.isCalendarFeedDisabled(user)) { throw new SecurityException("Calendar feed disabled"); } final Calendar calendar = new Calendar(); calendar.getProperties().add(new ProdId("-//Lavagna//iCal4j 1.0//EN")); calendar.getProperties().add(Version.VERSION_2_0); calendar.getProperties().add(CalScale.GREGORIAN); calendar.getProperties().add(Method.PUBLISH); final String applicationUrl = StringUtils .appendIfMissing(configurationRepository.getValue(Key.BASE_APPLICATION_URL), "/"); final List<VEvent> events = new ArrayList<>(); final SimpleDateFormat releaseDateFormatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); // Milestones List<Project> projects = projectService.findAllProjects(user); for (Project project : projects) { CardLabel milestoneLabel = cardLabelRepository.findLabelByName(project.getId(), "MILESTONE", CardLabel.LabelDomain.SYSTEM); Url mUrl = new Url(new URI(String.format("%s%s/milestones/", applicationUrl, project.getShortName()))); for (LabelListValueWithMetadata m : cardLabelRepository .findListValuesByLabelId(milestoneLabel.getId())) { if (m.getMetadata().containsKey("releaseDate")) { java.util.Date date = releaseDateFormatter.parse(m.getMetadata().get("releaseDate") + " 12:00"); SearchFilter filter = filter(SearchFilter.FilterType.MILESTONE, SearchFilter.ValueType.STRING, m.getValue()); SearchFilter notTrashFilter = filter(SearchFilter.FilterType.NOTLOCATION, SearchFilter.ValueType.STRING, BoardColumn.BoardColumnLocation.TRASH.toString()); SearchResults cards = searchService.find(Arrays.asList(filter, notTrashFilter), project.getId(), null, user); double closed = 0; double total = 0; StringBuilder descBuilder = new StringBuilder(); for (CardFullWithCounts card : cards.getFound()) { if (card.getColumnDefinition() == ColumnDefinition.CLOSED) { closed++; } total++; descBuilder.append(getEventName(card)); descBuilder.append("\n"); } final String name = String.format("%s - %s (%.0f%%)", project.getShortName(), m.getValue(), total > 0 ? 100 * closed / total : 100); final VEvent event = new VEvent(new Date(date.getTime()), name); event.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE); event.getProperties().add(new Description(descBuilder.toString())); final UUID id = new UUID(getLong(m.getCardLabelId(), m.getId()), getLong(m.getOrder(), 0)); event.getProperties().add(new Uid(id.toString())); // Reminder on milestone's date if (!m.getMetadata().containsKey("status") || m.getMetadata().get("status").equals("CLOSED")) { final VAlarm reminder = new VAlarm(new Dur(0, 0, 0, 0)); reminder.getProperties().add(Action.DISPLAY); reminder.getProperties().add(new Description(name)); event.getAlarms().add(reminder); } // Url event.getProperties().add(mUrl); events.add(event); } } } // Cards Map<Integer, UserDescription> usersCache = new HashMap<>(); Map<Integer, CardFullWithCounts> map = new LinkedHashMap<>(); SearchFilter locationFilter = filter(SearchFilter.FilterType.LOCATION, SearchFilter.ValueType.STRING, BoardColumn.BoardColumnLocation.BOARD.toString()); SearchFilter aFilter = filter(SearchFilter.FilterType.ASSIGNED, SearchFilter.ValueType.CURRENT_USER, "me"); for (CardFullWithCounts card : searchService.find(Arrays.asList(locationFilter, aFilter), null, null, user) .getFound()) { map.put(card.getId(), card); } SearchFilter wFilter = filter(SearchFilter.FilterType.WATCHED_BY, SearchFilter.ValueType.CURRENT_USER, "me"); for (CardFullWithCounts card : searchService.find(Arrays.asList(locationFilter, wFilter), null, null, user) .getFound()) { map.put(card.getId(), card); } for (CardFullWithCounts card : map.values()) { Url cardUrl = new Url(new URI(String.format("%s%s/%s-%s", applicationUrl, card.getProjectShortName(), card.getBoardShortName(), card.getSequence()))); CardDataHistory cardDesc = cardDataService.findLatestDescriptionByCardId(card.getId()); for (LabelAndValue lav : card.getLabelsWithType(LabelType.TIMESTAMP)) { String name = getEventName(card); final VEvent event = new VEvent(new Date(lav.getLabelValueTimestamp()), name); event.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE); event.getProperties().add(new Created(new DateTime(card.getCreationDate()))); event.getProperties().add(new LastModified(new DateTime(card.getLastUpdateTime()))); final UUID id = new UUID(getLong(card.getColumnId(), card.getId()), getLong(lav.getLabelId(), lav.getLabelValueId())); event.getProperties().add(new Uid(id.toString())); // Reminder on label's date if (card.getColumnDefinition() != ColumnDefinition.CLOSED) { final VAlarm reminder = new VAlarm(new Dur(0, 0, 0, 0)); reminder.getProperties().add(Action.DISPLAY); reminder.getProperties().add(new Description(name)); event.getAlarms().add(reminder); } // Organizer UserDescription ud = getUserDescription(card.getCreationUser(), usersCache); Organizer organizer = new Organizer(URI.create(ud.getEmail())); organizer.getParameters().add(new Cn(ud.getName())); event.getProperties().add(organizer); // Url event.getProperties().add(cardUrl); // Description if (cardDesc != null) { event.getProperties().add(new Description(cardDesc.getContent())); } events.add(event); } } calendar.getComponents().addAll(events); return calendar; }
From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java
public void insertNetwork(WellKnownObject wko) throws SQLException { String tableName = wko.tableName() + "_network"; PreparedStatement s = connection.prepareStatement(String.format( "INSERT into %s (id, parent, relationship, child, updated_by) VALUES (?, ?, ?, ?, ?)", tableName)); try {//from w w w.j a v a2 s .c om s.setString(1, UuidGenerator.toBase64(new UUID(0, 0))); s.setString(2, wko.id()); s.setString(3, WellKnownRelationship.RELATIONSHIP.id()); s.setString(4, wko.id()); s.setString(5, WellKnownAgency.CORE.id()); s.execute(); } catch (SQLException e) { throw new SQLException(String.format("Unable to insert root %s", tableName), e); } }
From source file:org.apache.nifi.web.api.ApplicationResource.java
protected String generateUuid() { final Optional<String> seed = getIdGenerationSeed(); UUID uuid;/* ww w. java 2s . com*/ if (seed.isPresent()) { try { UUID seedId = UUID.fromString(seed.get()); uuid = new UUID(seedId.getMostSignificantBits(), seed.get().hashCode()); } catch (Exception e) { logger.warn( "Provided 'seed' does not represent UUID. Will not be able to extract most significant bits for ID generation."); uuid = UUID.nameUUIDFromBytes(seed.get().getBytes(StandardCharsets.UTF_8)); } } else { uuid = ComponentIdGenerator.generateId(); } return uuid.toString(); }
From source file:edu.ku.brc.af.core.UsageTracker.java
/** * Gets the installation ID that 'uniquely' identifies the running instance * from other installations.//from w ww . ja v a 2s. c o m * * @return the installation ID string */ public synchronized static String getInstallId() { AppPreferences appPrefs = AppPreferences.getLocalPrefs(); if (appPrefs.isAvailable()) { // get the first part of the install ID String installIdStart = appPrefs.get("InstallIdStart", null); //$NON-NLS-1$ if (installIdStart == null) { // create a new ID start (this is the first time the app has run) Random r = new Random(System.currentTimeMillis()); UUID idStart = new UUID(r.nextLong(), r.nextLong()); installIdStart = idStart.toString(); appPrefs.put("InstallIdStart", installIdStart); //$NON-NLS-1$ } // get the last part of the install ID String installIdEnd = appPrefs.get("InstallIdEnd", null); //$NON-NLS-1$ File pluginRegFile = XMLHelper.getConfigDir("plugin_registry.xml"); //$NON-NLS-1$ long lastMod = pluginRegFile.lastModified(); String lastModString = Long.toHexString(lastMod); if (installIdEnd == null || !installIdEnd.equals(lastModString)) { // somebody must have copied this install to a new storage // reset the InstallIdEnd preference clearUsageStats(); appPrefs.put("InstallIdEnd", lastModString); //$NON-NLS-1$ installIdEnd = lastModString; } String installId = installIdStart + "--" + installIdEnd; //$NON-NLS-1$ return installId; } return null; }
From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java
private void createNullInference() throws SQLException { PreparedStatement s = connection.prepareStatement( "INSERT into ruleform.network_inference (id, premise1, premise2, inference, updated_by) VALUES (?, ?, ?, ?, ?)"); try {/*from w w w . j a va 2 s . co m*/ s.setString(1, UuidGenerator.toBase64(new UUID(0, 0))); s.setString(2, WellKnownRelationship.RELATIONSHIP.id()); s.setString(3, WellKnownRelationship.RELATIONSHIP.id()); s.setString(4, WellKnownRelationship.RELATIONSHIP.id()); s.setString(5, WellKnownAgency.CORE.id()); s.execute(); } catch (SQLException e) { throw new SQLException("Unable to insert null inference", e); } }