Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add examples for SE and MP to update counters of HTTP response status ranges (1xx, 2xx, etc.) for 3.x #4617

Merged
merged 10 commits into from
Jul 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions examples/metrics/http-status-count-se/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# http-status-count-se

This Helidon SE project illustrates a service which updates a family of counters based on the HTTP status returned in each response.

The main source in this example is identical to that in the Helidon SE QuickStart application except in these ways:
* The `HttpStatusMetricService` class creates and updates the status metrics.
* The `Main` class has a two small enhancements:
* The `createRouting` method instantiates `HttpStatusMetricService` and sets up routing for it.
* The `startServer` method has an additional variant to simplify a new unit test.

## Incorporating status metrics into your own application
Use this example for inspiration in writing your own service or just use the `HttpStatusMetricService` directly in your own application.

1. Copy and paste the `HttpStatusMetricService` class into your application, adjusting the package declaration as needed.
2. Register routing for an instance of `HttpStatusMetricService`, as shown here:
```java
Routing.Builder builder = Routing.builder()
...
.register(HttpStatusMetricService.create()
...
```

## Build and run


With JDK17+
```bash
mvn package
java -jar target/http-status-count-se.jar
```

## Exercise the application
```bash
curl -X GET http://localhost:8080/simple-greet
```
```listing
{"message":"Hello World!"}
```

```bash
curl -X GET http://localhost:8080/greet
```
```listing
{"message":"Hello World!"}
```
```bash
curl -X GET http://localhost:8080/greet/Joe
```
```listing
{"message":"Hello Joe!"}
```
```bash
curl -X PUT -H "Content-Type: application/json" -d '{"greeting" : "Hola"}' http://localhost:8080/greet/greeting

curl -X GET http://localhost:8080/greet/Jose
```
```listing
{"message":"Hola Jose!"}
```

## Try metrics
```bash
# Prometheus Format
curl -s -X GET http://localhost:8080/metrics/application
```

```listing
...
# TYPE application_httpStatus_total counter
# HELP application_httpStatus_total Counts the number of HTTP responses in each status category (1xx, 2xx, etc.)
application_httpStatus_total{range="1xx"} 0
application_httpStatus_total{range="2xx"} 5
application_httpStatus_total{range="3xx"} 0
application_httpStatus_total{range="4xx"} 0
application_httpStatus_total{range="5xx"} 0
...
```
# JSON Format

```bash
curl -H "Accept: application/json" -X GET http://localhost:8080/metrics
```
```json
{
...
"httpStatus;range=1xx": 0,
"httpStatus;range=2xx": 5,
"httpStatus;range=3xx": 0,
"httpStatus;range=4xx": 0,
"httpStatus;range=5xx": 0,
...
```

## Try health

```bash
curl -s -X GET http://localhost:8080/health
```
```listing
{"outcome":"UP",...

```
103 changes: 103 additions & 0 deletions examples/metrics/http-status-count-se/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

Copyright (c) 2017, 2022 Oracle and/or its affiliates.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.helidon.applications</groupId>
<artifactId>helidon-se</artifactId>
<version>3.0.0-SNAPSHOT</version>
<relativePath>../../../applications/se/pom.xml</relativePath>
</parent>
<groupId>io.helidon.examples</groupId>
<artifactId>http-status-count-se</artifactId>
<version>1.0-SNAPSHOT</version>

<name>Helidon Examples Metrics HTTP Status Counters</name>

<properties>
<mainClass>io.helidon.examples.se.httpstatuscount.Main</mainClass>
</properties>

<dependencies>
<dependency>
<groupId>io.helidon.webserver</groupId>
<artifactId>helidon-webserver</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.config</groupId>
<artifactId>helidon-config-yaml</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.metrics</groupId>
<artifactId>helidon-metrics</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.health</groupId>
<artifactId>helidon-health</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.health</groupId>
<artifactId>helidon-health-checks</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.media</groupId>
<artifactId>helidon-media-jsonp</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.webclient</groupId>
<artifactId>helidon-webclient</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-libs</id>
</execution>
</executions>
</plugin>
<plugin>
<groupId>io.helidon.build-tools</groupId>
<artifactId>helidon-maven-plugin</artifactId>
<executions>
<execution>
<id>third-party-license-report</id>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* Copyright (c) 2022 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.examples.se.httpstatuscount;

import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;

import io.helidon.common.http.Http;
import io.helidon.config.Config;
import io.helidon.webserver.Routing;
import io.helidon.webserver.ServerRequest;
import io.helidon.webserver.ServerResponse;
import io.helidon.webserver.Service;

import jakarta.json.Json;
import jakarta.json.JsonBuilderFactory;
import jakarta.json.JsonException;
import jakarta.json.JsonObject;


/**
* A simple service to greet you. Examples:
*
* Get default greeting message:
* curl -X GET http://localhost:8080/greet
*
* Get greeting message for Joe:
* curl -X GET http://localhost:8080/greet/Joe
*
* Change greeting
* curl -X PUT -H "Content-Type: application/json" -d '{"greeting" : "Howdy"}' http://localhost:8080/greet/greeting
*
* The message is returned as a JSON object
*/

public class GreetService implements Service {

/**
* The config value for the key {@code greeting}.
*/
private final AtomicReference<String> greeting = new AtomicReference<>();

private static final JsonBuilderFactory JSON = Json.createBuilderFactory(Collections.emptyMap());

private static final Logger LOGGER = Logger.getLogger(GreetService.class.getName());

GreetService(Config config) {
greeting.set(config.get("app.greeting").asString().orElse("Ciao"));
}

/**
* A service registers itself by updating the routing rules.
* @param rules the routing rules.
*/
@Override
public void update(Routing.Rules rules) {
rules
.get("/", this::getDefaultMessageHandler)
.get("/{name}", this::getMessageHandler)
.put("/greeting", this::updateGreetingHandler);
}

/**
* Return a worldly greeting message.
* @param request the server request
* @param response the server response
*/
private void getDefaultMessageHandler(ServerRequest request, ServerResponse response) {
sendResponse(response, "World");
}

/**
* Return a greeting message using the name that was provided.
* @param request the server request
* @param response the server response
*/
private void getMessageHandler(ServerRequest request, ServerResponse response) {
String name = request.path().param("name");
sendResponse(response, name);
}

private void sendResponse(ServerResponse response, String name) {
String msg = String.format("%s %s!", greeting.get(), name);

JsonObject returnObject = JSON.createObjectBuilder()
.add("message", msg)
.build();
response.send(returnObject);
}

private static <T> T processErrors(Throwable ex, ServerRequest request, ServerResponse response) {

if (ex.getCause() instanceof JsonException) {
LOGGER.log(Level.FINE, "Invalid JSON", ex);
JsonObject jsonErrorObject = JSON.createObjectBuilder()
.add("error", "Invalid JSON")
.build();
response.status(Http.Status.BAD_REQUEST_400).send(jsonErrorObject);
} else {
LOGGER.log(Level.FINE, "Internal error", ex);
JsonObject jsonErrorObject = JSON.createObjectBuilder()
.add("error", "Internal error")
.build();
response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(jsonErrorObject);
}

return null;
}

private void updateGreetingFromJson(JsonObject jo, ServerResponse response) {
if (!jo.containsKey("greeting")) {
JsonObject jsonErrorObject = JSON.createObjectBuilder()
.add("error", "No greeting provided")
.build();
response.status(Http.Status.BAD_REQUEST_400)
.send(jsonErrorObject);
return;
}

greeting.set(jo.getString("greeting"));
response.status(Http.Status.NO_CONTENT_204).send();
}

/**
* Set the greeting to use in future messages.
* @param request the server request
* @param response the server response
*/
private void updateGreetingHandler(ServerRequest request,
ServerResponse response) {
request.content().as(JsonObject.class)
.thenAccept(jo -> updateGreetingFromJson(jo, response))
.exceptionally(ex -> processErrors(ex, request, response));
}
}
Loading