Bouncy castle - how to rebuild Public key from EdDSA - eddsa

I have Edward curve key parameters - x, d and curve. How can I rebuild PublicKey/Private keys using bouncy castle?

If x is your public key, d is your private key and curve is Curve25519 or Curve448, then you can simply do the following:
final BigInteger x = ...; // here is your public key as an integer
final BigInteger d = ...; // here is your private key as an integer
final Ed25519PrivateKeyParameters reconstructedPrivateKey = new Ed25519PrivateKeyParameters(d.toByteArray(), 0);
final Ed25519PublicKeyParameters reconstructedPublicKey = new Ed25519PublicKeyParameters(x.toByteArray(), 0);
This is an example of getting Ed25519 public/private keys, for X25519, Ed448, or X448 you just need to use their respective classes instead.

Related

Is it possible to get top 10 from ktable\kstream?

I have a topic with a String key which is a signal type and Signal value which is a class like this
public clas Signal {
public final int deviceId;
public final int value;
...
}
Each device can send signal values which raise or fall with time without a pattern.
Is it possible to get top 10 devices with max signal value at all period of time by each type (key of the topic) as a KTable<String,Signal>? Would it helped if all signal values were raising?
Topic structure can be changed if needed.
It is possible to do with Kafka Streams for the case when values are always raising, for example. It is needed to create own Top10 aggregate, which stores top 10 and updates it on add call:
final var builder = new StreamsBuilder();
final var topTable = builder
.table(
SignalChange.TOPIC_NAME,
Consumed.with(Serdes.String(), new SignalChange.Serde())
).toStream()
.groupByKey()
.aggregate(
() -> new Top10(),
(k, v, top10) -> top10.add(v),
Materialized.with(Serdes.String(), new Top10.Serde())
);
topTable can then be joined with any stream requesting for the top.

Query regarding merging values of a Map to the first key of the Map

I've a hashmap with few key value pairs.
My requirement is to iterate over the all the key and value pairs but merge all the value to the first key of the hashset.
For example,
Map<String,Integer> resultMap = new HashMap();
Map<String,Integer> map = new HashMap();
map.put("abc",1);
map.put("def",2);
map.put("efg",3);
map.put("uvw",4);
map.put("xyz",5);
I want to do something similar to this:
map.foreach((k,v)->resultMap.merge(k,v,(v1,v2)->v1+v2)
the resultant map will have only one key i.e. "abc" and value as (1+2+3+4+5)=15
How can I do this efficiently using java8?
You can do like this:
String firstKey = "";
for (Map.Entry<String,Integer> entry:map.entrySet()) {
if (resultMap.isEmpty()) firstKey = entry.getKey();
resultMap.merge(firstKey, entry.getValue(), Integer::sum);
}
stream version:
resultMap = map.entrySet().stream()
.collect(HashMap::new, (m, e) ->
{
if (m.isEmpty()) m.put(e.getKey(), e.getValue());
else m.merge(m.entrySet().stream()
.findFirst().get().getKey(),e.getValue(),Integer::sum);
}
, HashMap::putAll);
You can sum all the values of the map first and then add it resultMap with first key.
int sum = map.values().stream().reduce(0, Integer::sum);
Map.Entry<String,Integer> entry = map.entrySet().iterator().next();
String key = entry.getKey();
resultMap.put(key,sum);
Using Merge function, first sum all the values with "randomKey" not present in the original Map. Then replace random key with original map's first key
map.forEach((k,v)->resultMap.merge("randomKey",v,Integer::sum));
Map.Entry<String,Integer> entry = map.entrySet().iterator().next();
Object obj = resultMap.remove("randomKey");
resultMap.put(entry.getKey(), (Integer) obj);

Java 8 GroupBy and transform result to a list

Hello I have to group by multiple fields and make a summary by one of these files, thereafter I have to work with this result and make some more transformations my problem is that I'm getting a complex structure after the grouping and it's not easy to work with this items. This is my code:
Map<String, Map<String, Map<LocalDateTime, Map<String, Double>>>> processed = null;
processed = itemsToProcess
.stream()
.collect(groupingBy(entity::getId,
groupingBy(entity::getType,
groupingBy(entity::getCreateDate,
groupingBy(entity::getCode,
summingDouble(entity::getPay))))));
The objective of this grouping is the summary of the pays but thereafter I I have to do some transformations with this processed structure, my doubt if is there is a way to transform this in a simple list in order to make more easy this task?
My input is basically a list of:
List<Person> itemsToProcess= new ArrayList<>();
#JsonInclude
public class Person extends Entity<Person > {
private static final long serialVersionUID = 1L;
/* File line content */
private String id;
private String type;
private LocalDateTime createDate;
private String code;
private double pay;
private String city
private String company
}
The output that I'm looking for is the summary of the pay field grouped by {id,type,createDate,pay}
example if I have the next values
Id type createdDAte Code pay more fields....
1 0 today BC 500
1 0 today BC 600
2 0 today BC 600
2 0 today BC 300
3 0 today BC 300
The result must be:
Id type createdDAte Code pay more fields....
1 0 today BC 1100
2 0 today BC 900
3 0 today BC 300
You can use Collectors.toMap to Map by that four properties and merging the same group person objects and creating a new one using the constructor.
List<Person> processed =
new ArrayList<>(
itemsToProcess
.stream()
.collect(Collectors.toMap(
i -> Arrays.asList(i.getId(), i.getType(), i.getCreateDate(), i.getCode()),
i -> i,
(a, b) -> new Person(a.getId(), a.getType(), a.getCreateDate(), a.getCode(),
a.getPay() + b.getPay())))
.values());
Output:
Person [id=2, type=0, createDate=2020-08-18T12:26:15.616034800, code=BC, pay=900.0]
Person [id=3, type=0, createDate=2020-08-18T12:26:15.616034800, code=BC, pay=300.0]
Person [id=1, type=0, createDate=2020-08-18T12:26:15.616034800, code=BC, pay=1100.0]
Demo here
Quick way is to group by a map of the key fields:
groupingBy(e -> Map.<String, Object>of(
"id", e.getId(),
"type", e.getType(),
"createDate", e.getCreateDate(),
"code", e.getCode(),
"pay", e.getPay()
), identity())
Map's equals() method works as you would hope it does.

Getting key value from key of hazelcast IMap

I put my object to hazelcast map using spring annotation:
#Cacheable(value = "cacheName", key = "{ #someId1,#someId2}")
public String generateValue(Long someId1, Long someId2)
I would like to invalidate object from cache based on condition placed on key of the Imap. I found that key is a ArrayList with size equal 2. That is expected result.
Set set = cache.keySet(); // this returns Set<ArrayList<Long>>
I try to set condition on key:
EntryObject e = new PredicateBuilder().getEntryObject();
Predicate predicateKey = e.key().get("__key#get(0)").equal(someId1).and(e.get("__key#get(1)").equal(someId2));
But invoking this predicate end up in failure:
Set<Long> idKeysToInvalidate = cache.keySet(predicateKey);
com.hazelcast.query.QueryException: java.lang.IllegalArgumentException: There is no suitable accessor for '__key#get(0)' on class 'class java.util.ArrayList'
at com.hazelcast.query.impl.getters.ReflectionHelper.createGetter(ReflectionHelper.java:176)
Did anyone encounter the same issue?
I haven't done it myself, at least on a key, but can you try __key#[0] otherwise see here: http://docs.hazelcast.org/docs/3.8/manual/html-single/index.html#querying-in-collections-and-arrays
I solved issue as below:
EntryObject e = new PredicateBuilder().getEntryObject();
List<Long> input = Arrays.asList(someId1, someId2);
Predicate predicateKey = e.key().get("hashCode").equal(input.hashCode());
Set<List> idKeysToInvalidate = cache.keySet(predicateKey);

Item-by-item list comparison, updating each item with its result (no third list)

The solutions I have found so far in my research on comparing lists of objects have usually generated a new list of objects, say of those items existing in one list, but not in the other. In my case, I want to compare two lists to discover the items whose key exists in one list and not the other (comparing both ways), and for those keys found in both lists, checking whether the value is the same or different.
The object being compared has multiple properites that constitute the key, plus a property that constitutes the value, and finally, an enum property that describes the result of the comparison, e.g., {Equal, NotEqual, NoMatch, NotYetCompared}. So my object might look like:
class MyObject
{
//Key combination
string columnA;
string columnB;
decimal columnC;
//The Value
decimal columnD;
//Enum for comparison, used for styling the item (value hidden from UI)
//Alternatively...this could be a string type, holding the enum.ToString()
MyComparisonEnum result;
}
These objects are collected into two ObservableCollection<MyObject> to be compared. When bound to the UI, the grid rows are being styled based on the caomparison result enum, so the user can easily see what keys are in the new dataset but not in the old, vice-versa, along with those keys in both datasets with a different value. Both lists are presented in the UI in data grids, with the rows styled based on the comparison result.
Would LINQ be suitable as a tool to solve this efficiently, or should I use loops to scan the lists and break out when the key is found, etc (a solution like this comes naturally to be from my procedural programming background)... or some other method?
Thank you!
You can use Except and Intersect:
var list1 = new List<MyObject>();
var list2 = new List<MyObject>();
// initialization code
var notIn2 = list1.Except(list2);
var notIn1 = list2.Except(list1);
var both = list1.Intersect(list2);
To find objects with different values (ColumnD) you can use this (quite efficient) Linq query:
var diffValue = from o1 in list1
join o2 in list2
on new { o1.columnA, o1.columnB, o1.columnC } equals new { o2.columnA, o2.columnB, o2.columnC }
where o1.columnD != o2.columnD
select new { Object1 = o1, Object2 = o2 };
foreach (var diff in diffValue)
{
MyObject obj1 = diff.Object1;
MyObject obj2 = diff.Object2;
Console.WriteLine("Obj1-Value:{0} Obj2-Value:{1}", obj1.columnD, obj2.columnD);
}
when you override Equals and GetHashCode appropriately:
class MyObject
{
//Key combination
string columnA;
string columnB;
decimal columnC;
//The Value
decimal columnD;
//Enum for comparison, used for styling the item (value hidden from UI)
//Alternatively...this could be a string type, holding the enum.ToString()
MyComparisonEnum result;
public override bool Equals(object obj)
{
if (obj == null || !(obj is MyObject)) return false;
MyObject other = (MyObject)obj;
return columnA.Equals(other.columnA) && columnB.Equals(other.columnB) && columnC.Equals(other.columnC);
}
public override int GetHashCode()
{
int hash = 19;
hash = hash + (columnA ?? "").GetHashCode();
hash = hash + (columnB ?? "").GetHashCode();
hash = hash + columnC.GetHashCode();
return hash;
}
}

Resources