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

The following examples show how to use org.eclipse.microprofile.metrics.annotation.Timed. 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: TrellisWebDAV.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #3
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #4
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #5
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #6
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 #7
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 #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[] 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 #10
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 #11
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 #12
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #13
Source File: TrellisWebDAV.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #14
Source File: TrellisWebDAV.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #15
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #16
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 #17
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 #18
Source File: BookStoreEndpoint.java    From ebook-Building-an-API-Backend-with-MicroProfile with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #19
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 #20
Source File: MetricController.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 6 votes vote down vote up
@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);
}
 
Example #21
Source File: TrellisHttpResource.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Perform an OPTIONS operation on an LDP Resource.
 *
 * @param uriInfo the URI info
 * @param headers the HTTP headers
 * @param request the request
 * @return the async response
 */
@OPTIONS
@Timed
@Operation(summary = "Get the interaction options for a linked data resource")
@APIResponse(description = "The interaction options for a linked data resource")
public CompletionStage<Response> options(@Context final Request request, @Context final UriInfo uriInfo,
        @Context final HttpHeaders headers) {
    final TrellisRequest req = new TrellisRequest(request, uriInfo, headers);
    final OptionsHandler optionsHandler = new OptionsHandler(req, trellis, extensions);
    return supplyAsync(optionsHandler::ldpOptions).thenApply(ResponseBuilder::build)
        .exceptionally(this::handleException);
}
 
Example #22
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 #23
Source File: WebAcFilter.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Timed
@Override
public void filter(final ContainerRequestContext ctx) {
    if (!enabled) {
        return; // If WebAC is disabled then skip the checks
    }

    final String path = ctx.getUriInfo().getPath();
    final Session s = buildSession(ctx, baseUrl);
    final String method = ctx.getMethod();

    final AuthorizedModes modes = accessService.getAuthorizedModes(buildTrellisIdentifier(path), s);
    ctx.setProperty(SESSION_WEBAC_MODES, modes);

    final Prefer prefer = Prefer.valueOf(ctx.getHeaderString(PREFER));

    // Control-level access
    if (ctx.getUriInfo().getQueryParameters().getOrDefault(HttpConstants.EXT, emptyList())
            .contains(HttpConstants.ACL) || reqAudit(prefer)) {
        verifyCanControl(modes.getAccessModes(), s, path);
    // Everything else
    } else {
        if (readable.contains(method) || reqRepresentation(prefer)) {
            verifyCanRead(modes.getAccessModes(), s, path);
        }
        if (writable.contains(method)) {
            verifyCanWrite(modes.getAccessModes(), s, path);
        }
        if (appendable.contains(method)) {
            verifyCanAppend(modes.getAccessModes(), s, path);
        }
    }
}
 
Example #24
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 #25
Source File: ZoneInfoEndpoint.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 5 votes vote down vote up
@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;
}
 
Example #26
Source File: TrellisWebDAV.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Move 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
 */
@MOVE
@Timed
public void moveResource(@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 String baseUrl = getBaseUrl(req);
    final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
    final IRI destination = getDestination(headers, baseUrl);
    final Session session = HttpSession.from(security);

    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)
        // Note: all MOVE operations are recursive (Depth: infinity), hence recursiveCopy
        .thenAccept(res -> recursiveCopy(services, session, res, destination, baseUrl))
        .thenAccept(future -> recursiveDelete(services, session, identifier, baseUrl))
        .thenCompose(future -> services.getResourceService().delete(Metadata.builder(identifier)
                .interactionModel(LDP.Resource).build()))
        .thenCompose(future -> {
            final Dataset immutable = rdf.createDataset();
            services.getAuditService().creation(identifier, session).stream()
                .map(skolemizeQuads(services.getResourceService(), baseUrl)).forEachOrdered(immutable::add);
            return services.getResourceService().add(identifier, immutable)
                .whenComplete((a, b) -> closeDataset(immutable));
        })
        .thenAccept(future -> services.getEventService().emit(new SimpleEvent(externalUrl(identifier,
            baseUrl), session.getAgent(), asList(PROV.Activity, AS.Delete), singletonList(LDP.Resource))))
        .thenApply(future -> status(NO_CONTENT).build())
        .exceptionally(this::handleException).thenApply(response::resume);
}
 
Example #27
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 #28
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 #29
Source File: WeatherService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Path("/day/status")
@Timed(name = "weather_day_status", absolute = true,
        displayName = "Weather Day Status",
        description = "This metric shows the weather status of the day.")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String dayStatus() {
    return "Hi, today is a sunny day!";
}
 
Example #30
Source File: MetricController.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
@Path("timed")
@Timed(name = "timed-request")
@GET
public String timedRequest() {
    // Demo, not production style
    int wait = new Random().nextInt(1000);
    try {
        Thread.sleep(wait);
    } catch (InterruptedException e) {
        // Demo
        e.printStackTrace();
    }

    return "Request is used in statistics, check with the Metrics call.";
}