List of usage examples for java.util UUID nameUUIDFromBytes
public static UUID nameUUIDFromBytes(byte[] name)
From source file:org.marinemc.util.mojang.UUIDHandler.java
/** * @param name/*from ww w .j a va2 s . c om*/ * to use as key * @return UUID (name hash) */ public UUID getUuidOfflineMode(final String name) { final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); add(name, uuid); return uuid; }
From source file:com.ecyrd.jspwiki.content.Exporter.java
/** * The generated UUID of a page is based on the Wiki name and the * page name (or path).//ww w . j a va2s . c om * * @param p * @return * @throws IOException */ private String mkUuid(String wiki, String name) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(wiki.getBytes("UTF-8")); out.write(name.getBytes("UTF-8")); return UUID.nameUUIDFromBytes(out.toByteArray()).toString(); }
From source file:org.openmrs.util.databasechange.MigrateConceptReferenceTermChangeSet.java
/** * @see liquibase.change.custom.CustomTaskChange#execute(liquibase.database.Database) *//*from w w w . j a v a 2s . c o m*/ @Override public void execute(Database database) throws CustomChangeException { final JdbcConnection connection = (JdbcConnection) database.getConnection(); Boolean prevAutoCommit = null; PreparedStatement selectTypes = null; PreparedStatement batchUpdateMap = null; PreparedStatement selectMap = null; PreparedStatement updateMapTerm = null; PreparedStatement insertTerm = null; PreparedStatement updateMapType = null; try { prevAutoCommit = connection.getAutoCommit(); connection.setAutoCommit(false); //Prepare a list of types and their ids. Map<String, Integer> typesToIds = new HashMap<String, Integer>(); selectTypes = connection.prepareStatement("select * from concept_map_type"); selectTypes.execute(); ResultSet selectTypeResult = selectTypes.getResultSet(); while (selectTypeResult.next()) { typesToIds.put(selectTypeResult.getString("name").trim().toUpperCase(), selectTypeResult.getInt("concept_map_type_id")); } selectTypes.close(); //The FK on concept_reference_term_id is not yet created so we are safe to copy over IDs. //The trims are done to be able to compare properly. batchUpdateMap = connection.prepareStatement( "update concept_reference_map set" + " concept_reference_term_id = concept_map_id," + " source_code = trim(source_code), comment = trim(comment)"); batchUpdateMap.execute(); batchUpdateMap.close(); //Preparing statements for use in the loop. updateMapTerm = connection.prepareStatement( "update concept_reference_map set" + " concept_reference_term_id = ? where concept_map_id = ?"); insertTerm = connection.prepareStatement("insert into concept_reference_term" + " (concept_reference_term_id, uuid, concept_source_id, code, creator, date_created, description)" + " values (?, ?, ?, ?, ?, ?, ?)"); updateMapType = connection.prepareStatement( "update concept_reference_map set" + " concept_map_type_id = ? where concept_map_id = ?"); int prevSource = -1; String prevSourceCode = null; String prevComment = null; int prevInsertedTerm = -1; //In addition to source and source_code we order by UUID to always insert the same term if run on different systems. selectMap = connection.prepareStatement( "select * from concept_reference_map" + " order by source, source_code, uuid"); selectMap.execute(); final ResultSet selectMapResult = selectMap.getResultSet(); while (selectMapResult.next()) { final int conceptMapId = selectMapResult.getInt("concept_map_id"); final int source = selectMapResult.getInt("source"); final String sourceCode = selectMapResult.getString("source_code"); final String comment = selectMapResult.getString("comment"); final int creator = selectMapResult.getInt("creator"); final Date dateCreated = selectMapResult.getDate("date_created"); final String uuid = selectMapResult.getString("uuid"); final Integer mapTypeId = determineMapTypeId(comment, typesToIds); final int updatedMapTypeId = (mapTypeId == null) ? typesToIds.get(DEFAULT_CONCEPT_MAP_TYPE) : mapTypeId; updateMapType.setInt(1, updatedMapTypeId); updateMapType.setInt(2, conceptMapId); updateMapType.execute(); if (updateMapType.getUpdateCount() != 1) { throw new CustomChangeException("Failed to set map type: " + mapTypeId + " for map: " + conceptMapId + ", updated rows: " + updateMapType.getUpdateCount()); } if (source == prevSource && (sourceCode == prevSourceCode || (sourceCode != null && sourceCode.equals(prevSourceCode)))) { if (mapTypeId == null && comment != null && !comment.equals(prevComment)) { log.warn("Lost comment '" + comment + "' for map " + conceptMapId + ". Preserved comment " + prevComment); } //We need to use the last inserted term. updateMapTerm.setInt(1, prevInsertedTerm); updateMapTerm.setInt(2, conceptMapId); updateMapTerm.execute(); if (updateMapTerm.getUpdateCount() != 1) { throw new CustomChangeException( "Failed to set reference term: " + prevInsertedTerm + " for map: " + conceptMapId + ", updated rows: " + updateMapTerm.getUpdateCount()); } } else { insertTerm.setInt(1, conceptMapId); //We need to guaranty that UUIDs are always the same when run on different systems. insertTerm.setString(2, UUID.nameUUIDFromBytes(uuid.getBytes()).toString()); insertTerm.setInt(3, source); insertTerm.setString(4, sourceCode); insertTerm.setInt(5, creator); insertTerm.setDate(6, dateCreated); if (mapTypeId == null) { insertTerm.setString(7, comment); } else { insertTerm.setString(7, null); } insertTerm.execute(); prevInsertedTerm = conceptMapId; } prevSource = source; prevSourceCode = sourceCode; prevComment = comment; } selectMap.close(); updateMapType.close(); updateMapTerm.close(); insertTerm.close(); connection.commit(); } catch (Exception e) { try { if (connection != null) { connection.rollback(); } } catch (Exception ex) { log.error("Failed to rollback", ex); } throw new CustomChangeException(e); } finally { closeStatementQuietly(selectTypes); closeStatementQuietly(batchUpdateMap); closeStatementQuietly(selectMap); closeStatementQuietly(updateMapTerm); closeStatementQuietly(insertTerm); closeStatementQuietly(updateMapType); if (connection != null && prevAutoCommit != null) { try { connection.setAutoCommit(prevAutoCommit); } catch (DatabaseException e) { log.error("Failed to reset auto commit", e); } } } }
From source file:org.ecocean.media.MediaAsset.java
public static String generateUUIDv3(int id, byte b1, byte b2) { if (id == MediaAssetFactory.NOT_SAVED) return null; if (id < 0) return null; byte[] b = new byte[6]; b[0] = b1;/* w w w .j a v a2s . co m*/ b[1] = b2; b[2] = (byte) (id >> 24); b[3] = (byte) (id >> 16); b[4] = (byte) (id >> 8); b[5] = (byte) (id >> 0); return UUID.nameUUIDFromBytes(b).toString(); }
From source file:eu.matejkormuth.rpgdavid.starving.listeners.HiddenCommandsListener.java
@EventHandler private void onCommand(final PlayerCommandPreprocessEvent event) { // Command for listing all items. if (event.getMessage().equalsIgnoreCase("/items")) { List<Item> items = Starving.getInstance().getItemManager().getItems(); for (int j = 0; j < items.size(); j++) { Item i = items.get(j);/*ww w . j a v a 2 s . co m*/ event.getPlayer().sendMessage(j + " - " + i.getName()); } } // Command for giving custom items. else if (event.getMessage().contains("/itemsgive")) { List<Item> items = Starving.getInstance().getItemManager().getItems(); for (int j = 0; j < items.size(); j++) { Item i = items.get(j); if (j == Integer.valueOf(event.getMessage().split(Pattern.quote(" "))[1])) { event.getPlayer().getInventory().addItem(i.toItemStack()); } } } // Command for giving custom chemicals. else if (event.getMessage().contains("/chemical")) { if (!event.getMessage().contains(" ")) { event.getPlayer().sendMessage("args missing!"); } String args = event.getMessage().split(Pattern.quote(" "))[1]; String[] chemicals = args.split(Pattern.quote(",")); ChemicalItem ci = new ChemicalItem("spawnedChemicalItem", new ChemicalCompound()) { @Override public Recipe getRecipe() { return null; } @Override protected void onConsume0(Player player) { } }; for (String chemical : chemicals) { String[] parts = chemical.split(Pattern.quote(":")); String name = parts[0]; String amount = parts[1]; for (Chemical ch : Chemicals.all()) { if (ch.getName().equalsIgnoreCase(name)) { ci.getContents().add(ch, Float.valueOf(amount)); } } } event.getPlayer().getInventory().addItem(ci.toItemStack()); } // Command for setting entities target. else if (event.getMessage().contains("/settarget")) { String[] parts = event.getMessage().split(" "); int entity = Integer.valueOf(parts[1]); int target = Integer.valueOf(parts[2]); for (Entity e : Worlds.first().getEntities()) { if (e.getEntityId() == target) { Starving.getInstance().getZombieManager().get(entity).setFollowTarget(e); } } } // Command for spawning zombie walking the dog. else if (event.getMessage().contains("/zombieeaster")) { ZombieWithDog.spawn(event.getPlayer().getLocation()); } // Command for settings time. else if (event.getMessage().contains("/time set")) { String[] parts = event.getMessage().split(" "); int time = Integer.valueOf(parts[2]); event.getPlayer().sendMessage(ChatColor.YELLOW + "[Starving] Shifting time..."); Starving.getInstance().getRegistered(TimeUpdater.class).vanllaSetMoveTime(time); event.getPlayer().sendMessage(ChatColor.GREEN + "[Starving] Time set!"); } // Command for spawning zombie. else if (event.getMessage().contains("/zombie")) { String[] parts = event.getMessage().split(" "); if (parts.length == 2) { int count = Integer.valueOf(parts[1]); for (int i = 0; i < count; i++) { Starving.getInstance().getZombieManager().spawnAt(event.getPlayer().getLocation() .add((Math.random() - 0.5) * count / 4, 0, (Math.random() - 0.5) * count / 4)); } } else { Starving.getInstance().getZombieManager().spawnAt(event.getPlayer().getLocation()); } } // Command for testing some random things. else if (event.getMessage().contains("/darkness")) { ((CraftPlayer) event.getPlayer()).getHandle().playerConnection .sendPacket(new PacketPlayOutGameStateChange(7, 0.001f)); ((CraftPlayer) event.getPlayer()).getHandle().playerConnection .sendPacket(new PacketPlayOutGameStateChange(8, 160)); } // Command for testing some random things. else if (event.getMessage().contains("/npctest")) { String name = "debilko" + (int) Math.floor(Math.random() * 1000000); NPC npc = Starving.getInstance().getNPCManager().getMainRegistry().createPlayer() .withProfile(UUID.nameUUIDFromBytes(name.getBytes()), name) .withSpawnLocation(event.getPlayer().getLocation()).spawn(); event.getPlayer().teleport(npc.getLocation()); } // Command for generating access key. else if (event.getMessage().contains("/genkey")) { char[] VALID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray(); int keyLength = 32; char[] key = new char[keyLength]; for (int i = 0; i < keyLength; i++) { key[i] = VALID_CHARS[RandomUtils.nextInt(VALID_CHARS.length - 1)]; } event.getPlayer().sendMessage("Your new accesskey is: " + new String(key)); Data.of(event.getPlayer()).setRemoteAccesKey(new String(key)); event.getPlayer().sendMessage("http://starving.eu/key.php?key=" + new String(key)); } // Command for opening custom items inventory. else if (event.getMessage().contains("/itemsinv")) { ItemManager im = Starving.getInstance().getItemManager(); int size = (im.getItems().size() / 9); Inventory inv = Bukkit.createInventory(null, 9 * (size + 1), ChatColor.GOLD + "Custom items: "); List<Item> sorted = im.getItems(); Collections.sort(sorted, new ItemNameComparator()); for (Item i : sorted) { inv.addItem(i.toItemStack()); } event.getPlayer().openInventory(inv); } // Command for testing some random things. else if (event.getMessage().contains("/itemdropvehicle")) { org.bukkit.entity.Item i = ItemDrops.drop(event.getPlayer().getLocation(), Items.of(Material.APPLE)); i.setVelocity(event.getPlayer().getEyeLocation().getDirection().multiply(3)); i.setPassenger(event.getPlayer()); i.setPickupDelay(20 * 15); } // Command for testing some random things. else if (event.getMessage().contains("/peadd")) { // FIXME: Please, remove this soon. Only for testing. ParticleEmitter pe = new ParticleEmitter(new Location(Bukkit.getWorld("Beta"), 571.5, 68, -235.5), 1f, 40, ParticleEffect.SMOKE_LARGE); pe.setOffsets(0.5f, 0.1f, 0.5f); pe.setDirection(new Vector(0.1f, 0, 0.15f)); Starving.getInstance().getParticleEmmiters().add(pe); ParticleEmitter pe2 = new ParticleEmitter(new Location(Bukkit.getWorld("Beta"), 571.5, 68, -235.5), 1f, 80, ParticleEffect.REDSTONE); pe2.setOffsets(0.5f, 0.1f, 0.5f); pe2.setColor(new ParticleEffect.OrdinaryColor(255, 0, 255)); //pe2.setDirection(new Vector(0.1f, 0, 0.15f)); Starving.getInstance().getParticleEmmiters().add(pe2); } // Command for testing some random things. else if (event.getMessage().contains("/peclear")) { Starving.getInstance().getParticleEmmiters().clear(); } // Command for testing some random things. else if (event.getMessage().contains("/ason")) { Starving.getInstance().getAmbientSoundManager().addPlayer(event.getPlayer()); } // Command for testing some random things. else if (event.getMessage().contains("/asoff")) { Starving.getInstance().getAmbientSoundManager().removePlayer(event.getPlayer()); } }
From source file:org.apache.kylin.source.hive.HiveMetadataExplorer.java
@Override public ColumnDesc[] evalQueryMetadata(String query) { if (StringUtils.isEmpty(query)) { throw new RuntimeException("Evaluate query shall not be empty."); }//from w ww . j a va2 s . c o m KylinConfig config = KylinConfig.getInstanceFromEnv(); String tmpDatabase = config.getHiveDatabaseForIntermediateTable(); String tmpView = "kylin_eval_query_" + UUID.nameUUIDFromBytes(query.getBytes(StandardCharsets.UTF_8)).toString().replace("-", ""); String dropViewSql = "DROP VIEW IF EXISTS " + tmpDatabase + "." + tmpView; String evalViewSql = "CREATE VIEW " + tmpDatabase + "." + tmpView + " as " + query; try { logger.debug("Removing duplicate view {}", tmpView); hiveClient.executeHQL(dropViewSql); logger.debug("Creating view {} for query: {}", tmpView, query); hiveClient.executeHQL(evalViewSql); logger.debug("Evaluating query columns' metadata"); HiveTableMeta hiveTableMeta = hiveClient.getHiveTableMeta(tmpDatabase, tmpView); return extractColumnFromMeta(hiveTableMeta); } catch (Exception e) { throw new RuntimeException("Cannot evaluate metadata of query: " + query, e); } finally { try { logger.debug("Cleaning up."); hiveClient.executeHQL(dropViewSql); } catch (Exception e) { logger.warn("Cannot drop temp view of query: {}", query, e); } } }
From source file:org.photovault.replication.ChangeDTO.java
public UUID calcUuid() throws IOException { return UUID.nameUUIDFromBytes(getXmlData()); }
From source file:com.digitalpebble.behemoth.util.ContentExtractor.java
private void generateDocs(Path input, Path dir, int[] count) throws IOException, ArchiveException { DocumentFilter docFilter = DocumentFilter.getFilters(getConf()); Reader[] cacheReaders = SequenceFileOutputFormat.getReaders(getConf(), input); for (Reader current : cacheReaders) { // read the key + values in that file Text key = new Text(); BehemothDocument inputDoc = new BehemothDocument(); while (current.next(key, inputDoc)) { count[0]++;//from w w w.j a v a 2 s . co m // filter the doc? if (!docFilter.keep(inputDoc)) continue; if (dumpBinary && inputDoc.getContent() == null) continue; else if (!dumpBinary && inputDoc.getText() == null) continue; String fileName = Integer.toString(count[0]); String urldoc = inputDoc.getUrl(); if (mode.equals(FileNamingMode.URL) && urldoc != null && urldoc.length() > 0) { fileName = URLEncoder.encode(urldoc, "UTF-8"); } else if (mode.equals(FileNamingMode.UUID) && urldoc != null && urldoc.length() > 0) { fileName = UUID.nameUUIDFromBytes(urldoc.getBytes()).toString(); } else { fileName = String.format("%09d", count[0]); } if (!dumpBinary) fileName += ".txt"; byte[] contentBytes; if (dumpBinary) contentBytes = inputDoc.getContent(); else contentBytes = inputDoc.getText().getBytes("UTF-8"); // out.write(contentBytes, 0, contentBytes.length); addToArchive(fileName, contentBytes, dir); // add the mapping URL->filename in the index -> archive num index.writeBytes(urldoc + "\t" + fileName + "\t" + String.format("%06d", partNum) + "\n"); } current.close(); } }
From source file:org.kitodo.dataformat.access.DivXmlElementAccess.java
/** * Creates a METS {@code <div>} element from this structure. * * @param mediaUnitIDs// w w w. ja va 2 s . c o m * the assigned identifier for each media unit so that the link * pairs of the struct link section can be formed later * @param smLinkData * the link pairs of the struct link section are added to this * list * @param mets * the METS structure in which the meta-data is added * @return a METS {@code <div>} element */ DivType toDiv(Map<MediaUnit, String> mediaUnitIDs, LinkedList<Pair<String, String>> smLinkData, Mets mets) { DivType div = new DivType(); div.setID(metsReferrerId); div.setLABEL(super.getLabel()); div.setORDERLABEL(super.getOrderlabel()); div.setTYPE(super.getType()); smLinkData.addAll(super.getViews().parallelStream().map(View::getMediaUnit).map(mediaUnitIDs::get) .map(mediaUnitId -> Pair.of(metsReferrerId, mediaUnitId)).collect(Collectors.toList())); Optional<MdSecType> optionalDmdSec = createMdSec(super.getMetadata(), MdSec.DMD_SEC); if (optionalDmdSec.isPresent()) { MdSecType dmdSec = optionalDmdSec.get(); String name = metsReferrerId + ':' + MdSec.DMD_SEC.toString(); dmdSec.setID(UUID.nameUUIDFromBytes(name.getBytes(StandardCharsets.UTF_8)).toString()); mets.getDmdSec().add(dmdSec); div.getDMDID().add(dmdSec); } Optional<AmdSecType> optionalAmdSec = createAmdSec(super.getMetadata(), metsReferrerId, div); if (optionalAmdSec.isPresent()) { AmdSecType admSec = optionalAmdSec.get(); mets.getAmdSec().add(admSec); } if (Objects.nonNull(super.getLink())) { MptrXmlElementAccess.addMptrToDiv(super.getLink(), div); } for (IncludedStructuralElement subincludedStructuralElement : super.getChildren()) { div.getDiv().add( new DivXmlElementAccess(subincludedStructuralElement).toDiv(mediaUnitIDs, smLinkData, mets)); } return div; }
From source file:de.Keyle.MyPet.api.Util.java
public static UUID getOfflinePlayerUUID(String name) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); }