Java Code Examples for java.util.UUID#fromString()

The following examples show how to use java.util.UUID#fromString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GoogleJobStore.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the ID of the first {@link PortabilityJob} in state {@code jobState} in Datastore, or
 * null if none found.
 *
 * <p>TODO(rtannenbaum): Order by creation time so we can process jobs in a FIFO manner. Trying to
 * OrderBy.asc("created") currently fails because we don't yet have an index set up.
 */
@Override
public UUID findFirst(JobAuthorization.State jobState) {
  Query<Key> query =
      Query.newKeyQueryBuilder()
          .setKind(JOB_KIND)
          .setFilter(PropertyFilter.eq(PortabilityJob.AUTHORIZATION_STATE, jobState.name()))
          // .setOrderBy(OrderBy.asc("created"))
          .setLimit(1)
          .build();
  QueryResults<Key> results = datastore.run(query);
  if (!results.hasNext()) {
    return null;
  }
  Key key = results.next();
  return UUID.fromString(key.getName());
}
 
Example 2
Source File: SubnetWebHandlers.java    From alcor with Apache License 2.0 6 votes vote down vote up
public Mono<ServerResponse> createSubnet(ServerRequest request) {

        final Mono<SubnetWebJson> subnetObj = request.bodyToMono(SubnetWebJson.class);
        final UUID projectId = UUID.fromString(request.pathVariable("projectId"));

        final UUID generatedSubnetId = UUID.randomUUID();
        Mono<SubnetWebJson> newSubnetObj = subnetObj.map(p ->
                p.getSubnet().getId().isEmpty() || !CommonUtil.isUUID(p.getSubnet().getId()) ?
                        new SubnetWebJson(p.getSubnet(), generatedSubnetId) : new SubnetWebJson(p.getSubnet()));

        Mono<SubnetWebJson> response = serviceProxy.createSubnet(projectId, newSubnetObj);

        return response.flatMap(od -> ServerResponse.ok()
                .contentType(APPLICATION_JSON)
                .body(fromObject(od)))
                .onErrorResume(SubnetNotFoundException.class, e -> ServerResponse.notFound().build());
    }
 
Example 3
Source File: YAMLUUIDPlayerDB.java    From BungeePerms with GNU General Public License v3.0 6 votes vote down vote up
@Override
public UUID getUUID(String player)
{
    UUID ret = null;

    for (String uuid : uuidconf.getSubNodes(""))
    {
        String p = uuidconf.getString(uuid, "");
        if (p.equalsIgnoreCase(player))
        {
            ret = UUID.fromString(uuid);
        }
    }

    return ret;
}
 
Example 4
Source File: RiverAttribute.java    From TFC2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void readFromNBT(NBTTagCompound nbt, com.bioxx.jmapgen.IslandMap m) 
{
	this.id = UUID.fromString(nbt.getString("uuid"));
	river = nbt.getDouble("river");
	if(nbt.hasKey("downriver"))
		downriver = m.centers.get(nbt.getInteger("downriver"));
	if(nbt.hasKey("upriver"))
	{
		int[] nArray = nbt.getIntArray("upriver");
		upriver = new Vector<Center>();
		for(int i = 0; i < nArray.length; i++)
		{
			this.upriver.add(m.centers.get(nArray[i]));
		}
	}

	this.riverMid = new Point(nbt.getInteger("midX"), nbt.getInteger("midY"));
	this.deadRiver = nbt.getBoolean("isDead");
}
 
Example 5
Source File: DatabaseManager.java    From PlayTimeTracker with MIT License 5 votes vote down vote up
private void setupRecurrenceMap() {
    recurrenceMap = new HashMap<>();
    if (recurrenceFile.isFile()) {
        ConfigurationSection cfg = YamlConfiguration.loadConfiguration(recurrenceFile);
        for (String uuid_str : cfg.getKeys(false)) {
            ConfigurationSection sec = cfg.getConfigurationSection(uuid_str);
            UUID id = UUID.fromString(uuid_str);
            Map<String, Long> ruleMap = new HashMap<>();
            for (String ruleName : sec.getKeys(false)) {
                ruleMap.put(ruleName, sec.getLong(ruleName));
            }
            recurrenceMap.put(id, ruleMap);
        }
    }
}
 
Example 6
Source File: UUIDUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public static UUID tryGetUUID( String s ) {
    if ( s == null ) {
        return null;
    }
    if ( s.length() != 36 ) {
        return null;
    }
    // 8-4-4-4-12
    // 0-7,8,9-12,13,14-17,18,19-22,23,24-35
    if ( s.charAt( 8 ) != '-' ) {
        return null;
    }
    if ( s.charAt( 13 ) != '-' ) {
        return null;
    }
    if ( s.charAt( 18 ) != '-' ) {
        return null;
    }
    if ( s.charAt( 23 ) != '-' ) {
        return null;
    }
    UUID uuid = null;
    try {
        uuid = UUID.fromString( s );
    }
    catch ( Exception e ) {
        logger.info( "Could not convert String {} into a UUID", s, e );
    }
    return uuid;
}
 
Example 7
Source File: UUIDSerializer.java    From MCAuthLib with MIT License 5 votes vote down vote up
/**
 * Converts a String to a UUID.
 *
 * @param value String to convert.
 * @return The resulting UUID.
 */
public static UUID fromString(String value) {
    if(value == null || value.equals("")) {
        return null;
    }

    return UUID.fromString(value.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"));
}
 
Example 8
Source File: UuidSupplierTest.java    From cerberus with Apache License 2.0 5 votes vote down vote up
@Test
public void get_returns_valid_uuid() {
  final String uuid = subject.get();

  try {
    UUID.fromString(uuid);
  } catch (IllegalArgumentException iae) {
    fail("UUID generated unable to be parsed by UUID.fromString()");
  }
}
 
Example 9
Source File: SsManifestParser.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void parseStartTag(XmlPullParser parser) {
  if (TAG_PROTECTION_HEADER.equals(parser.getName())) {
    inProtectionHeader = true;
    String uuidString = parser.getAttributeValue(null, KEY_SYSTEM_ID);
    uuidString = stripCurlyBraces(uuidString);
    uuid = UUID.fromString(uuidString);
  }
}
 
Example 10
Source File: MySQLUUIDPlayerDB.java    From BungeePerms with GNU General Public License v3.0 5 votes vote down vote up
@Override
public UUID getUUID(String player)
{
    UUID ret = null;

    PreparedStatement stmt = null;
    ResultSet res = null;
    try
    {
        mysql.checkConnection();
        stmt = mysql.stmt("SELECT id, uuid FROM `" + table + "` WHERE player=? ORDER BY id ASC LIMIT 1");
        stmt.setString(1, player);
        res = mysql.returnQuery(stmt);
        if (res.last())
        {
            ret = UUID.fromString(res.getString("uuid"));
        }
    }
    catch (Exception e)
    {
        debug.log(e);
    }
    finally
    {
        Mysql.close(res);
        Mysql.close(stmt);
    }

    return ret;
}
 
Example 11
Source File: MultiBluetoothManager.java    From DataLogger with MIT License 5 votes vote down vote up
public BluetoothClient(BluetoothAdapter bluetoothAdapter, String adressMac, int index) {
            mBluetoothAdapter = bluetoothAdapter;
            mAdressMac = adressMac;
            mIndex = index;
//            mUuid = UUID.fromString("e0917680-d427-11e4-8830-" + bluetoothAdapter.getAddress().replace(":", ""));
            mUuid = UUID.fromString(mUUIDs[mIndex]);
        }
 
Example 12
Source File: AccountingApiBankTransactionTest.java    From Xero-Java with MIT License 5 votes vote down vote up
@Test
  public void createBankTransactionAttachmentByFileNameTest() throws IOException {
  	System.out.println("@Test - createBankTransactionAttachmentByFileNameTest");
      UUID bankTransactionID = UUID.fromString("297c2dc5-cc47-4afd-8ec8-74990b8761e9");
      ClassLoader classLoader = getClass().getClassLoader();
File bytes = new File(classLoader.getResource("helo-heros.jpg").getFile());
      String fileName = "sample5.jpg";

      Attachments response = accountingApi.createBankTransactionAttachmentByFileName(accessToken,xeroTenantId,bankTransactionID, fileName, bytes);
assertThat(response.getAttachments().get(0).getAttachmentID(), is(equalTo(UUID.fromString("4508a692-e52c-4ad8-a138-2f13e22bf57b"))));
assertThat(response.getAttachments().get(0).getFileName().toString(), is(equalTo("sample5.jpg")));
assertThat(response.getAttachments().get(0).getMimeType().toString(), is(equalTo("image/jpg")));
assertThat(response.getAttachments().get(0).getUrl().toString(), is(equalTo("https://api.xero.com/api.xro/2.0/BankTransactions/db54aab0-ad40-4ced-bcff-0940ba20db2c/Attachments/sample5.jpg")));
//System.out.println(response.getAttachments().get(0).toString());
  }
 
Example 13
Source File: DownloadSharedPreferenceEntry.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Check if a string is a valid GUID. GUID is RFC 4122 compliant, it should have format
 * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
 * TODO(qinmin): move this to base/.
 * @return true if the string is a valid GUID, or false otherwise.
 */
static boolean isValidGUID(String guid) {
    if (guid == null) return false;
    try {
        // Java UUID class doesn't check the length of the string. Need to convert it back to
        // string so that we can validate the length of the original string.
        UUID uuid = UUID.fromString(guid);
        String uuidString = uuid.toString();
        return guid.equalsIgnoreCase(uuidString);
    } catch (IllegalArgumentException e) {
        return false;
    }
}
 
Example 14
Source File: Data.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Loads an object from its stored data, with an unknown class.
 * The class of the object must be stored within the data.
 *
 * @param data - The data
 * @param <T> - The object type
 * @return The object loaded with given data.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> T unserialize(Data data) {
	try {
		Class<T> clazz = (Class<T>) Class.forName((String) data.get("class"));
		if (clazz.isEnum()) {
			return (T) Enum.valueOf((Class<? extends Enum>)clazz, data.get("value"));
		} else if (clazz == Vector3D.class) {
			return (T) new Vector3D(data.get("x"), data.get("y"), data.get("z"));
		} else if (clazz == Vector2D.class) {
			return (T) new Vector2D(data.get("x"), (double) data.get("y"));
		} else if (clazz == UUID.class) {
			return (T) UUID.fromString(data.get("uuid"));
		} else if (clazz == Collection.class) {
			ArrayList<T> ret = new ArrayList<>(data.size());
			LongStream.range(0, data.size() - 1).forEachOrdered(i -> ret.add(data.get(Long.toUnsignedString(i))));
			return (T) ret;
		} else if (clazz == Class.class) {
			return (T) Class.forName(data.get("name"));
		} else if (Storable.class.isAssignableFrom(clazz)) {
			return (T) unserialize((Class<? extends Storable>) clazz, data);
		} else {
			throw new IllegalArgumentException(data.className);
		}
	} catch (Exception e) {
		throw new DataException(e);
	}
}
 
Example 15
Source File: EdgeValue.java    From datawave with Apache License 2.0 5 votes vote down vote up
public static EdgeData.EdgeValue.UUID convertUuidStringToUuidObj(String uuidString) throws IllegalArgumentException {
    UUID uuidObj = UUID.fromString(uuidString);
    EdgeData.EdgeValue.UUID.Builder uuidBuilder = EdgeData.EdgeValue.UUID.newBuilder();
    uuidBuilder.setLeastSignificantBits(uuidObj.getLeastSignificantBits());
    uuidBuilder.setMostSignificantBits(uuidObj.getMostSignificantBits());
    return uuidBuilder.build();
}
 
Example 16
Source File: HypixelAPIManager.java    From The-5zig-Mod with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Loads the API key from file.
 *
 * @return the API key.
 * @throws HypixelAPIMissingKeyException if the API key file does not exist or is corrupted.
 */
private UUID loadKey() throws HypixelAPIMissingKeyException {
	File keyFile = new File(The5zigMod.getModDirectory(), "servers/hypixel/api_" + The5zigMod.getDataManager().getUniqueId() + ".key");
	if (!keyFile.exists())
		throw new HypixelAPIMissingKeyException();

	try {
		return UUID.fromString(IOUtils.toString(keyFile.toURI()));
	} catch (Exception e) {
		throw new HypixelAPIMissingKeyException(e);
	}
}
 
Example 17
Source File: TimeUUIDType.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer fromStringCQL2(String source) throws MarshalException
{
    // Return an empty ByteBuffer for an empty string.
    if (source.isEmpty())
        return ByteBufferUtil.EMPTY_BYTE_BUFFER;

    ByteBuffer idBytes = null;

    // ffffffff-ffff-ffff-ffff-ffffffffff
    if (regexPattern.matcher(source).matches())
    {
        UUID uuid = null;
        try
        {
            uuid = UUID.fromString(source);
            idBytes = decompose(uuid);
        }
        catch (IllegalArgumentException e)
        {
            throw new MarshalException(String.format("unable to make UUID from '%s'", source), e);
        }

        if (uuid.version() != 1)
            throw new MarshalException("TimeUUID supports only version 1 UUIDs");
    }
    else
    {
        idBytes = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes(TimestampSerializer.dateStringToTimestamp(source)));
    }

    return idBytes;
}
 
Example 18
Source File: DetectorMappingRepositoryImplTest.java    From adaptive-alerting with Apache License 2.0 4 votes vote down vote up
private ConsumerDetectorMapping attachConsumerToDetector(String detectorUuid) {
    return new ConsumerDetectorMapping("cid", UUID.fromString(detectorUuid));
}
 
Example 19
Source File: TestRegionReplicaReplicationEndpoint.java    From hbase with Apache License 2.0 4 votes vote down vote up
private void testRegionReplicaReplicationIgnores(boolean dropTable, boolean disableReplication)
    throws Exception {
  // tests having edits from a disabled or dropped table is handled correctly by skipping those
  // entries and further edits after the edits from dropped/disabled table can be replicated
  // without problems.
  final TableName tableName = TableName.valueOf(
    name.getMethodName() + "_drop_" + dropTable + "_disabledReplication_" + disableReplication);
  HTableDescriptor htd = HTU.createTableDescriptor(tableName);
  int regionReplication = 3;
  htd.setRegionReplication(regionReplication);
  HTU.deleteTableIfAny(tableName);

  HTU.getAdmin().createTable(htd);
  TableName toBeDisabledTable = TableName.valueOf(
    dropTable ? "droppedTable" : (disableReplication ? "disableReplication" : "disabledTable"));
  HTU.deleteTableIfAny(toBeDisabledTable);
  htd = HTU.createTableDescriptor(TableName.valueOf(toBeDisabledTable.toString()),
    HColumnDescriptor.DEFAULT_MIN_VERSIONS, 3, HConstants.FOREVER,
    HColumnDescriptor.DEFAULT_KEEP_DELETED);
  htd.setRegionReplication(regionReplication);
  HTU.getAdmin().createTable(htd);

  // both tables are created, now pause replication
  HTU.getAdmin().disableReplicationPeer(ServerRegionReplicaUtil.getReplicationPeerId());

  // now that the replication is disabled, write to the table to be dropped, then drop the table.

  Connection connection = ConnectionFactory.createConnection(HTU.getConfiguration());
  Table table = connection.getTable(tableName);
  Table tableToBeDisabled = connection.getTable(toBeDisabledTable);

  HTU.loadNumericRows(tableToBeDisabled, HBaseTestingUtility.fam1, 6000, 7000);

  RegionLocator rl = connection.getRegionLocator(toBeDisabledTable);
  HRegionLocation hrl = rl.getRegionLocation(HConstants.EMPTY_BYTE_ARRAY);
  byte[] encodedRegionName = hrl.getRegion().getEncodedNameAsBytes();

  Cell cell = CellBuilderFactory.create(CellBuilderType.DEEP_COPY).setRow(Bytes.toBytes("A"))
      .setFamily(HTU.fam1).setValue(Bytes.toBytes("VAL")).setType(Type.Put).build();
  Entry entry = new Entry(
    new WALKeyImpl(encodedRegionName, toBeDisabledTable, 1),
      new WALEdit()
          .add(cell));
  HTU.getAdmin().disableTable(toBeDisabledTable); // disable the table
  if (dropTable) {
    HTU.getAdmin().deleteTable(toBeDisabledTable);
  } else if (disableReplication) {
    htd.setRegionReplication(regionReplication - 2);
    HTU.getAdmin().modifyTable(htd);
    HTU.getAdmin().enableTable(toBeDisabledTable);
  }

  HRegionServer rs = HTU.getMiniHBaseCluster().getRegionServer(0);
  MetricsSource metrics = mock(MetricsSource.class);
  ReplicationEndpoint.Context ctx =
    new ReplicationEndpoint.Context(rs, HTU.getConfiguration(), HTU.getConfiguration(),
      HTU.getTestFileSystem(), ServerRegionReplicaUtil.getReplicationPeerId(),
      UUID.fromString(rs.getClusterId()), rs.getReplicationSourceService().getReplicationPeers()
        .getPeer(ServerRegionReplicaUtil.getReplicationPeerId()),
      metrics, rs.getTableDescriptors(), rs);
  RegionReplicaReplicationEndpoint rrpe = new RegionReplicaReplicationEndpoint();
  rrpe.init(ctx);
  rrpe.start();
  ReplicationEndpoint.ReplicateContext repCtx = new ReplicationEndpoint.ReplicateContext();
  repCtx.setEntries(Lists.newArrayList(entry, entry));
  assertTrue(rrpe.replicate(repCtx));
  verify(metrics, times(1)).incrLogEditsFiltered(eq(2L));
  rrpe.stop();
  if (disableReplication) {
    // enable replication again so that we can verify replication
    HTU.getAdmin().disableTable(toBeDisabledTable); // disable the table
    htd.setRegionReplication(regionReplication);
    HTU.getAdmin().modifyTable(htd);
    HTU.getAdmin().enableTable(toBeDisabledTable);
  }

  try {
    // load some data to the to-be-dropped table
    // load the data to the table
    HTU.loadNumericRows(table, HBaseTestingUtility.fam1, 0, 1000);

    // now enable the replication
    HTU.getAdmin().enableReplicationPeer(ServerRegionReplicaUtil.getReplicationPeerId());

    verifyReplication(tableName, regionReplication, 0, 1000);
  } finally {
    table.close();
    rl.close();
    tableToBeDisabled.close();
    HTU.deleteTableIfAny(toBeDisabledTable);
    connection.close();
  }
}
 
Example 20
Source File: Generators.java    From ts-reaktive with MIT License 4 votes vote down vote up
private static UUID workerId(int index) {
    UUID workerIdBase = UUID.fromString("35c2ae01-b26e-49ad-8fd1-000000000000");
    return new UUID(workerIdBase.getMostSignificantBits(), workerIdBase.getLeastSignificantBits() + index);
}