List of usage examples for java.util UUID nameUUIDFromBytes
public static UUID nameUUIDFromBytes(byte[] name)
From source file:RhodesService.java
/** * This method is used only for non-Motorola devices as the UUID needs to be computed by other parameters. * @return 32-byte long UUID// ww w .jav a2 s . c o m */ private static String computeUUID() { RhodesService srv = RhodesService.getInstance(); if (srv == null) throw new IllegalStateException("No rhodes service instance at this moment"); String res = ""; WifiManager wifi = (WifiManager) srv.getSystemService(Context.WIFI_SERVICE); // Get WiFi status WifiInfo wifiInfo = wifi.getConnectionInfo(); String macAddress = wifiInfo.getMacAddress(); macAddress = macAddress.replaceAll(":", ""); UUID localUuid = UUID.nameUUIDFromBytes(macAddress.getBytes()); res = localUuid.toString().replaceAll("-", ""); return res.toUpperCase(); }
From source file:com.cloud.hypervisor.xenserver.resource.XenServerStorageProcessor.java
@Override public Answer backupSnapshot(final CopyCommand cmd) { final Connection conn = hypervisorResource.getConnection(); final DataTO srcData = cmd.getSrcTO(); final DataTO cacheData = cmd.getCacheTO(); final DataTO destData = cmd.getDestTO(); final int wait = cmd.getWait(); final String primaryStorageNameLabel = srcData.getDataStore().getUuid(); String secondaryStorageUrl = null; NfsTO cacheStore = null;/*from w w w. ja va 2 s. c o m*/ String destPath = null; if (cacheData != null) { cacheStore = (NfsTO) cacheData.getDataStore(); secondaryStorageUrl = cacheStore.getUrl(); destPath = cacheData.getPath(); } else { cacheStore = (NfsTO) destData.getDataStore(); secondaryStorageUrl = cacheStore.getUrl(); destPath = destData.getPath(); } final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData; final SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData; final String snapshotUuid = snapshotTO.getPath(); final String volumeUuid = snapshotTO.getVolume().getPath(); final String prevBackupUuid = snapshotOnImage.getParentSnapshotPath(); final String prevSnapshotUuid = snapshotTO.getParentSnapshotPath(); // By default assume failure String details = null; String snapshotBackupUuid = null; Long physicalSize = null; final Map<String, String> options = cmd.getOptions(); boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot")); boolean result = false; try { final SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel); if (primaryStorageSR == null) { throw new InternalErrorException( "Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel); } final String psUuid = primaryStorageSR.getUuid(conn); final Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn)); final VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid); String snapshotPaUuid = null; if (prevSnapshotUuid != null && !fullbackup) { try { snapshotPaUuid = getVhdParent(conn, psUuid, snapshotUuid, isISCSI); if (snapshotPaUuid != null) { final String snashotPaPaPaUuid = getVhdParent(conn, psUuid, snapshotPaUuid, isISCSI); final String prevSnashotPaUuid = getVhdParent(conn, psUuid, prevSnapshotUuid, isISCSI); if (snashotPaPaPaUuid != null && prevSnashotPaUuid != null && prevSnashotPaUuid.equals(snashotPaPaPaUuid)) { fullbackup = false; } else { fullbackup = true; } } } catch (final Exception e) { s_logger.debug("Failed to get parent snapshots, take full snapshot", e); fullbackup = true; } } final URI uri = new URI(secondaryStorageUrl); final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath(); final DataStoreTO destStore = destData.getDataStore(); final String folder = destPath; String finalPath = null; final String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString(); if (fullbackup) { // the first snapshot is always a full snapshot if (!hypervisorResource.createSecondaryStorageFolder(conn, secondaryStorageMountPath, folder)) { details = " Filed to create folder " + folder + " in secondary storage"; s_logger.warn(details); return new CopyCmdAnswer(details); } final String snapshotMountpoint = secondaryStorageUrl + "/" + folder; SR snapshotSr = null; try { snapshotSr = hypervisorResource.createNfsSRbyURI(conn, new URI(snapshotMountpoint), false); final VDI backedVdi = hypervisorResource.cloudVDIcopy(conn, snapshotVdi, snapshotSr, wait); snapshotBackupUuid = backedVdi.getUuid(conn); final String primarySRuuid = snapshotSr.getUuid(conn); physicalSize = getSnapshotSize(conn, primarySRuuid, snapshotBackupUuid, isISCSI, wait); if (destStore instanceof SwiftTO) { try { final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); final String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO) destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait); final String swiftPath = container + File.separator + destSnapshotName; finalPath = swiftPath; } finally { try { deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid); } catch (final Exception e) { s_logger.debug("Failed to delete snapshot on cache storages", e); } } } else if (destStore instanceof S3TO) { try { finalPath = backupSnapshotToS3(conn, (S3TO) destStore, snapshotSr.getUuid(conn), folder, snapshotBackupUuid, isISCSI, wait); if (finalPath == null) { throw new CloudRuntimeException( "S3 upload of snapshots " + snapshotBackupUuid + " failed"); } } finally { try { deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid); } catch (final Exception e) { s_logger.debug("Failed to delete snapshot on cache storages", e); } } // finalPath = folder + File.separator + snapshotBackupUuid; } else { finalPath = folder + cacheStore.getPathSeparator() + snapshotBackupUuid; } } finally { if (snapshotSr != null) { hypervisorResource.removeSR(conn, snapshotSr); } } } else { final String primaryStorageSRUuid = primaryStorageSR.getUuid(conn); if (destStore instanceof SwiftTO) { final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString(); snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO) destStore, primaryStorageSRUuid, snapshotPaUuid, "S-" + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait); finalPath = container + File.separator + snapshotBackupUuid; } else if (destStore instanceof S3TO) { finalPath = backupSnapshotToS3(conn, (S3TO) destStore, primaryStorageSRUuid, folder, snapshotPaUuid, isISCSI, wait); if (finalPath == null) { throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed"); } } else { final String results = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, isISCSI, wait); final String[] tmp = results.split("#"); snapshotBackupUuid = tmp[1]; physicalSize = Long.parseLong(tmp[2]); finalPath = folder + cacheStore.getPathSeparator() + snapshotBackupUuid; } } // delete primary snapshots with only the last one left destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid); final SnapshotObjectTO newSnapshot = new SnapshotObjectTO(); newSnapshot.setPath(finalPath); newSnapshot.setPhysicalSize(physicalSize); if (fullbackup) { newSnapshot.setParentSnapshotPath(null); } else { newSnapshot.setParentSnapshotPath(prevBackupUuid); } result = true; return new CopyCmdAnswer(newSnapshot); } catch (final XenAPIException e) { details = "BackupSnapshot Failed due to " + e.toString(); s_logger.warn(details, e); } catch (final Exception e) { details = "BackupSnapshot Failed due to " + e.getMessage(); s_logger.warn(details, e); } finally { if (!result) { // remove last bad primary snapshot when exception happens try { destroySnapshotOnPrimaryStorage(conn, snapshotUuid); } catch (final Exception e) { s_logger.debug("clean up snapshot failed", e); } } } return new CopyCmdAnswer(details); }
From source file:com.cloud.storage.resource.NfsSecondaryStorageResource.java
synchronized public String getRootDir(String secUrl) { try {/*from ww w. j a va2s.c o m*/ URI uri = new URI(secUrl); String nfsHost = uri.getHost(); InetAddress nfsHostAddr = InetAddress.getByName(nfsHost); String nfsHostIp = nfsHostAddr.getHostAddress(); String nfsPath = nfsHostIp + ":" + uri.getPath(); String dir = UUID.nameUUIDFromBytes(nfsPath.getBytes()).toString(); String root = _parent + "/" + dir; mount(root, nfsPath); return root; } catch (Exception e) { String msg = "GetRootDir for " + secUrl + " failed due to " + e.toString(); s_logger.error(msg, e); throw new CloudRuntimeException(msg); } }
From source file:org.exoplatform.outlook.OutlookServiceImpl.java
/** * Generate id./*from w w w . j ava2 s . c o m*/ * * @param workspace the workspace * @param path the path * @return the uuid */ protected UUID generateId(String workspace, String path) { StringBuilder s = new StringBuilder(); s.append(workspace); s.append(path); s.append(System.currentTimeMillis()); s.append(String.valueOf(RANDOM.nextLong())); return UUID.nameUUIDFromBytes(s.toString().getBytes()); }
From source file:org.apache.nifi.web.StandardNiFiServiceFacade.java
@Override public TemplateDTO createTemplate(String name, String description, String snippetId) { // get the specified snippet Snippet snippet = snippetDAO.getSnippet(snippetId); // create the template TemplateDTO templateDTO = new TemplateDTO(); templateDTO.setName(name);/*from w ww . j av a 2 s. co m*/ templateDTO.setDescription(description); templateDTO.setTimestamp(new Date()); templateDTO.setSnippet(snippetUtils.populateFlowSnippet(snippet, true, true)); // set the id based on the specified seed final ClusterContext clusterContext = ClusterContextThreadLocal.getContext(); if (clusterContext != null) { templateDTO.setId( UUID.nameUUIDFromBytes(clusterContext.getIdGenerationSeed().getBytes(StandardCharsets.UTF_8)) .toString()); } // create the template Template template = templateDAO.createTemplate(templateDTO); return dtoFactory.createTemplateDTO(template); }
From source file:org.apache.nifi.web.StandardNiFiServiceFacade.java
@Override public TemplateDTO importTemplate(TemplateDTO templateDTO) { // ensure id is set final ClusterContext clusterContext = ClusterContextThreadLocal.getContext(); if (clusterContext != null) { templateDTO.setId(// w w w. j a v a 2s . c o m UUID.nameUUIDFromBytes(clusterContext.getIdGenerationSeed().getBytes(StandardCharsets.UTF_8)) .toString()); } // mark the timestamp templateDTO.setTimestamp(new Date()); // import the template final Template template = templateDAO.importTemplate(templateDTO); // return the template dto return dtoFactory.createTemplateDTO(template); }
From source file:com.cloud.vm.UserVmManagerImpl.java
@Override @ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", create = true) public VMTemplateVO createPrivateTemplateRecord(CreateTemplateCmd cmd, Account templateOwner) throws ResourceAllocationException { Long userId = UserContext.current().getCallerUserId(); Account caller = UserContext.current().getCaller(); boolean isAdmin = (isAdmin(caller.getType())); _accountMgr.checkAccess(caller, null, true, templateOwner); String name = cmd.getTemplateName(); if ((name == null) || (name.length() > 32)) { throw new InvalidParameterValueException( "Template name cannot be null and should be less than 32 characters"); }// ww w .ja va 2s .c o m if (cmd.getTemplateTag() != null) { if (!_accountService.isRootAdmin(caller.getType())) { throw new PermissionDeniedException( "Parameter templatetag can only be specified by a Root Admin, permission denied"); } } // do some parameter defaulting Integer bits = cmd.getBits(); Boolean requiresHvm = cmd.getRequiresHvm(); Boolean passwordEnabled = cmd.isPasswordEnabled(); Boolean isPublic = cmd.isPublic(); Boolean featured = cmd.isFeatured(); int bitsValue = ((bits == null) ? 64 : bits.intValue()); boolean requiresHvmValue = ((requiresHvm == null) ? true : requiresHvm.booleanValue()); boolean passwordEnabledValue = ((passwordEnabled == null) ? false : passwordEnabled.booleanValue()); if (isPublic == null) { isPublic = Boolean.FALSE; } boolean allowPublicUserTemplates = Boolean.parseBoolean(_configDao.getValue("allow.public.user.templates")); if (!isAdmin && !allowPublicUserTemplates && isPublic) { throw new PermissionDeniedException( "Failed to create template " + name + ", only private templates can be created."); } Long volumeId = cmd.getVolumeId(); Long snapshotId = cmd.getSnapshotId(); if ((volumeId == null) && (snapshotId == null)) { throw new InvalidParameterValueException( "Failed to create private template record, neither volume ID nor snapshot ID were specified."); } if ((volumeId != null) && (snapshotId != null)) { throw new InvalidParameterValueException( "Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")"); } HypervisorType hyperType; VolumeVO volume = null; VMTemplateVO privateTemplate = null; if (volumeId != null) { // create template from volume volume = _volsDao.findById(volumeId); if (volume == null) { throw new InvalidParameterValueException( "Failed to create private template record, unable to find volume " + volumeId); } //check permissions _accountMgr.checkAccess(caller, null, true, volume); // If private template is created from Volume, check that the volume will not be active when the private template is // created if (!_storageMgr.volumeInactive(volume)) { String msg = "Unable to create private template for volume: " + volume.getName() + "; volume is attached to a non-stopped VM, please stop the VM first"; if (s_logger.isInfoEnabled()) { s_logger.info(msg); } throw new CloudRuntimeException(msg); } hyperType = _volsDao.getHypervisorType(volumeId); } else { // create template from snapshot SnapshotVO snapshot = _snapshotDao.findById(snapshotId); if (snapshot == null) { throw new InvalidParameterValueException( "Failed to create private template record, unable to find snapshot " + snapshotId); } volume = _volsDao.findById(snapshot.getVolumeId()); VolumeVO snapshotVolume = _volsDao.findByIdIncludingRemoved(snapshot.getVolumeId()); //check permissions _accountMgr.checkAccess(caller, null, true, snapshot); if (snapshot.getStatus() != Snapshot.Status.BackedUp) { throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.Status.BackedUp + " state yet and can't be used for template creation"); } /* // bug #11428. Operation not supported if vmware and snapshots parent volume = ROOT if(snapshot.getHypervisorType() == HypervisorType.VMware && snapshotVolume.getVolumeType() == Type.DATADISK){ throw new UnsupportedServiceException("operation not supported, snapshot with id " + snapshotId + " is created from Data Disk"); } */ hyperType = snapshot.getHypervisorType(); } _resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template); if (!isAdmin || featured == null) { featured = Boolean.FALSE; } Long guestOSId = cmd.getOsTypeId(); GuestOSVO guestOS = _guestOSDao.findById(guestOSId); if (guestOS == null) { throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist."); } String uniqueName = Long.valueOf((userId == null) ? 1 : userId).toString() + UUID.nameUUIDFromBytes(name.getBytes()).toString(); Long nextTemplateId = _templateDao.getNextInSequence(Long.class, "id"); String description = cmd.getDisplayText(); boolean isExtractable = false; Long sourceTemplateId = null; if (volume != null) { VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; if (template != null) { sourceTemplateId = template.getId(); } else if (volume.getVolumeType() == Type.ROOT) { //vm created out of blank template UserVm userVm = ApiDBUtils.findUserVmById(volume.getInstanceId()); sourceTemplateId = userVm.getIsoId(); } } String templateTag = cmd.getTemplateTag(); if (templateTag != null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Adding template tag: " + templateTag); } } privateTemplate = new VMTemplateVO(nextTemplateId, uniqueName, name, ImageFormat.RAW, isPublic, featured, isExtractable, TemplateType.USER, null, null, requiresHvmValue, bitsValue, templateOwner.getId(), null, description, passwordEnabledValue, guestOS.getId(), true, hyperType, templateTag, cmd.getDetails()); if (sourceTemplateId != null) { if (s_logger.isDebugEnabled()) { s_logger.debug( "This template is getting created from other template, setting source template Id to: " + sourceTemplateId); } } privateTemplate.setSourceTemplateId(sourceTemplateId); VMTemplateVO template = _templateDao.persist(privateTemplate); // Increment the number of templates if (template != null) { if (cmd.getDetails() != null) { _templateDetailsDao.persist(template.getId(), cmd.getDetails()); } _resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template); } if (template != null) { return template; } else { throw new CloudRuntimeException("Failed to create a template"); } }
From source file:com.cloud.configuration.ConfigurationManagerImpl.java
@Override @DB// w w w . j a v a 2 s . c o m public DataCenterVO createZone(final long userId, final String zoneName, final String dns1, final String dns2, final String internalDns1, final String internalDns2, final String guestCidr, final String domain, final Long domainId, final NetworkType zoneType, final String allocationStateStr, final String networkDomain, final boolean isSecurityGroupEnabled, final boolean isLocalStorageEnabled, final String ip6Dns1, final String ip6Dns2) { // checking the following params outside checkzoneparams method as we do // not use these params for updatezone // hence the method below is generic to check for common params if (guestCidr != null && !NetUtils.validateGuestCidr(guestCidr)) { throw new InvalidParameterValueException("Please enter a valid guest cidr"); } // Validate network domain if (networkDomain != null) { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException( "Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\""); } } checkZoneParameters(zoneName, dns1, dns2, internalDns1, internalDns2, true, domainId, allocationStateStr, ip6Dns1, ip6Dns2); final byte[] bytes = (zoneName + System.currentTimeMillis()).getBytes(); final String zoneToken = UUID.nameUUIDFromBytes(bytes).toString(); // Create the new zone in the database final DataCenterVO zoneFinal = new DataCenterVO(zoneName, null, dns1, dns2, internalDns1, internalDns2, guestCidr, domain, domainId, zoneType, zoneToken, networkDomain, isSecurityGroupEnabled, isLocalStorageEnabled, ip6Dns1, ip6Dns2); if (allocationStateStr != null && !allocationStateStr.isEmpty()) { final Grouping.AllocationState allocationState = Grouping.AllocationState.valueOf(allocationStateStr); zoneFinal.setAllocationState(allocationState); } else { // Zone will be disabled since 3.0. Admin should enable it after // physical network and providers setup. zoneFinal.setAllocationState(Grouping.AllocationState.Disabled); } return Transaction.execute(new TransactionCallback<DataCenterVO>() { @Override public DataCenterVO doInTransaction(final TransactionStatus status) { final DataCenterVO zone = _zoneDao.persist(zoneFinal); CallContext.current().putContextParameter(DataCenter.class, zone.getUuid()); if (domainId != null) { // zone is explicitly dedicated to this domain // create affinity group associated and dedicate the zone. final AffinityGroup group = createDedicatedAffinityGroup(null, domainId, null); final DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zone.getId(), null, null, null, domainId, null, group.getId()); _dedicatedDao.persist(dedicatedResource); } // Create default system networks createDefaultSystemNetworks(zone.getId()); return zone; } }); }
From source file:es.javocsoft.android.lib.toolbox.ToolBox.java
/** * Returns a unique UUID for the an android device. As with any UUIDs, * this unique ID is "very highly likely" to be unique across all Android * devices. Much more than ANDROID_ID is. * * It uses as the base the ANDROID_ID only if is not null and not the * some device manufacturers buggy ID 9774d56d682e549c for 2.2, 2.3 android * version (@see http://code.google.com/p/android/issues/detail?id=10603). * If is not available or is the buggy one, a unique UUID will be * generated using the SERIAL property of the device and if not available, * a bunch of device properties will be used to generated a unique UUID string. * * @param context//from w w w . ja v a2 s.c o m * @return a UUID that may be used, in most cases, to uniquely identify your * device for most. */ public static String device_getId(Context context) { UUID uuid = null; String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); if (androidId == null) { uuid = generateUniqueDeviceUUIDId(); } else { //Several devices by several manufacturers are affected by the ANDROID_ID bug in 2.2. //All affected devices have the same ANDROID_ID, which is 9774d56d682e549c. Which is //also the same device id reported by the emulator. if (!"9774d56d682e549c".equals(androidId)) { try { uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")); } catch (UnsupportedEncodingException e) { Log.e(TAG, "UnsupportedEncodingException (" + e.getMessage() + ").", e); } } else { uuid = generateUniqueDeviceUUIDId(); } } return uuid.toString(); }
From source file:es.javocsoft.android.lib.toolbox.ToolBox.java
/** * Generates a unique device id using the device * "serial" property if is available. If not, a bunch * of device properties will be used to get a reliable * unique string key for the device./*from w w w.ja v a 2 s.co m*/ * * If there is an error in UUID generation null is * returned. * * @return The unique UUID or nul in case of error. */ private static UUID generateUniqueDeviceUUIDId() { UUID uuid = null; try { //We generate a unique id String serial = null; if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) { serial = Build.SERIAL; uuid = UUID.nameUUIDFromBytes(serial.getBytes("utf8")); } else { //This bunch of data should be enough to "ensure" the //uniqueness. String m_szDevIDAlterbative = "35" + //To look like a valid IMEI Build.BOARD.length() % 10 + Build.BRAND.length() % 10 + Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 + Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10 + Build.USER.length() % 10; //13 digits uuid = UUID.nameUUIDFromBytes(m_szDevIDAlterbative.getBytes("utf8")); } } catch (UnsupportedEncodingException e) { Log.e(TAG, "UnsupportedEncodingException (" + e.getMessage() + ").", e); } return uuid; }