How Convert Microsoft GUID to JAVA UUID? - java

I need to communicate a Guid that was generated in .NET to a Java application.
This is my GUID
ce095552-b466-4d03-ac41-430ec9286806
and I want to set it to UUID variable !
UUID.nameUUIDFromBytes(stringUUID.getBytes())
UUID.fromString(stringUUID)
I am getting error
Caused by: java.lang.NumberFormatException: Invalid long: ""ce095552"
how can I cast GUID to UUID?

When you get some Microsoft objectGUIDs , Active Directory objectGUID of the group object for example, you need to get the binary and then convert it to hexadecimal after then you need generate a MS GUID (look at order byte sequence inside convertToDashedString function).
The byte order comparing UUID and GUID is different: try convert it using online converters like: robobunny converter
Now I'm storing and working with ms guid
public static String convertMSGUIDToHexFormat(String guid){
guid = guid.replaceAll("-", "");
guid = guid.replaceAll("(.{8})(.{4})(.{4})(.{4})(.{12})", "$1-$2-$3-$4-$5").replaceAll("(.{2})(.{2})(.{2})(.{2}).(.{2})(.{2}).(.{2})(.{2})(.{18})", "$4$3$2$1-$6$5-$8$7$9");
guid = guid.replaceAll("-", "");
return guid;
}
public static String convertHexToMSGUIDFormat(String hex){
return hex.replaceAll("(.{8})(.{4})(.{4})(.{4})(.{12})", "$1-$2-$3-$4-$5").replaceAll("(.{2})(.{2})(.{2})(.{2}).(.{2})(.{2}).(.{2})(.{2})(.{18})", "$4$3$2$1-$6$5-$8$7$9");
}
When I know a better way, then I change that supposed quick fix

UUID.fromString() works fine:
String guid = "ce095552-b466-4d03-ac41-430ec9286806";
UUID uuid = UUID.fromString(guid);
System.out.println(uuid);

Invalid long: ""ce095552"
Looks like the GUID you are passing to UUID.fromString still includes quotes ("). Make sure the GUID string does not include any additional characters and it should work.

String guid = "41e72bd6-d38f-4f78-855f-160562262a54";
UUID uuid = UUID.fromString(guid);
ReadValueId readValueId = new ReadValueId(
new NodeId(2, uuid),
AttributeId.Value.uid(), null, QualifiedName.NULL_VALUE);

Related

java.lang.NumberFormatException when trying to fetch a line in a Cassandra table

I use the Datastax driver to fetch a line in a Cassandra table :
MappingManager manager = new MappingManager(session);
Mapper<CassandraEntity> mapper = manager.mapper(CassandraEntity.class);
UUID id = UUID.fromString(uuid);
CassandraEntity cassandraEntity = mapper.get(id);
When the uuid exists in the table then everything works fine. But when the uuid does not exist I have this error :
ERROR [2017-01-27 14:27:24,030] io.dropwizard.jersey.errors.LoggingExceptionMapper: Error handling a request: 48a3bf442525acf8
! java.lang.NumberFormatException: For input string: "68c34e83db3o"
! at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.7.0_75]
! at java.lang.Long.parseLong(Long.java:441) ~[na:1.7.0_75]
! at java.lang.Long.valueOf(Long.java:513) ~[na:1.7.0_75]
! at java.lang.Long.decode(Long.java:665) ~[na:1.7.0_75]
! at java.util.UUID.fromString(UUID.java:206) ~[na:1.7.0_75]
How can I nicely manage this error ?
68c34e83db3o is not a valid UUID so UUID.fromString is throwing this exception, the javadocs state:
Throws:
IllegalArgumentException - If name does not conform to the string ? representation as described in toString()
NumberFormatException is an instance of IllegalArgumentExcepiton.
How are you forming uuid before passing it into fromString? It's possible you might need to do some formatting/santization before calling fromString. 68c34e83db3o almost looks like a hex string (except for that last o).
c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3o is not a valid UUID. The sixteen octets of a UUID are represented as 32 lowercase hexadecimal (base 16) digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens). So :
c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3a is a valid UUID
c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3b is a valid UUID
c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3c is a valid UUID
c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3d is a valid UUID
c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3e is a valid UUID
c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3f is a valid UUID
But c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3g is not a valid UUID nor c37d661d-7e61-49ea-96a5-68c34e83‌​‌​‌​db3o
To quickly check if a UUID is valid you can use this Fiddle : https://jsfiddle.net/mshaffer/6e2Ljh97
As Andy Tolbert said, when the UUID is not valid then the UUID.fromString method throws an IllegalArgumentException. To handle this exception, use the solution given at How to judge a string is UUID type? :
try{
UUID uuid = UUID.fromString(someUUID);
//do something
} catch (IllegalArgumentException exception){
//handle the case where string is not valid UUID
}

reading two variable values after decrypting

I am working on "Forgot Password". I am trying to create a reset token with email + current_time. email is user login whilst code will check if time >= 5 minutes then this link will not work. Here is my code:
// preparing token email + time
Date now = new Date();
String prepareToken = "?email="+email+"&tokenTime="+now.getTime();
// encrypt prepareToken value
Encryptor enc = new Encryptor();
resetToken = enc.encrypt(resetToken);
The token will be sent as for example as http://domainname.com/ForgotPassword?resetToken=adj23498ljj238809802340823
Problem:
When user click it then I got as request parameter and obviously decrypt this parameter but how can I get email in one String + time as another String
Please advise
If your issue is simply parsing the decoded String to get some sort of Map of your parameters, I'd suggest you to read Parse a URI String into Name-Value Collection .
Hope it helps.
EDIT :
Assuming you have the splitQuery(URL url) method from the previous link and that you successfully decoded the token :
public String getEmailFromToken(String decodedToken) {
// if you decoded your token it will looks like the prepareToken String
String stubUrl = "http://localhost"+decodedToken;
Map<String,String> map = splitQuery(new URL(stubUrl));
return map.get("timeToken");
}
I created a properly formed URL to respect the URL syntax.
With little tweak, you should be able to implement splitQuery for a String. I hope you can manage that.

How to save a UUID as binary(16) in java

I have a table TestTable with columns ID as binary(16) and name as varchar(50)
I've been trying to store an ordered UUID as PK like in this article Store UUID in an optimized way
I see the UUID is saved in database as HEX (blob)
So I want to save this ID from java but I am getting this error
Data truncation: Data too long for column 'ID' at row 1
I am currently using the library sql2o to interact with mysql
So basically this is my code
String suuid = UUID.randomUUID().toString();
String partial_id = suuid.substring(14,18) + suuid.substring(9, 13) + suuid.substring(0, 8) + suuid.substring(19, 23) + suuid.substring(24)
String final_id = String.format("%040x", new BigInteger(1, partial_id.getBytes()));
con.createQuery("INSERT INTO TestTable(ID, Name) VALUES(:id, :name)")
.addParameter("id", final_id)
.addParameter("name", "test1").executeUpdate();
The partial id should be something like this 11d8eebc58e0a7d796690800200c9a66
I tried this statement in mysql without issue
insert into testtable(id, name) values(UNHEX(CONCAT(SUBSTR(uuid(), 15, 4),SUBSTR(uuid(), 10, 4),SUBSTR(uuid(), 1, 8),SUBSTR(uuid(), 20, 4),SUBSTR(uuid(), 25))), 'Test2');
But I got the same error when I remove the unhex function. So how can I send the correct ID from Java to mysql?
UPDATE
I solved my problem inspired on the answer of David Ehrmann. But in my case I used the HexUtils from tomcat to transform my sorted UUID string into bytes[]:
byte[] final_id = HexUtils.fromHexString(partial_id);
Try storing it as bytes:
UUID uuid = UUID.randomUUID();
byte[] uuidBytes = new byte[16];
ByteBuffer.wrap(uuidBytes)
.order(ByteOrder.BIG_ENDIAN)
.putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits());
con.createQuery("INSERT INTO TestTable(ID, Name) VALUES(:id, :name)")
.addParameter("id", uuidBytes)
.addParameter("name", "test1").executeUpdate();
A bit of an explanation: your table is using BINARY(16), so serializing UUID as its raw bytes is a really straightforward approach. UUIDs are essentially 128-bit ints with a few reserved bits, so this code writes it out as a big-endian 128-bit int. The ByteBuffer is just an easy way to turn two longs into a byte array.
Now in practice, all the conversion effort and headaches won't be worth the 20 bytes you save per row.

Unable to get UniqueIdentifier from X500Principal of X509Certificate

I wanted to get the unique identifier of a X509Certificate using Java.
I tried to get the value from using the below code:-
java.security.cert.X509Certificate certificate=// certificate object
certificate.getSubjectX500Principal().getName();
But i am unable to get the unique identifier value alone.This is the value i am getting:-
2.5.4.45=#0309000000db000000a01a,OU=06
I wanted to get the value alone for "2.5.4.45".
I also tried to get the value using the below code:-
String dn2 = certificate.getSubjectX500Principal().getName();
LdapName ldapDN;
ldapDN = new LdapName(dn2);
for(Rdn rdn: ldapDN.getRdns()) {
System.out.println(rdn.getType() + " -> " + rdn.getValue());
if(rdn.getType().equalsIgnoreCase("2.5.4.45")){
System.out.println(rdn.getValue());
}
I am getting an object as the value for unique identifier. I am not able to parse the Object, get the value for this.
Update ::
I am still not able to figure out a way to get the UniqueIdentifier identifer.Any help is appreciated.
You need provide set of known OIDs. Then you will get a human readable value of DN String. Value of known OIDs will be readable when you define OID. For example:
Map<String, String> knownOids = new HashMap<String, String>();
knownOids.put("2.5.4.45", "uniqueIdentifier");
String humanReadableDN = certToken.getCertificate().getSubjectX500Principal().getName(X500Principal.RFC2253, knownOids);
Example OID repository you can find here: http://oid-info.com/get/2.5.4.45
For Example, this:
CN=Krzysiek,1.2.840.113549.1.9.1=#160f3334353334354064666766642e706c
Will be translated to this:
commonName=Krzysiek,emailAddress=345345#dfgfd.pl
When you provide a set with:
knownOids.put("1.2.840.113549.1.9.1", "emailAddress");

Hazelcast not able to read data into my own class object using IMap.get, where data inserted using Memcached text protocol

I am inserting record into Hazelcast from C Application using Memcached Client Library API's, where record is as follows:
typedef struct _activeClient
{
char ID[25];
int IP;
char aMethod[16];
}activeClient;
Now I am trying reading same record using Hazelcast Java Native API's. Here is my Java program.
IMap < String, MemcacheEntry > mapInst = client.getMap("hz_memcache_ABC_MAP");
System.out.println("Map Size:" + mapInst.size());
String key = new String("70826892122991");
MemcacheEntry tmpValRec = pvrMapIst.get(key);
System.out.println("Key:" + key + "ID:" + tmpValRec.getValue());
Here tmpValRec.getValue() printing record content in single String format. But, I want to retrive each member value from tmpValRec to my own java class object. Here is the class
class ActiveClients
{
String ueID;
int Ip;
String aMethod;
ActiveClients()
{
ueID = "";
Ip = 0;
aMethod = "";
}
}
Pointing me to an example would be great help.
I guess the only option is to parse the string to deserialize your object. I know this is a pain, but I don't see a better alternative. Unless of course you store a blob as a value in memcached where the blob is the serialized content of the class.

Categories