下面列出了javax.websocket.OnError#org.eclipse.microprofile.metrics.annotation.Timed 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Path("timed")
@Timed(name = "timed-request")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String timedRequest() {
long start = System.currentTimeMillis();
// Demo, not production style
int wait = new Random().nextInt(1000);
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
// Demo
e.printStackTrace();
}
long end = System.currentTimeMillis();
long delay = end - start;
doIncrement();
long count = getCustomerCount();
return String.format("MetricController#timedRequest, delay[0-1000]=%d, count=%d", delay, count);
}
@APIResponses(
value = {
@APIResponse(
responseCode = "404",
description = "We could not find anything",
content = @Content(mediaType = "text/plain"))
,
@APIResponse(
responseCode = "200",
description = "We have a list of books",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = Properties.class)))})
@Operation(summary = "Outputs a list of books",
description = "This method outputs a list of books")
@Timed(name = "get-all-books",
description = "Monitor the time getAll Method takes",
unit = MetricUnits.MILLISECONDS,
absolute = true)
@GET
public Response getAll() {
return Response.ok(bookService.getAll()).build();
}
@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();
}
@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());
}
}
@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());
}
}
@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());
}
}
@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());
}
}
@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());
}
}
@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());
}
}
/**
* Perform a GET operation on an LDP Resource.
*
* @implNote The Memento implemenation pattern exactly follows
* <a href="https://tools.ietf.org/html/rfc7089#section-4.2.1">section 4.2.1 of RFC 7089</a>.
* @param uriInfo the URI info
* @param headers the HTTP headers
* @param request the request
* @return the async response
*/
@GET
@Timed
@Operation(summary = "Get a linked data resource")
@APIResponses(
value = {
@APIResponse(
responseCode = "404",
description = "Missing resource"),
@APIResponse(
responseCode = "200",
description = "The linked data resource, serialized as Turtle",
content = @Content(mediaType = "text/turtle")),
@APIResponse(
responseCode = "200",
description = "The linked data resource, serialized as JSON-LD",
content = @Content(mediaType = "application/ld+json"))})
public CompletionStage<Response> getResource(@Context final Request request, @Context final UriInfo uriInfo,
@Context final HttpHeaders headers) {
return fetchResource(new TrellisRequest(request, uriInfo, headers))
.thenApply(ResponseBuilder::build).exceptionally(this::handleException);
}
/**
* Perform a PATCH operation on an LDP Resource.
*
* @param uriInfo the URI info
* @param secContext the security context
* @param headers the HTTP headers
* @param request the request
* @param body the body
* @return the async response
*/
@PATCH
@Timed
@Operation(summary = "Update a linked data resource")
public CompletionStage<Response> updateResource(@Context final Request request, @Context final UriInfo uriInfo,
@Context final HttpHeaders headers, @Context final SecurityContext secContext,
@RequestBody(description = "The update request for RDF resources, typically as SPARQL-Update",
required = true,
content = @Content(mediaType = "application/sparql-update")) final String body) {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext);
final String urlBase = getBaseUrl(req);
final IRI identifier = buildTrellisIdentifier(req.getPath());
final PatchHandler patchHandler = new PatchHandler(req, body, trellis, extensions, supportsCreateOnPatch,
defaultJsonLdProfile, urlBase);
return getParent(identifier).thenCombine(trellis.getResourceService().get(identifier), patchHandler::initialize)
.thenCompose(patchHandler::updateResource).thenCompose(patchHandler::updateMemento)
.thenApply(ResponseBuilder::build).exceptionally(this::handleException);
}
/**
* Perform a DELETE operation on an LDP Resource.
*
* @param uriInfo the URI info
* @param secContext the security context
* @param headers the HTTP headers
* @param request the request
* @return the async response
*/
@DELETE
@Timed
@Operation(summary = "Delete a linked data resource")
public CompletionStage<Response> deleteResource(@Context final Request request, @Context final UriInfo uriInfo,
@Context final HttpHeaders headers, @Context final SecurityContext secContext) {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext);
final String urlBase = getBaseUrl(req);
final IRI identifier = buildTrellisIdentifier(req.getPath());
final DeleteHandler deleteHandler = new DeleteHandler(req, trellis, extensions, urlBase);
return getParent(identifier)
.thenCombine(trellis.getResourceService().get(identifier), deleteHandler::initialize)
.thenCompose(deleteHandler::deleteResource).thenApply(ResponseBuilder::build)
.exceptionally(this::handleException);
}
/**
* Perform a POST operation on a LDP Resource.
*
* @param uriInfo the URI info
* @param secContext the security context
* @param headers the HTTP headers
* @param request the request
* @param body the body
* @return the async response
*/
@POST
@Timed
@Operation(summary = "Create a linked data resource")
public CompletionStage<Response> createResource(@Context final Request request, @Context final UriInfo uriInfo,
@Context final HttpHeaders headers, @Context final SecurityContext secContext,
@RequestBody(description = "The new resource") final InputStream body) {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext);
final String urlBase = getBaseUrl(req);
final String path = req.getPath();
final String identifier = getIdentifier(req);
final String separator = path.isEmpty() ? "" : "/";
final IRI parent = buildTrellisIdentifier(path);
final IRI child = buildTrellisIdentifier(path + separator + identifier);
final PostHandler postHandler = new PostHandler(req, parent, identifier, body, trellis, extensions, urlBase);
return trellis.getResourceService().get(parent)
.thenCombine(trellis.getResourceService().get(child), postHandler::initialize)
.thenCompose(postHandler::createResource).thenCompose(postHandler::updateMemento)
.thenApply(ResponseBuilder::build).exceptionally(this::handleException);
}
/**
* Perform a PUT operation on a LDP Resource.
*
* @param uriInfo the URI info
* @param secContext the security context
* @param headers the HTTP headers
* @param request the request
* @param body the body
* @return the async response
*/
@PUT
@Timed
@Operation(summary = "Create or update a linked data resource")
public CompletionStage<Response> setResource(@Context final Request request, @Context final UriInfo uriInfo,
@Context final HttpHeaders headers, @Context final SecurityContext secContext,
@RequestBody(description = "The updated resource") final InputStream body) {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, secContext);
final String urlBase = getBaseUrl(req);
final IRI identifier = buildTrellisIdentifier(req.getPath());
final PutHandler putHandler = new PutHandler(req, body, trellis, extensions, preconditionRequired,
createUncontained, urlBase);
return getParent(identifier).thenCombine(trellis.getResourceService().get(identifier), putHandler::initialize)
.thenCompose(putHandler::setResource).thenCompose(putHandler::updateMemento)
.thenApply(ResponseBuilder::build).exceptionally(this::handleException);
}
/**
* Copy a resource.
* @param response the async response
* @param request the request
* @param uriInfo the URI info
* @param headers the headers
* @param security the security context
*/
@COPY
@Timed
public void copyResource(@Suspended final AsyncResponse response, @Context final Request request,
@Context final UriInfo uriInfo, @Context final HttpHeaders headers,
@Context final SecurityContext security) {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security);
final Session session = HttpSession.from(security);
final IRI destination = getDestination(headers, getBaseUrl(req));
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
// Default is recursive copy as per RFC-4918
final Depth.DEPTH depth = getDepth(headers.getHeaderString("Depth"));
getParent(destination).thenCombine(services.getResourceService().get(destination), this::checkResources)
.thenCompose(parent -> services.getResourceService().touch(parent.getIdentifier()))
.thenCompose(future -> services.getResourceService().get(identifier))
.thenApply(this::checkResource)
.thenCompose(res -> copyTo(res, session, depth, destination, getBaseUrl(req)))
.thenApply(future -> status(NO_CONTENT).build())
.exceptionally(this::handleException).thenApply(response::resume);
}
/**
* Get properties for a resource.
* @param response the response
* @param request the request
* @param uriInfo the URI info
* @param headers the headers
* @param propfind the propfind
* @throws ParserConfigurationException if the XML parser is not properly configured
*/
@PROPFIND
@Consumes({APPLICATION_XML})
@Produces({APPLICATION_XML})
@Timed
public void getProperties(@Suspended final AsyncResponse response, @Context final Request request,
@Context final UriInfo uriInfo, @Context final HttpHeaders headers, final DavPropFind propfind)
throws ParserConfigurationException {
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers);
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
final String location = fromUri(getBaseUrl(req)).path(req.getPath()).build().toString();
final Document doc = getDocument();
services.getResourceService().get(identifier)
.thenApply(this::checkResource)
.thenApply(propertiesToMultiStatus(doc, location, propfind))
.thenApply(multistatus -> status(MULTI_STATUS).entity(multistatus).build())
.exceptionally(this::handleException).thenApply(response::resume);
}
/**
* Update properties on a resource.
* @param response the async response
* @param request the request
* @param uriInfo the URI info
* @param headers the headers
* @param security the security context
* @param propertyUpdate the property update request
* @throws ParserConfigurationException if the XML parser is not properly configured
*/
@PROPPATCH
@Consumes({APPLICATION_XML})
@Produces({APPLICATION_XML})
@Timed
public void updateProperties(@Suspended final AsyncResponse response,
@Context final Request request, @Context final UriInfo uriInfo,
@Context final HttpHeaders headers, @Context final SecurityContext security,
final DavPropertyUpdate propertyUpdate) throws ParserConfigurationException {
final Document doc = getDocument();
final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security);
final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
final String baseUrl = getBaseUrl(req);
final String location = fromUri(baseUrl).path(req.getPath()).build().toString();
final Session session = HttpSession.from(security);
services.getResourceService().get(identifier)
.thenApply(this::checkResource)
.thenCompose(resourceToMultiStatus(doc, identifier, location, baseUrl, session, propertyUpdate))
.thenApply(multistatus -> status(MULTI_STATUS).entity(multistatus).build())
.exceptionally(this::handleException).thenApply(response::resume);
}
@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);
}
@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())));
}
/**
* 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);
}
}
@GET
@Path("/userTZ")
@RolesAllowed("WorldClockSubscriber")
@Produces(MediaType.TEXT_PLAIN)
@Timed
public String getSubscriberZoneInfo() {
System.out.printf("Zoneinfo for %s: %s\n", jwt.getName(), zoneinfo);
return zoneinfo;
}
@GET
@Path("/hello")
@Timed(name="helloTime", absolute = true, description = "Timing of the Hello call",
tags={"type=timer","app=shop"})
public String getHelloTimed() {
try {
Thread.sleep((long) (Math.random()*200.0));
} catch (InterruptedException e) {
// We don't care if the sleep is interrupted.
}
return "Hello World";
}
@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!";
}
@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"));
}
@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();
}
@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();
}
@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();
}
@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.";
}
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);
}
}
@Timed(name = "getResourceTimed")
@Path("/timed")
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getResourceTimed() {
String response = getResource();
return JSON.createObjectBuilder()
.add("message", response)
.build();
}