Cassandra convert UUID to string and back - cassandra

If i use UUID1 for my column names and then retrieve them with php how can i convert that UUID to readable string so i could insert that string to the HTML and then later on use it to select that same column by converting that string back to UUID? Is that even possible?
I could go with UTF8 or something else but i want to avoid collisions and get ordered wide rows, and i really need to store those column names to the HTML, i can't see any other way to do it.
I'm using phpcassa.

You can cast UUID objects to strings to get a nice printable version. That same string can be used with UUID::import() to create an identical UUID object again:
use phpcassa\UUID;
$uuid = UUID::uuid1();
$pretty_uuid = (string)$uuid;
echo("Printable version: " . $pretty_uuid . "\n");
$uuid_copy = UUID::import($pretty_uuid);
assert ($uuid == $uuid_copy);

Assuming you are getting the UUID as byte[], you can use something like this:
public Object convertFromNoSqlImpl(byte[] value) {
byte[] timeArray = new byte[8];
byte[] clockSeqAndNodeArray=new byte[8];
System.arraycopy(value,0,timeArray,0,8);
System.arraycopy(value,8,clockSeqAndNodeArray,0,8);
long time = StandardConverters.convertFromBytes(Long.class, timeArray);
long clockSeqAndNode = StandardConverters.convertFromBytes(Long.class, clockSeqAndNodeArray);
UUID ud = new UUID(time,clockSeqAndNode);
return ud;
}

Related

How to get first String based on whitespace out of a full String using java8?

Let's Example I have String s = "Rahul Kumar" I need to have Rahul as a output using java8
Actual Requirement, I do have a list of Trip Object, I want to set driverName property as only first name to each Trip Object and return that list?
System.out.println( someStringValue.subSequence(0, someStringValue.indexOf(' ')));
I'm getting trouble to incorporate this code into the listOfTrip. If I'm doing like this,
List<CharSequence> list = listOfTrips.stream().map(e -> e.getDriverName().subSequence(0, someStringValue.indexOf(' '))).collect(Collectors.toList()); System.out.println(list);
Here, With this, The return type is wrong and it is not fetching only first name out of full name.
Below will give you the proper result:
List<CharSequence> list2 = listOfTrips.stream()
.map(m->m.getDriverName().substring(0,m.getDriverName().indexOf(' ')))
.collect(Collectors.toList());
Please try this also once:
String s = "Rahul Kumar";
Optional<String> beforeWhiteSpace = Pattern.compile(" ").splitAsStream(s).collect(Collectors.toList()).stream().findFirst();

How to put Java object in Couchbase's JsonObject in one operation

With Couchbase's jsonObject we can create object with certain fields:
import com.couchbase.client.java.document.json.JsonObject
...
JsonObject content = JsonObject.create().put("some", "value");
The put function has several String & value options such as double, int, String etc, as can be seen here.
I was looking for a way to put a whole object in it. Something like:
Cat cat = new Cat(.....)
JsonObject content = JsonObject.create().put(cat);
Is there a way to do it and not to iterate over all of Cat's fields?
So here is how it can be done:
Cat cat = new Cat(...);
String asJson = gson.toJson(cat);
JsonObject.fromJson(asJson);

Map to hold multiple sets of key and values

I have a map1 which holds the information as
[40256942,6] [60246792,5]
Now that I want to prepare a map2 that holds information such as
itemNo, 40256942
qty, 6
itemNo, 60246792
qty, 5
to prepare final information as json
“partialArticlesInfo”: [{itemNo:”40256942”, availQty:”6”}, {itemNo:”60246792”, availQty:”5”}]
I am trying to iterate map1 to retrieve values and set that against the key. But I am getting only one entry which is last one. Is there any way , I get the new map with entries such as mentioned above
Map<String, String> partialArticlesInfo = new HashMap<String,String>();
Map<String, String> partialArticlesTempMap = null;
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet())
{
partialArticlesTempMap = new HashMap<String,String>();
partialArticlesTempMap.put("itemNo",entry.getKey());
partialArticlesTempMap.put("availQty",entry.getValue());
partialArticlesInfo.putAll(partialArticlesTempMap);
}
In Java (I'm assuming you're using Java, in the future it would be helpful to specify that) and every other language I know of, a map holds mappings between keys and values. Only one mapping is allowed per key. In your "map2", the keys are "itemNo" and "availQty". So what is happening is that your for loop sets the values for the first entry, and then is overwriting them with the data from the second entry, which is why that is the only one you see. Look at Java - Map and Map - Java 8 for more info.
I don't understand why you are trying to put the data into a map, you could just put it straight into JSON with something like this:
JSONArray partialArticlesInfo = new JSONArray();
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet()) {
JSONObject stockEntry = new JSONObject();
stockEntry.put("itemNo", entry.getKey());
stockEntry.put("availQty", entry.getValue());
partialArticlesInfo.put(stockEntry);
}
JSONObject root = new JSONObject();
root.put("partialArticlesInfo",partialArticlesInfo);
This will take "map1" (partialStockArticlesQtyMap in your code) and create a JSON object exactly like your example - no need to have map2 as an intermediate step. It loops over each entry in map1, creates a JSON object representing it and adds it to a JSON array, which is finally added to a root JSON object as "partialArticlesInfo".
The exact code may be slightly different depending on which JSON library you are using - check the docs for the specifics.
I agree with Brendan. Another solution would be otherwise to store in the Set or List objects like the following.
class Item {
Long itemNo;
int quantity;
public int hashCode() {
Long.hashCode(itemNo) + Integer.hashCode(quantity);
}
public int equals(Object other) {
other instanceOf Item && other.itemNo == this.itemNo && other.quantity = this.quantity;
}
}
}
then you can use the JsonArray method described by him to get the Json string in output
This means that adding new variables to the object won't require any more effort to generate the Json

How are AMF3 string tables built?

I am working on AMF3 format decoding. I have used inline objects and variables, however I am having problem with the String reference. Can anyone tell how String reference table is built?
Currently, I have:
var object:Object = new Object();
object.s1 = "abc";
object.s2 = object.s1;
object.s0 = "111";
byteBuffer.writeObject(object);
then I write this to a byteBuffer and finally to a file. I am wondering how String references are built?
Flex builds a table for string references. As soon as Flex encounters a string in an object, it does the following:
If the string is new:
Add the string to the table and increase the reference number.
Otherwise
add a reference to the string.

UUID Cassandra

I am new to Cassandra. I am trying to insert some values to the columnfamily. The definition of columnfamily in the config file is as follows.
<ColumnFamily Name="CommandQueue"
ColumnType="Super"
CompareWith="TimeUUIDType"
CompareSubcolumnsWith="UTF8Type"/>
When ever I try to insert values to I always get "InvalidRequestException(why: UUIDs must be exactly 16 bytes)".
I am using batch_mutate() to insert column.
How can I insert values to the column family.
"We have an API for that" :-)
https://github.com/rantav/hector/blob/master/core/src/main/java/me/prettyprint/cassandra/utils/TimeUUIDUtils.java
This class makes it easy to build type1 UUIDs and extract the timestamps as needed. See the related test case for examples.
Hector is MIT licensed, so if you are set on doing your own thing, feel free to use whatever helps.
Below is a code snippet (from Nick Berardi's Coder Journal)
public static Guid GenerateTimeBasedGuid(DateTime dateTime)
{
long ticks = dateTime.Ticks - GregorianCalendarStart.Ticks;
byte[] guid = new byte[ByteArraySize];
byte[] clockSequenceBytes = BitConverter.GetBytes(Convert.ToInt16(Environment.TickCount
% Int16.MaxValue));
byte[] timestamp = BitConverter.GetBytes(ticks);
// copy node
Array.Copy(Node, 0, guid, NodeByte, Node.Length);
// copy clock sequence
Array.Copy(clockSequenceBytes, 0, guid, GuidClockSequenceByte,clockSequenceBytes.Length);
// copy timestamp
Array.Copy(timestamp, 0, guid, 0, timestamp.Length);
// set the variant
guid[VariantByte] &= (byte)VariantByteMask;
guid[VariantByte] |= (byte)VariantByteShift;
// set the version
guid[VersionByte] &= (byte)VersionByteMask;
guid[VersionByte] |= (byte)((int)GuidVersion.TimeBased << VersionByteShift);
return new Guid(guid);
}
I am just continuing where "Schildmejir" has stopped. This how you can actually use the generated GUID in inserting values to columnfamilies.
Mutation foobar = new Mutation()
{
Column_or_supercolumn = new ColumnOrSuperColumn()
{ Super_column = new SuperColumn()
{ Name = GuidGenerator.GenerateTimeBasedGuid(DateTime.Now).ToByteArray(),
Columns = listOfSomeColumns
}
}
};
List<Column> foobarlist = new List<Column>();
listOfChannelIds.Add(new Column() { Name = utf8Encoding.GetBytes("somename"), Value = utf8Encoding.GetBytes(somestring), Timestamp = timeStamp });
You can use the generated GUID either in SupercolumnName or columnName depending on the requirement.
Cassandra expects UUIDs to conform to RFC 4122, so you'll need to either generate compliant values yourself or use an existing library for the language of your choice (most languages have free UUID generation libraries readily available).

Resources