use of io.vertx.reactivex.core.shareddata.Lock in project api-framework by vinscom.
the class SecurityTools method startup.
@SuppressWarnings("unchecked")
@StartService
public void startup() {
setRandom(new SecureRandom());
if (!getVertx().isClustered()) {
mGlobalUniqueString.complete("A" + mRandom.nextInt());
return;
}
Map<String, Object> cryptCtx = new HashMap<>();
Single<Lock> lock = getVertx().sharedData().rxGetLockWithTimeout("_in.erail.security", 5000);
getVertx().sharedData().<String, byte[]>rxGetClusterWideMap("_in.erail.security").flatMap((m) -> {
cryptCtx.put("map", m);
return m.rxGet("key");
}).map((k) -> {
cryptCtx.put("key", k);
return cryptCtx;
}).flatMap((ctx) -> {
if (ctx.get("key") == null) {
return lock.map((l) -> {
ctx.put("lock", l);
return ctx;
});
}
return Single.just(ctx);
}).flatMap(ctx -> {
if (ctx.get("lock") != null) {
return ((AsyncMap<String, Object>) (ctx.get("map"))).rxGet("key").map((k) -> {
ctx.put("key", k);
return ctx;
});
}
return Single.just(ctx);
}).flatMap((ctx) -> {
if (ctx.get("key") == null) {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
byte[] key = keygen.generateKey().getEncoded();
return ((AsyncMap<String, Object>) (ctx.get("map"))).rxPut("key", key).doOnComplete(() -> ctx.put("key", key)).toSingleDefault(ctx);
}
return Single.just(ctx);
}).map(ctx -> (byte[]) ctx.get("key")).doFinally(() -> {
if (cryptCtx.containsKey("lock")) {
Lock l = (Lock) cryptCtx.get("lock");
l.release();
}
}).subscribe((key) -> {
mKeySpec.complete(new SecretKeySpec(key, "AES"));
String unique = Base64.getEncoder().encodeToString(Arrays.copyOfRange(key, 0, 5));
mGlobalUniqueString.complete(unique.replace("=", ""));
getLog().info(() -> String.format("GlobalUniqueString:[%s]", unique));
});
}
Aggregations