org.eclipse.microprofile.metrics.annotation.Counted Java Examples

The following examples show how to use org.eclipse.microprofile.metrics.annotation.Counted. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RoomEndpoint.java    From sample-room-java with Apache License 2.0 9 votes vote down vote up
@Timed(name = "websocket_onOpen_timer",
    reusable = true,
    tags = "label=websocket")
@Counted(name = "websocket_onOpen_count",
    monotonic = true,
    reusable = true,
    tags = "label=websocket")
@Metered(name = "websocket_onOpen_meter",
    reusable = true,
    tags = "label=websocket")
@OnOpen
public void onOpen(Session session, EndpointConfig ec) {
    Log.log(Level.FINE, this, "A new connection has been made to the room.");

    // All we have to do in onOpen is send the acknowledgement
    sendMessage(session, Message.ACK_MSG);
}
 
Example #2
Source File: CDIAnnotationInfo.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public String name() {
    if (annotation instanceof Counted) {
        return ((Counted) annotation).name();
    } else if (annotation instanceof ConcurrentGauge) {
        return ((ConcurrentGauge) annotation).name();
    } else if (annotation instanceof Gauge) {
        return ((Gauge) annotation).name();
    } else if (annotation instanceof Metered) {
        return ((Metered) annotation).name();
    } else if (annotation instanceof Timed) {
        return ((Timed) annotation).name();
    } else if (annotation instanceof SimplyTimed) {
        return ((SimplyTimed) annotation).name();
    } else {
        throw new IllegalArgumentException("Unknown metric annotation type " + annotation.annotationType());
    }
}
 
Example #3
Source File: CDIAnnotationInfo.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public boolean absolute() {
    if (annotation instanceof Counted) {
        return ((Counted) annotation).absolute();
    } else if (annotation instanceof ConcurrentGauge) {
        return ((ConcurrentGauge) annotation).absolute();
    } else if (annotation instanceof Gauge) {
        return ((Gauge) annotation).absolute();
    } else if (annotation instanceof Metered) {
        return ((Metered) annotation).absolute();
    } else if (annotation instanceof Timed) {
        return ((Timed) annotation).absolute();
    } else if (annotation instanceof SimplyTimed) {
        return ((SimplyTimed) annotation).absolute();
    } else {
        throw SmallRyeMetricsMessages.msg.unknownMetricAnnotationType(annotation.annotationType());
    }
}
 
Example #4
Source File: RoomEndpoint.java    From sample-room-java with Apache License 2.0 6 votes vote down vote up
/**
 * Simple broadcast: loop over all mentioned sessions to send the message
 * <p>
 * We are effectively always broadcasting: a player could be connected
 * to more than one device, and that could correspond to more than one connected
 * session. Allow topic filtering on the receiving side (Mediator and browser)
 * to filter out and display messages.
 *
 * @param session Target session (used to find all related sessions)
 * @param message Message to send
 * @see #sendRemoteTextMessage(Session, Message)
 */
@Timed(name = "websocket_sendMessage_timer",
    reusable = true,
    tags = "label=websocket")
@Counted(name = "websocket_sendMessage_count",
    monotonic = true,
    reusable = true,
    tags = "label=websocket")
@Metered(name = "websocket_sendMessage_meter",
    reusable = true,
    tags = "label=websocket")
public void sendMessage(Session session, Message message) {
    for (Session s : session.getOpenSessions()) {
        sendMessageToSession(s, message);
    }
}
 
Example #5
Source File: CDIAnnotationInfo.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public String[] tags() {
    if (annotation instanceof Counted) {
        return ((Counted) annotation).tags();
    } else if (annotation instanceof ConcurrentGauge) {
        return ((ConcurrentGauge) annotation).tags();
    } else if (annotation instanceof Gauge) {
        return ((Gauge) annotation).tags();
    } else if (annotation instanceof Metered) {
        return ((Metered) annotation).tags();
    } else if (annotation instanceof Timed) {
        return ((Timed) annotation).tags();
    } else if (annotation instanceof SimplyTimed) {
        return ((SimplyTimed) annotation).tags();
    } else {
        throw SmallRyeMetricsMessages.msg.unknownMetricAnnotationType(annotation.annotationType());
    }
}
 
Example #6
Source File: RoomEndpoint.java    From sample-room-java with Apache License 2.0 6 votes vote down vote up
@Timed(name = "websocket_onError_timer",
    reusable = true,
    tags = "label=websocket")
@Counted(name = "websocket_onError_count",
    monotonic = true,
    reusable = true,
    tags = "label=websocket")
@Metered(name = "websocket_onError_meter",
    reusable = true,
    tags = "label=websocket")
@OnError
public void onError(Session session, Throwable t) {
    Log.log(Level.FINE, this, "A problem occurred on connection", t);

    // TODO: Careful with what might revealed about implementation details!!
    // We're opting for making debug easy..
    tryToClose(session,
            new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION,
                    trimReason(t.getClass().getName())));
}
 
Example #7
Source File: TodoResource.java    From quarkus-deep-dive with Apache License 2.0 6 votes vote down vote up
@PATCH
@Path("/{id}")
@Transactional
@Counted(name = "updateCount", monotonic = true, description = "How many update calls have been done.")
@Timed(name = "updateTime", description = "How long does the update method takes.", unit = MetricUnits.MILLISECONDS)
public Response update(@Valid Todo todo, @PathParam("id") Long id) {
    Todo entity = Todo.findById(id);
    if (entity == null) {
        throw new WebApplicationException("Item with id of " + id + " does not exist.", 404);
    }
    entity.id = id;
    entity.completed = todo.completed;
    entity.order = todo.order;
    entity.title = todo.title;
    entity.url = todo.url;
    return Response.ok(entity).build();
}
 
Example #8
Source File: CDIAnnotationInfo.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public String unit() {
    if (annotation instanceof Counted) {
        return ((Counted) annotation).unit();
    } else if (annotation instanceof ConcurrentGauge) {
        return ((ConcurrentGauge) annotation).unit();
    } else if (annotation instanceof Gauge) {
        return ((Gauge) annotation).unit();
    } else if (annotation instanceof Metered) {
        return ((Metered) annotation).unit();
    } else if (annotation instanceof Timed) {
        return ((Timed) annotation).unit();
    } else if (annotation instanceof SimplyTimed) {
        return ((SimplyTimed) annotation).unit();
    } else {
        throw SmallRyeMetricsMessages.msg.unknownMetricAnnotationType(annotation.annotationType());
    }
}
 
Example #9
Source File: CDIAnnotationInfo.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public String description() {
    if (annotation instanceof Counted) {
        return ((Counted) annotation).description();
    } else if (annotation instanceof ConcurrentGauge) {
        return ((ConcurrentGauge) annotation).description();
    } else if (annotation instanceof Gauge) {
        return ((Gauge) annotation).description();
    } else if (annotation instanceof Metered) {
        return ((Metered) annotation).description();
    } else if (annotation instanceof Timed) {
        return ((Timed) annotation).description();
    } else if (annotation instanceof SimplyTimed) {
        return ((SimplyTimed) annotation).description();
    } else {
        throw SmallRyeMetricsMessages.msg.unknownMetricAnnotationType(annotation.annotationType());
    }
}
 
Example #10
Source File: CDIAnnotationInfo.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
@Override
public String displayName() {
    if (annotation instanceof Counted) {
        return ((Counted) annotation).displayName();
    } else if (annotation instanceof ConcurrentGauge) {
        return ((ConcurrentGauge) annotation).displayName();
    } else if (annotation instanceof Gauge) {
        return ((Gauge) annotation).displayName();
    } else if (annotation instanceof Metered) {
        return ((Metered) annotation).displayName();
    } else if (annotation instanceof Timed) {
        return ((Timed) annotation).displayName();
    } else if (annotation instanceof SimplyTimed) {
        return ((SimplyTimed) annotation).displayName();
    } else {
        throw SmallRyeMetricsMessages.msg.unknownMetricAnnotationType(annotation.annotationType());
    }
}
 
Example #11
Source File: TodoResource.java    From quarkus-deep-dive with Apache License 2.0 5 votes vote down vote up
@DELETE
@Transactional
@Path("/{id}")
@Counted(name = "deleteOneCount", monotonic = true, description = "How many deleteOne calls have been done.")
@Timed(name = "deleteOneTime", description = "How long does the deleteOne method takes.", unit = MetricUnits.MILLISECONDS)
public Response deleteOne(@PathParam("id") Long id) {
    Todo entity = Todo.findById(id);
    if (entity == null) {
        throw new WebApplicationException("Todo with id of " + id + " does not exist.", Status.NOT_FOUND);
    }
    entity.delete();
    return Response.noContent().build();
}
 
Example #12
Source File: MetricCdiInjectionExtension.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private <X> void findAnnotatedInterfaces(@Observes @WithAnnotations({ Counted.class, Gauge.class, Metered.class,
        SimplyTimed.class, Timed.class, ConcurrentGauge.class }) ProcessAnnotatedType<X> pat) {
    Class<X> clazz = pat.getAnnotatedType().getJavaClass();
    Package pack = clazz.getPackage();
    if (pack != null && pack.getName().equals(GaugeRegistrationInterceptor.class.getPackage().getName())) {
        return;
    }
    if (clazz.isInterface()) {
        // All declared metrics of an annotated interface are registered during AfterDeploymentValidation
        metricsInterfaces.add(clazz);
    }
}
 
Example #13
Source File: PrimeNumberChecker.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{number}")
@Produces("text/plain")
@Counted(name = "performedChecks", description = "How many primality checks have been performed.")
@Timed(name = "checksTimer", description = "A measure how long it takes to perform the primality test.", unit = MetricUnits.MILLISECONDS)
public String checkIfPrime(@PathParam long number) {
    if (number < 1) {
        return "Only natural numbers can be prime numbers.";
    }
    if (number == 1) {
        return "1 is not prime.";
    }
    if (number == 2) {
        return "2 is prime.";
    }
    if (number % 2 == 0) {
        return number + " is not prime, it is divisible by 2.";
    }
    for (int i = 3; i < Math.floor(Math.sqrt(number)) + 1; i = i + 2) {
        if (number % i == 0) {
            return number + " is not prime, is divisible by " + i + ".";
        }
    }
    if (number > highestPrimeNumberSoFar) {
        highestPrimeNumberSoFar = number;
    }
    return number + " is prime.";
}
 
Example #14
Source File: WeatherService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Path("/week/status")
@Counted(monotonic = true, name = "weather_week_status", absolute = true)
@GET
@Produces(MediaType.TEXT_PLAIN)
public String weekStatus() {
    return "Hi, week will be mostly sunny!";
}
 
Example #15
Source File: TodoResource.java    From quarkus-deep-dive with Apache License 2.0 5 votes vote down vote up
@DELETE
@Transactional
@Counted(name = "deleteCompletedCount", monotonic = true, description = "How many deleteCompleted calls have been done.")
@Timed(name = "deleteCompletedTime", description = "How long does the deleteCompleted method takes.", unit = MetricUnits.MILLISECONDS)
public Response deleteCompleted() {
    Todo.deleteCompleted();
    return Response.noContent().build();
}
 
Example #16
Source File: TodoResource.java    From quarkus-deep-dive with Apache License 2.0 5 votes vote down vote up
@POST
@Transactional
@Counted(name = "createCount", monotonic = true, description = "How many create calls have been done.")
@Timed(name = "createTime", description = "How long does the create method takes.", unit = MetricUnits.MILLISECONDS)
public Response create(@Valid Todo item) {
    item.persist();
    return Response.status(Status.CREATED).entity(item).build();
}
 
Example #17
Source File: TodoResource.java    From quarkus-deep-dive with Apache License 2.0 5 votes vote down vote up
@GET
@Counted(name = "getAllCount", monotonic = true,
        description = "How many getAll calls have been done.")
@Timed(name = "getAllTime",
        description = "How long does the getAll method takes.",
        unit = MetricUnits.MILLISECONDS)
public List<Todo> getAll() {
    return Todo.listAll(Sort.by("order"));
}
 
Example #18
Source File: BookStoreEndpoint.java    From ebook-Building-an-API-Backend-with-MicroProfile with Apache License 2.0 5 votes vote down vote up
@Counted(unit = MetricUnits.NONE,
        name = "getBook",
        absolute = true,
        monotonic = true,
        displayName = "get single book",
        description = "Monitor how many times getBook method was called")
@GET
@Path("{id}")
public Response getBook(@PathParam("id") Long id) {
    Book book = bookService.findById(id);

    return Response.ok(book).build();
}
 
Example #19
Source File: MultipleMetricsMethodBean.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Counted(name = "counter")
@Gauge(name = "gauge", unit = MetricUnits.NONE)
@Metered(name = "meter")
@Timed(name = "timer")
public Long metricsMethod() {
    return 1234L;
}
 
Example #20
Source File: CountedMethodBean.java    From microprofile-metrics with Apache License 2.0 5 votes vote down vote up
@Counted(name = "countedMethod", absolute = true)
public T countedMethod(Callable<T> callable) {
    try {
        return callable.call();
    }
    catch (Exception cause) {
        throw new RuntimeException(cause);
    }
}
 
Example #21
Source File: GoogleCallback.java    From liberty-bikes with Eclipse Public License 1.0 5 votes vote down vote up
@GET
@Counted(name = "num_google_logins",
         displayName = "Number of Google Logins",
         description = "How many times a user has logged in through Google Auth.",
         absolute = true)
public Response getGoogleAuthURL(@Context HttpServletRequest request) throws IOException, URISyntaxException {
    // google calls us back at this app when a user has finished authing with them.
    // when it calls us back here, it passes an oauth_verifier token that we
    // can exchange for a google access token.

    GoogleAuthorizationCodeFlow flow = (GoogleAuthorizationCodeFlow) request.getSession().getAttribute("google");
    if (flow == null)
        return failureRedirect("did not find 'google' attribute set in HTTP session. It should be set by GoogleAuth");
    String code = request.getParameter("code");

    //now we need to invoke the access_token endpoint to swap the code for a token.
    String callbackURL = config.authUrl + "/GoogleCallback";

    Map<String, String> claims = new HashMap<String, String>();
    try {
        GoogleAuthorizationCodeTokenRequest token = flow.newTokenRequest(code).setRedirectUri(callbackURL);
        GoogleTokenResponse gResponse = token.execute();
        claims.putAll(introspectAuth(flow, gResponse));
    } catch (IOException e) {
        e.printStackTrace();
    }

    // if auth key was no longer valid, we won't build a JWT. Redirect back to start.
    if (!"true".equals(claims.get("valid"))) {
        return failureRedirect("claim was not valid");
    } else {
        String newJwt = createJwt(claims);
        return Response.temporaryRedirect(new URI(config.frontendUrl + "/" + newJwt)).build();
    }
}
 
Example #22
Source File: RoomEndpoint.java    From sample-room-java with Apache License 2.0 5 votes vote down vote up
@Timed(name = "websocket_onClose_timer",
    reusable = true,
    tags = "label=websocket")
@Counted(name = "websocket_onClose_count",
    monotonic = true,
    reusable = true,
    tags = "label=websocket")
@Metered(name = "websocket_onClose_meter",
    reusable = true,
    tags = "label=websocket")
@OnClose
public void onClose(Session session, CloseReason r) {
    Log.log(Level.FINE, this, "A connection to the room has been closed with reason " + r);
}
 
Example #23
Source File: RoomEndpoint.java    From sample-room-java with Apache License 2.0 5 votes vote down vote up
/**
 * The hook into the interesting room stuff.
 * @param session
 * @param message
 * @throws IOException
 */
@Timed(name = "websocket_onMessage_timer",
    reusable = true,
    tags = "label=websocket")
@Counted(name = "websocket_onMessage_count",
    monotonic = true,
    reusable = true,
    tags = "label=websocket")
@Metered(name = "websocket_onMessage_meter",
    reusable = true,
    tags = "label=websocket")
@OnMessage
public void receiveMessage(Session session, Message message) throws IOException {
    roomImplementation.handleMessage(session, message, this);
}
 
Example #24
Source File: WeatherService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Path("/day/status")
@Counted(monotonic = true, name = "weather_day_status", absolute = true,
        displayName = "Weather Day Status",
        description = "This metric shows the weather status of the day.",
        tags = {"weather=day"})
@GET
@Produces(MediaType.TEXT_PLAIN)
public String dayStatus() {
    return "Hi, today is a sunny day!";
}
 
Example #25
Source File: RestHandler.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 5 votes vote down vote up
@GET
@Counted(name="aCounter", monotonic = true, absolute = true)
@Metered(name="aMeter", absolute = true)
@Timed(  name="aTimer", absolute = true)
public String triggerAllMetrics() {

  justACounter.inc(2);

  return "Yo!";

}
 
Example #26
Source File: Party.java    From liberty-bikes with Eclipse Public License 1.0 4 votes vote down vote up
@Inject
@Counted(name = "number_of_parties", description = "Total Number of Parties", absolute = true)
public Party() {
    this(getRandomPartyID());
}
 
Example #27
Source File: GitHubCallback.java    From liberty-bikes with Eclipse Public License 1.0 4 votes vote down vote up
@GET
@Counted(name = "num_github_logins",
         displayName = "Number of Github Logins",
         description = "How many times a user has logged in through Github Auth.",
         absolute = true)
public Response getGitHubCallbackURL(@Context HttpServletRequest request) throws URISyntaxException {
    try {
        String githubCode = request.getParameter("code");
        String randomCode = (String) request.getSession().getAttribute("github");

        String thisURL = config.authUrl + "/GitHubCallback";

        // First send the user through GitHub OAuth to get permission to read their email address
        GithubTokenResponse response = githubOAuthAPI.accessToken(config.github_key, config.github_secret, githubCode, thisURL, randomCode);
        validate(response);
        System.out.println("GitHub access token: " + response.access_token);

        // Once we have the access token, use it to read their email
        EmailData[] emails = githubUserAPI.getEmail(response.access_token);
        for (EmailData email : emails)
            validate(email);
        String primaryEmail = null;
        for (EmailData data : emails)
            if (data.primary) {
                primaryEmail = data.email;
                break;
            } else {
                primaryEmail = data.email;
            }
        System.out.println("Got primary email of: " + primaryEmail);

        Map<String, String> claims = new HashMap<String, String>();
        claims.put("valid", "true");
        claims.put("id", "GITHUB:" + primaryEmail);
        claims.put("upn", primaryEmail);
        claims.put("email", primaryEmail);
        return Response.temporaryRedirect(new URI(config.frontendUrl + "/" + createJwt(claims))).build();
    } catch (Exception e) {
        e.printStackTrace();
        return fail();
    }
}
 
Example #28
Source File: ReuseMetricWithDifferingTagsBean.java    From smallrye-metrics with Apache License 2.0 4 votes vote down vote up
@Counted(name = "colorCounter", absolute = true, tags = { "color=blue" })
public void colorBlue2() {
}
 
Example #29
Source File: MultipleMetricsConstructorBean.java    From microprofile-metrics with Apache License 2.0 4 votes vote down vote up
@Counted(name = "counter")
@Metered(name = "meter")
@Timed(name = "timer")
public MultipleMetricsConstructorBean() {
}
 
Example #30
Source File: InventoryManager.java    From boost with Eclipse Public License 1.0 4 votes vote down vote up
@Counted(name = "inventoryAccessCount", absolute = true, monotonic = true, description = "Number of times the list of systems method is requested")
public InventoryList list() {
    return new InventoryList(systems);
}