How does StepMeterRegistry publish method execute in spring-boot? - spring-boot-actuator

package io.micrometer.core.instrument;
public interface Meter {
///...
default <T> T match(Function<Gauge, T> visitGauge, Function<Counter, T> visitCounter, Function<Timer, T> visitTimer,
Function<DistributionSummary, T> visitSummary, Function<LongTaskTimer, T> visitLongTaskTimer,
Function<TimeGauge, T> visitTimeGauge, Function<FunctionCounter, T> visitFunctionCounter,
Function<FunctionTimer, T> visitFunctionTimer, Function<Meter, T> visitMeter) {
if (this instanceof TimeGauge) {
return visitTimeGauge.apply((TimeGauge) this);
}
else if (this instanceof Gauge) {
return visitGauge.apply((Gauge) this);
}
else if (this instanceof Counter) {
return visitCounter.apply((Counter) this);
}
else if (this instanceof Timer) {
return visitTimer.apply((Timer) this);
}
else if (this instanceof DistributionSummary) {
return visitSummary.apply((DistributionSummary) this);
}
else if (this instanceof LongTaskTimer) {
return visitLongTaskTimer.apply((LongTaskTimer) this);
}
else if (this instanceof FunctionCounter) {
return visitFunctionCounter.apply((FunctionCounter) this);
}
else if (this instanceof FunctionTimer) {
return visitFunctionTimer.apply((FunctionTimer) this);
}
else {
return visitMeter.apply(this);
}
}
//...
}
public class XyzMeterRegistry extends StepMeterRegistry {
//...
#Override
protected void publish() {
for (List<Meter> batch : MeterPartition.partition(this, config.batchSize())) {
try {
// #formatter:off
httpClient.post(config.uri())
.withBasicAuthentication(config.userName(), config.password())
.withJsonContent(
batch.stream().flatMap(m -> m.match(
this::writeGauge,
this::writeCounter,
this::writeTimer,
this::writeSummary,
this::writeLongTaskTimer,
this::writeTimeGauge,
this::writeFunctionCounter,
this::writeFunctionTimer,
this::writeCustomMetric)
).collect(Collectors.joining(",", "[", "]"))
)
// #formatter:on
.send()
.onSuccess(response -> logger.debug("successfully sent {} metrics to kairos.", batch.size()))
.onError(response -> logger.error("failed to send metrics to kairos: {}", response.body()));
}
catch (Throwable t) {
logger.warn("failed to send metrics to kairos", t);
}
}
}
Stream<String> writeGauge(Gauge gauge) {
double value = gauge.value();
if (Double.isFinite(value)) {
return Stream.of(writeMetric(gauge.getId(), config().clock().wallTime(), value));
}
return Stream.empty();
}
Stream<String> writeCounter(Counter counter) {
return Stream.of(writeMetric(counter.getId(), config().clock().wallTime(), counter.count()));
}
Stream<String> writeTimer(Timer timer) {
long wallTime = config().clock().wallTime();
return Stream.of(writeMetric(idWithSuffix(timer.getId(), "count"), wallTime, timer.count()),
writeMetric(idWithSuffix(timer.getId(), "max"), wallTime, timer.max(getBaseTimeUnit())),
writeMetric(idWithSuffix(timer.getId(), "avg"), wallTime, timer.mean(getBaseTimeUnit())),
writeMetric(idWithSuffix(timer.getId(), "sum"), wallTime, timer.totalTime(getBaseTimeUnit())));
}
Stream<String> writeFunctionCounter(FunctionCounter counter) {
double count = counter.count();
if (Double.isFinite(count)) {
return Stream.of(writeMetric(counter.getId(), config().clock().wallTime(), count));
}
return Stream.empty();
}
//...etc.,
}
How the above match( ) is called from MeterRegistryComponent's publish method?
//How does here m.match(//....) is taking parameters from MeterRegistryComponent's publish method?**
//And what is the role of flatMap here?**
I just want to write custom meterregistry in which need to publish metrics using publish method

Related

Why I need to add some delay while making concurrent request in streaming gRPC? (Java) to get output

#Test
public void testType() throws InterruptedException {
Integer num = 15;
String name = "Sahil";
Float percentage = 96.7f;
DOB dob = DOB.newBuilder().setDay(20).setMonth(8).setYear(2022).build();
ArrayList<Object> objects = new ArrayList<>(Arrays.asList(num,name,percentage,dob));
TypeRequest.Builder builder = TypeRequest.newBuilder();
StreamObserver<TypeResponse> typeResponseStreamObserver = new StreamObserver<TypeResponse>() {
#Override
public void onNext(TypeResponse typeResponse) {
System.out.println(
"Type : " + typeResponse.getType()
);
}
#Override
public void onError(Throwable throwable) {
System.out.println("Error : "+throwable);
}
#Override
public void onCompleted() {
System.out.println("Finished all requests");
}
};
StreamObserver<TypeRequest> typeRequestStreamObserver = this.calculatorServiceStub.getType(typeResponseStreamObserver);
for(Object obj : objects){
if (obj instanceof Integer){
builder.setNum((Integer) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof String) {
builder.setName((String) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof Float) {
builder.setFNum((Float) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof DOB) {
builder.setDob((DOB) obj);
typeRequestStreamObserver.onNext(builder.build());
}
// --------------------------------------------
Thread.sleep(500);
// --------------------------------------------
}
typeRequestStreamObserver.onNext(builder.clearType().build());
typeRequestStreamObserver.onCompleted();
}
If I did not add any delay then the output console is just blank. Testing with tools like BloomRPC and Postman it works fine,
but for this I don't know why this is happening?
Any little help will be very helpful. I appreciate it.

Detect jailbroken bypass in Xamarin forms

My Xamarin based iOS application should not run in jailbroken devices. This is due to a IS audit. I have implemented the jailbroken detect mechanism. But I cannot find a way to detect whether someone using a jailbroken bypass method like for example A-bypass, shadow tweaks. Anyone with these tweaks can easily by pass the jailbroken detect code.
This is the class I used,
[assembly: Dependency(typeof(CheckHardware))]
namespace CustApp.iOS
{
public class CheckHardware : IHardwareSecurity
{
public CheckHardware()
{
}
public bool IsJailBreaked()
{
if (isPath() || canCreateFile() || isOpenLink())
{
return true;
}
else
{
return false;
}
}
private bool isPath()
{
bool res = false;
List<string> pathList = new List<string>
{
"/Applications/Cydia.app",
"/Applications/Checkra1n.app",
"/Applications/FakeCarrier.app",
"/Applications/Icy.app",
"/Applications/IntelliScreen.app",
"/Applications/MxTube.app",
"/Applications/RockApp.app",
"/Applications/SBSettings.app",
"/Applications/WinterBoard.app",
"/Applications/blackra1n.app",
"/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist",
"/Library/MobileSubstrate/DynamicLibraries/Veency.plist",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/System/Library/LaunchDaemons/com.ikey.bbot.plist",
"/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist",
"/etc/apt",
"/private/var/lib/apt",
"/private/var/lib/apt/",
"/private/var/lib/cydia",
"/private/var/mobile/Library/SBSettings/Themes",
"/private/var/stash",
"/private/var/tmp/cydia.log",
"/usr/bin/sshd",
"/var/cache/apt",
"/var/lib/apt",
"/usr/libexec/sftp-server",
"/usr/sbin/sshd",
"/bin/bash",
"/Library/MobileSubstrate/MobileSubstrate.dylib",
"/var/lib/cydia"
};
foreach (var fullPath in pathList)
{
if (File.Exists(fullPath))
{
res = true;
}
}
return res;
}
private bool canCreateFile()
{
try
{
File.WriteAllText("/private/jailbreak.txt", "This is a test.");
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
private bool isOpenLink()
{
if (UIApplication.SharedApplication.CanOpenUrl(NSUrl.FromString("cydia://package/com.example.package")))
{
return true;
}
else
{
return false;
}
}
public bool IsInEmulator()
{
bool isSimulator = Runtime.Arch == Arch.SIMULATOR;
return isSimulator;
}
}
}

Spring cloud function to create a GlobalKTable from strem

Is there an example of how to create a GlobalKTable to keep count from a KStream using Spring Cloud stream and using Functional approach?
Is implementing processor interface the right approach?
#Bean
public Consumer<KStream<String, Long>> processorsample() {
return input -> input.process(() -> new Processor<String, Long>() {
#Override
public void init(ProcessorContext context) {
if (state == null) {
state = (KeyValueStore<String, Long>) context.getStateStore("mystate");
}
}
#Override
public void process(String key, Long value) {
if (state != null) {
if (key != null) {
Long currentCount = state.get(key);
if (currentCount == null) {
state.put(key, value);
} else {
state.put(key, currentCount + value);
}
}
}
}
#Override
public void close() {
if (state != null) {
state.close();
}
}
}, "mystate");
}
According to the documentation GlobalKTables are read-only, you cannot modify a global table during the processing.
Since GlobalKTables are consumers of a Kafka topic, you can just send your data to the GlobalKTable's source topic, and eventually, it's going to be added to the table. But you cannot be sure that the GlobalKTable will be updated immediately.

want to use updateMessage("...") in a Class that is not an Task

I want to use updateMessage("...") in a Class that is not an Task.
How can I solve this Problem?
Is it possible to give a Task Handle which can perform a updateMessage("...") to a Function?
import javafx.concurrent.Task;
public class TestTask extends Task<Void> {
private final static int COUNT = 1000;
#Override
protected Void call() {
doTaskStuff("Found ");
return null;
}
public void doTaskStuff(String s) {
for (int i = 0; i < COUNT; i++) {
System.out.println(i);
this.updateProgress(i, COUNT);
this.updateMessage(s + (i + 1) + "!");
Dummy.dummy(this, i);
try {
Thread.sleep(1);
} catch (InterruptedException interruptedException) {
}
}
}
}
class Dummy {
public static void dummy(TestTask testTask, int i) {
String s = "";
if (i == 0) {
s = "i == 0";
} else {
s = "i != 0";
}
testTask.updateMessage(s);// does not work
}
}
The issue here is the method being protected. Of course you could override the method and increase the visibility, but this would imho be a bad approach:
#Override
public void updateMessage(String message) {
super.updateMessage(message);
}
Note that the method sets a single message, therefore you could just return the value:
updateMessage(Dummy.dummy(i));
public static String dummy(int i) {
return (i == 0) ? "i == 0" : "i != 0";
}
For multiple updates you could also provide access to this kind of functionality using an interface:
Dummy.dummy(this::updateMessage, i);
public static void dummy(Consumer<String> updater, int i) {
updater.accept((i == 0) ? "i == 0" : "i != 0");
}

If I know the name of a function, is it possible to get its parameters?

Dart code:
void hello(String name) {
print(name);
}
main() {
var funcName = "hello";
// how to get the parameter `String name`?
}
Using the function name as a string, "hello", is it possible to get the parameter String name of the real function hello ?
You can use mirrors to do that.
import 'dart:mirrors';
void hello(String name) {
print(name);
}
main() {
var funcName = "hello";
// get the top level functions in the current library
Map<Symbol, MethodMirror> functions =
currentMirrorSystem().isolate.rootLibrary.functions;
MethodMirror func = functions[const Symbol(funcName)];
// once function is found : get parameters
List<ParameterMirror> params = func.parameters;
for (ParameterMirror param in params) {
String type = MirrorSystem.getName(param.type.simpleName);
String name = MirrorSystem.getName(param.simpleName);
//....
print("$type $name");
}
}
You get this information through reflection (which it is not yet fully completed):
library hello_library;
import 'dart:mirrors';
void main() {
var mirrors = currentMirrorSystem();
const libraryName = 'hello_library';
var libraries = mirrors.findLibrary(const Symbol(libraryName));
var length = libraries.length;
if(length == 0) {
print('Library not found');
} else if(length > 1) {
print('Found more than one library');
} else {
var method = getStaticMethodInfo(libraries.first, const Symbol('hello'));
var parameters = getMethodParameters(method);
if(parameters != null) {
for(ParameterMirror parameter in parameters) {
print('name: ${parameter.simpleName}:, type: ${parameter.type.simpleName}');
}
}
}
}
MethodMirror getStaticMethodInfo(LibraryMirror library, Symbol methodName) {
if(library == null) {
return null;
}
return library.functions[methodName];
}
List<ParameterMirror> getMethodParameters(MethodMirror method) {
if(method == null) {
return null;
}
return method.parameters;
}
void hello(String name) {
print(name);
}

Resources