io.micrometer.core.annotation.Timed Java Examples

The following examples show how to use io.micrometer.core.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: TimedAspect.java    From micrometer with Apache License 2.0 7 votes vote down vote up
@Around("execution (@io.micrometer.core.annotation.Timed * *.*(..))")
public Object timedMethod(ProceedingJoinPoint pjp) throws Throwable {
    Method method = ((MethodSignature) pjp.getSignature()).getMethod();
    Timed timed = method.getAnnotation(Timed.class);
    if (timed == null) {
        method = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());
        timed = method.getAnnotation(Timed.class);
    }

    final String metricName = timed.value().isEmpty() ? DEFAULT_METRIC_NAME : timed.value();
    final boolean stopWhenCompleted = CompletionStage.class.isAssignableFrom(method.getReturnType());

    if (!timed.longTask()) {
        return processWithTimer(pjp, timed, metricName, stopWhenCompleted);
    } else {
        return processWithLongTaskTimer(pjp, timed, metricName, stopWhenCompleted);
    }
}
 
Example #2
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
@Override
@Timed
public void onPlatformPropertiesUpdatedEvent(PlatformPropertiesUpdatedEvent event) {

    // Transform the properties into documents
    List<ValuedPropertyDocument> valuedProperties = event.getValuedProperties()
            .stream()
            .map(ValuedPropertyDocument::new)
            .collect(Collectors.toList());

    // Retrieve platform

    Optional<PlatformDocument> optPlatformDocument = minimalPlatformRepository.findById(event.getPlatformId());
    if (!optPlatformDocument.isPresent()) {
        throw new NotFoundException("Platform not found - platform properties update impossible - platform ID: " + event.getPlatformId());
    }
    PlatformDocument platformDocument = optPlatformDocument.get();

    // Update platform information
    platformDocument.setVersionId(event.getPlatformVersionId());
    platformDocument.setGlobalProperties(valuedProperties);
    platformDocument.setGlobalPropertiesVersionId(event.getGlobalPropertiesVersionId());
    platformDocument.buildInstancesModelAndSave(minimalPlatformRepository);
}
 
Example #3
Source File: UserResource.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
  * POST /users: create a new user
  *
  * @param userDto entity to save
  * @return the ResponseEntity with status 201 (Created) and with body the new user
  * @throws IllegalArgumentException when any given argument is invalid
  */
 @PostMapping
 @Timed
 Mono<ResponseEntity<UserDto>> create(@Valid @RequestBody UserDto userDto) {
   LOGGER.debug("REST request to create a new user : {}", userDto);

   if (Objects.nonNull(userDto.getId())) {
     throw new IllegalArgumentException("A new user cannot already have an ID");
   }

   //@formatter:off
   return userService.create(userDto)
				  .map(createdUser -> ResponseEntity.created(URI.create(String.format("/api/v1/users/%s", createdUser.getId())))
													.body(createdUser));
//@formatter:on
 }
 
Example #4
Source File: TimedAspect.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private Object processWithLongTaskTimer(ProceedingJoinPoint pjp, Timed timed, String metricName, boolean stopWhenCompleted) throws Throwable {

        Optional<LongTaskTimer.Sample> sample = buildLongTaskTimer(pjp, timed, metricName).map(LongTaskTimer::start);

        if (stopWhenCompleted) {
            try {
                return ((CompletionStage<?>) pjp.proceed()).whenComplete((result, throwable) -> sample.ifPresent(this::stopTimer));
            } catch (Exception ex) {
                sample.ifPresent(this::stopTimer);
                throw ex;
            }
        }

        try {
            return pjp.proceed();
        } finally {
            sample.ifPresent(this::stopTimer);
        }
    }
 
Example #5
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
@Override
@Timed
public void onModuleTechnosUpdatedEvent(ModuleTechnosUpdatedEvent event) {
    Optional<ModuleDocument> optModuleDocument = moduleRepository.findById(event.getModuleId());
    if (!optModuleDocument.isPresent()) {
        throw new NotFoundException("Module not found - update impossible - module ID: " + event.getModuleId());
    }
    ModuleDocument moduleDocument = optModuleDocument.get();
    List<TechnoDocument> technoDocuments = technoProjectionRepository.getTechnoDocumentsFromDomainInstances(
            event.getTechnos(), moduleDocument.getDomainKey());
    moduleDocument.setTechnos(technoDocuments);
    moduleDocument.setVersionId(event.getVersionId());

    moduleDocument.extractPropertiesAndSave(moduleRepository);
}
 
Example #6
Source File: EventDispatcher.java    From spring-rdbms-cdc-kafka-elasticsearch with Apache License 2.0 6 votes vote down vote up
@KafkaListener(topics = {
    "mysqlcdc.cdc.USERS",
    "mysqlcdc.cdc.JOBS",
    "mysqlcdc.cdc.ADDRESSES"})
@Timed
public void handleEvents(List<ConsumerRecord<String, DebeziumEvent>> records,
                            Acknowledgment acknowledgment) {

  LOGGER.debug("Request to process {} records", records.size());

  List<ConsumerRecord<String, DebeziumEvent>> sortedRecords = records.stream()
      .sorted(Comparator.comparing(r -> r.value().getPayload().getDate()))
      .collect(Collectors.toList());

  sortedRecords.forEach(record -> {

    LOGGER.debug("Request to handle {} event in the topic {}", record.value().getPayload().getOperation(), record.topic());

    handlerFactory.getHandler(record.topic()).process(record.value());

  });

  acknowledgment.acknowledge();
}
 
Example #7
Source File: WebMvcMetricsFilter.java    From foremast with Apache License 2.0 6 votes vote down vote up
private void record(TimingSampleContext timingContext, HttpServletResponse response, HttpServletRequest request,
                    Object handlerObject, Throwable e) {
    for (Timed timedAnnotation : timingContext.timedAnnotations) {
        timingContext.timerSample.stop(Timer.builder(timedAnnotation, metricName)
            .tags(tagsProvider.httpRequestTags(request, response, handlerObject, e))
            .register(registry));
    }

    if (timingContext.timedAnnotations.isEmpty() && autoTimeRequests) {
        timingContext.timerSample.stop(Timer.builder(metricName)
            .tags(tagsProvider.httpRequestTags(request, response, handlerObject, e))
            .register(registry));
    }

    for (LongTaskTimer.Sample sample : timingContext.longTaskTimerSamples) {
        sample.stop();
    }
}
 
Example #8
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
@Override
@Timed
public void onPlatformModulePropertiesUpdatedEvent(PlatformModulePropertiesUpdatedEvent event) {
    // Tranformation des propriétés du domaine en documents
    final List<AbstractValuedPropertyDocument> abstractValuedProperties = AbstractValuedPropertyDocument.fromAbstractDomainInstances(event.getValuedProperties());

    // Récupération de la plateforme et mise à jour de la version
    Optional<PlatformDocument> optPlatformDocument = minimalPlatformRepository.findById(event.getPlatformId());
    if (!optPlatformDocument.isPresent()) {
        throw new NotFoundException("Platform not found - module properties update impossible - platform ID: " + event.getPlatformId());
    }
    PlatformDocument platformDocument = optPlatformDocument.get();
    platformDocument.setVersionId(event.getPlatformVersionId());

    // Modification des propriétés du module dans la plateforme
    platformDocument.getActiveDeployedModules()
            .filter(currentDeployedModuleDocument -> currentDeployedModuleDocument.getPropertiesPath().equals(event.getPropertiesPath()))
            .findAny().ifPresent(deployedModuleDocument -> {
        updateDeployedModuleVersionId(event.getPropertiesVersionId(), deployedModuleDocument);
        completePropertiesWithMustacheContent(abstractValuedProperties, deployedModuleDocument);
    });

    platformDocument.buildInstancesModelAndSave(minimalPlatformRepository);
}
 
Example #9
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<String> onGetInstancesModelQuery(GetInstancesModelQuery query) {
    PlatformKeyDocument platformKeyDocument = new PlatformKeyDocument(query.getPlatformKey());
    final Optional<PlatformDocument> platformDocument = platformRepository
            .findModuleByPropertiesPath(platformKeyDocument, query.getPropertiesPath());

    return platformDocument
            .map(PlatformDocument::getActiveDeployedModules)
            .orElse(Stream.empty())
            .flatMap(deployedModuleDocument -> Optional.ofNullable(deployedModuleDocument.getInstancesModel())
                    .orElseGet(Collections::emptyList)
                    .stream())
            .collect(Collectors.toList());
}
 
Example #10
Source File: MetricsRequestEventListener.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private Set<Timed> annotations(RequestEvent event) {
    final Set<Timed> timed = new HashSet<>();

    final ResourceMethod matchingResourceMethod = event.getUriInfo().getMatchedResourceMethod();
    if (matchingResourceMethod != null) {
        // collect on method level
        timed.addAll(timedFinder.findTimedAnnotations(matchingResourceMethod.getInvocable().getHandlingMethod()));

        // fallback on class level
        if (timed.isEmpty()) {
            timed.addAll(timedFinder.findTimedAnnotations(matchingResourceMethod.getInvocable().getHandlingMethod()
                .getDeclaringClass()));
        }
    }
    return timed;
}
 
Example #11
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
@QueryHandler
@Override
@Timed
public Optional<String> onGetPlatformIdFromEvents(GetPlatformIdFromEvents query) {
    // On recherche dans TOUS les événements un PlatformEventWithPayload ayant la bonne clef.
    // On se protège en terme de perfs en n'effectuant cette recherche que sur les 7 derniers jours.
    Instant todayLastWeek = Instant.ofEpochSecond(System.currentTimeMillis() / 1000 - 7 * 24 * 60 * 60);
    Stream<? extends TrackedEventMessage<?>> abstractEventStream = eventStorageEngine.readEvents(eventStorageEngine.createTokenAt(todayLastWeek), false);
    Optional<PlatformDeletedEvent> lastMatchingPlatformEvent = abstractEventStream
            .map(GenericTrackedDomainEventMessage.class::cast)
            .filter(msg -> PlatformAggregate.class.getSimpleName().equals(msg.getType()))
            .map(MessageDecorator::getPayload)
            // On part du principe qu'une plateforme à restaurer a forcément été supprimée,
            // on peut donc n'effectuer la recherche que sur l'évènement `PlatformDeletedEvent`
            .filter(PlatformDeletedEvent.class::isInstance)
            .map(PlatformDeletedEvent.class::cast)
            .filter(platformEvent -> platformEvent.getPlatformKey().getApplicationName().equalsIgnoreCase(query.getPlatformKey().getApplicationName()) &&
                    platformEvent.getPlatformKey().getPlatformName().equalsIgnoreCase(query.getPlatformKey().getPlatformName()))
            .reduce((first, second) -> second); // On récupère le dernier élément
    return lastMatchingPlatformEvent.map(PlatformDeletedEvent::getPlatformId);
}
 
Example #12
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<ValuedPropertyView> onGetGlobalPropertiesQuery(final GetGlobalPropertiesQuery query) {
    PlatformKeyDocument platformKeyDocument = new PlatformKeyDocument(query.getPlatformKey());
    return platformRepository.findGlobalPropertiesByPlatformKey(platformKeyDocument)
            .map(PlatformDocument::getGlobalProperties)
            .map(ValuedPropertyDocument::toValuedPropertyViews)
            .orElseGet(Collections::emptyList);
}
 
Example #13
Source File: MongoTemplateProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
/*** EVENT HANDLERS ***/

    @EventHandler
    @Override
    @Timed
    public void onTemplateCreatedEvent(TemplateCreatedEvent event) {
        Optional<ModuleDocument> optModuleDocument = moduleRepository.findById(event.getModuleId());
        if (!optModuleDocument.isPresent()) {
            throw new NotFoundException("Module not found - template creation impossible - module: " + event.getModuleKey().getNamespaceWithoutPrefix());
        }
        ModuleDocument moduleDocument = optModuleDocument.get();
        TemplateDocument templateDocument = new TemplateDocument(event.getTemplate());
        moduleDocument.addTemplate(templateDocument);
        moduleDocument.extractPropertiesAndSave(moduleRepository);
    }
 
Example #14
Source File: MongoTemplateProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
@Override
@Timed
public void onTemplateUpdatedEvent(TemplateUpdatedEvent event) {
    Optional<ModuleDocument> optModuleDocument = moduleRepository.findById(event.getModuleId());
    if (!optModuleDocument.isPresent()) {
        throw new NotFoundException("Module not found - template update impossible - module: " + event.getModuleKey().getNamespaceWithoutPrefix());
    }
    ModuleDocument moduleDocument = optModuleDocument.get();
    TemplateDocument templateDocument = new TemplateDocument(event.getTemplate());
    moduleDocument.updateTemplate(templateDocument);
    moduleDocument.extractPropertiesAndSave(moduleRepository);
}
 
Example #15
Source File: MongoTemplateProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
@Override
@Timed
public void onTemplateDeletedEvent(TemplateDeletedEvent event) {
    Optional<ModuleDocument> optModuleDocument = moduleRepository.findById(event.getModuleId());
    if (!optModuleDocument.isPresent()) {
        throw new NotFoundException("Module not found - template deletion impossible - module: " + event.getModuleKey().getNamespaceWithoutPrefix());
    }
    ModuleDocument moduleDocument = optModuleDocument.get();
    moduleDocument.removeTemplate(event.getTemplateName());
    moduleDocument.extractPropertiesAndSave(moduleRepository);
}
 
Example #16
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<ModuleView> onGetModulesWithinQuery(GetModulesWithinQuery query) {
    List<KeyDocument> moduleKeys = KeyDocument.fromModelKeys(query.getModulesKeys());
    return moduleRepository.findModulesWithin(moduleKeys).stream()
            .map(ModuleDocument::toModuleView)
            .collect(Collectors.toList());
}
 
Example #17
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public Optional<ApplicationView> onGetApplicationByNameQuery(GetApplicationByNameQuery query) {
    List<PlatformDocument> platformDocuments = query.getHidePlatformsModules()
            ? platformRepository.findPlatformsForApplicationAndExcludeModules(query.getApplicationName())
            : platformRepository.findAllByKeyApplicationName(query.getApplicationName());

    return Optional.ofNullable(CollectionUtils.isEmpty(platformDocuments) ? null
            : PlatformDocument.toApplicationView(query.getApplicationName(), platformDocuments));
}
 
Example #18
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<ModulePlatformView> onGetPlatformUsingModuleQuery(GetPlatformsUsingModuleQuery query) {
    TemplateContainer.Key moduleKey = query.getModuleKey();
    List<PlatformDocument> platformDocuments = platformRepository
            .findPlatformsUsingModule(
                    moduleKey.getName(), moduleKey.getVersion(), moduleKey.isWorkingCopy());
    return Optional.ofNullable(platformDocuments)
            .map(List::stream)
            .orElse(Stream.empty())
            .map(PlatformDocument::toModulePlatformView)
            .collect(Collectors.toList());
}
 
Example #19
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<SearchPlatformResultView> onSearchPlatformsQuery(SearchPlatformsQuery query) {
    String platformName = StringUtils.defaultString(query.getPlatformName(), "");
    List<PlatformDocument> platformDocuments =
            platformRepository.findAllByKeyApplicationNameLikeAndKeyPlatformNameLike(
                    query.getApplicationName(),
                    platformName);
    return Optional.ofNullable(platformDocuments)
            .map(List::stream)
            .orElse(Stream.empty())
            .map(PlatformDocument::toSearchPlatformResultView)
            .collect(Collectors.toList());
}
 
Example #20
Source File: MongoPlatformProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<ApplicationView> onGetAllApplicationsDetailQuery(GetAllApplicationsDetailQuery query) {

    return Optional.ofNullable(platformRepository.findAll()).stream()
            .flatMap(Collection::stream)
            .map(PlatformDocument::toPlatformView)
            .collect(groupingBy(PlatformView::getApplicationName))
            .entrySet()
            .stream()
            .map(entry -> new ApplicationView(entry.getKey(), entry.getValue()))
            .collect(Collectors.toList());

}
 
Example #21
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<Module.Key> onGetModulesWithPasswordWithinQuery(GetModulesWithPasswordWithinQuery query) {
    List<KeyDocument> modulesKeys = KeyDocument.fromModelKeys(query.getModulesKeys());
    return moduleRepository.findModulesWithPasswordWithin(modulesKeys).stream()
            .map(ModuleDocument::getDomainKey)
            .collect(Collectors.toList());
}
 
Example #22
Source File: ConsulCatalogWatch.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Timed("consul.watch-catalog-services")
public void catalogServicesWatch() {
	try {
		long index = -1;
		if (this.catalogServicesIndex.get() != null) {
			index = this.catalogServicesIndex.get().longValue();
		}

		CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
				.setQueryParams(new QueryParams(
						this.properties.getCatalogServicesWatchTimeout(), index))
				.setToken(this.properties.getAclToken()).build();
		Response<Map<String, List<String>>> response = this.consul
				.getCatalogServices(request);
		Long consulIndex = response.getConsulIndex();
		if (consulIndex != null) {
			this.catalogServicesIndex.set(BigInteger.valueOf(consulIndex));
		}

		if (log.isTraceEnabled()) {
			log.trace("Received services update from consul: " + response.getValue()
					+ ", index: " + consulIndex);
		}
		this.publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
	}
	catch (Exception e) {
		log.error("Error watching Consul CatalogServices", e);
	}
}
 
Example #23
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<TemplateContainerKeyView> onGetModulesUsingTechnoQuery(GetModulesUsingTechnoQuery query) {
    List<ModuleDocument> moduleDocuments = moduleRepository.findAllByTechnosId(query.getTechnoId());
    return moduleDocuments
            .stream()
            .map(ModuleDocument::getKey)
            .map(KeyDocument::toKeyView)
            .collect(Collectors.toList());
}
 
Example #24
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<ModulePropertiesView> onGetModulesSimplePropertiesQuery(GetModulesPropertiesQuery query) {
    List<KeyDocument> modulesKeys = KeyDocument.fromModelKeys(query.getModulesKeys());

    return moduleRepository.findPropertiesByKeyIn(modulesKeys)
            .stream()
            .map(ModuleDocument::toModulePropertiesView)
            .collect(Collectors.toList());
}
 
Example #25
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<AbstractPropertyView> onGetModulePropertiesQuery(GetModulePropertiesQuery query) {
    KeyDocument moduleKey = new KeyDocument(query.getModuleKey());
    return moduleRepository.findPropertiesByModuleKey(moduleKey)
            .map(ModuleDocument::getProperties)
            .map(AbstractPropertyDocument::toViews)
            .orElseGet(Collections::emptyList);
}
 
Example #26
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<ModuleView> onSearchModulesQuery(SearchModulesQuery query) {
    String[] values = query.getInput().split(" ");
    String name = values.length > 0 ? values[0] : "";
    String version = values.length > 1 ? values[1] : "";

    PageRequest pageable = PageRequest.of(0, query.getSize());
    return moduleRepository.findAllByKeyNameLikeAndKeyVersionLike(name, version, pageable)
            .stream()
            .map(ModuleDocument::toModuleView)
            .collect(Collectors.toList());
}
 
Example #27
Source File: MongoTechnoProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public Boolean onTechnoExistsQuery(TechnoExistsQuery query) {
    KeyDocument keyDocument = new KeyDocument(query.getTechnoKey());
    return technoRepository.existsByKey(keyDocument);
}
 
Example #28
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<String> onGetModuleVersionTypesQuery(GetModuleVersionTypesQuery query) {
    return moduleRepository.findKeysByNameAndVersion(query.getModuleName(), query.getModuleVersion())
            .stream()
            .map(ModuleDocument::getKey)
            .map(KeyDocument::isWorkingCopy)
            .map(TemplateContainer.VersionType::toString)
            .collect(Collectors.toList());
}
 
Example #29
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public List<String> onGetModulesNameQuery(GetModulesNameQuery query) {
    final DistinctIterable<String> iterable = mongoTemplate.getCollection(MODULE).distinct("key.name", String.class);
    return StreamSupport.stream(iterable.spliterator(), false).collect(Collectors.toList());
}
 
Example #30
Source File: MongoModuleProjectionRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
@Timed
public Optional<ModuleView> onGetModuleByIdQuery(GetModuleByIdQuery query) {
    return moduleRepository.findOptionalById(query.getModuleId())
            .map(ModuleDocument::toModuleView);
}