use of org.springframework.beans.factory.annotation.Value in project thingsboard by thingsboard.
the class DefaultTbApiUsageClient method reportStats.
private void reportStats() {
ConcurrentMap<OwnerId, ToUsageStatsServiceMsg.Builder> report = new ConcurrentHashMap<>();
for (ApiUsageRecordKey key : ApiUsageRecordKey.values()) {
ConcurrentMap<OwnerId, AtomicLong> statsForKey = stats.get(key);
statsForKey.forEach((ownerId, statsValue) -> {
long value = statsValue.get();
if (value == 0)
return;
ToUsageStatsServiceMsg.Builder statsMsgBuilder = report.computeIfAbsent(ownerId, id -> {
ToUsageStatsServiceMsg.Builder newStatsMsgBuilder = ToUsageStatsServiceMsg.newBuilder();
TenantId tenantId = ownerId.getTenantId();
newStatsMsgBuilder.setTenantIdMSB(tenantId.getId().getMostSignificantBits());
newStatsMsgBuilder.setTenantIdLSB(tenantId.getId().getLeastSignificantBits());
EntityId entityId = ownerId.getEntityId();
if (entityId != null && entityId.getEntityType() == EntityType.CUSTOMER) {
newStatsMsgBuilder.setCustomerIdMSB(entityId.getId().getMostSignificantBits());
newStatsMsgBuilder.setCustomerIdLSB(entityId.getId().getLeastSignificantBits());
}
return newStatsMsgBuilder;
});
statsMsgBuilder.addValues(UsageStatsKVProto.newBuilder().setKey(key.name()).setValue(value).build());
});
statsForKey.clear();
}
report.forEach(((ownerId, statsMsg) -> {
// TODO: figure out how to minimize messages into the queue. Maybe group by 100s of messages?
TenantId tenantId = ownerId.getTenantId();
EntityId entityId = Optional.ofNullable(ownerId.getEntityId()).orElse(tenantId);
TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, tenantId, entityId).newByTopic(msgProducer.getDefaultTopic());
msgProducer.send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), statsMsg.build()), null);
}));
if (!report.isEmpty()) {
log.debug("Reporting API usage statistics for {} tenants and customers", report.size());
}
}
use of org.springframework.beans.factory.annotation.Value in project vorto by eclipse.
the class NamespaceController method findAllAccessibleNamespacesByPartial.
/**
* Finds all namespaces accessible to the authenticated user, by a partial name. <br/>
* This is used in the UI to search for namespaces the user can view, aka all the public ones and
* the private ones the user has at least one role in.
*
* @param partial
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/search/{partial:.+}")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Collection<NamespaceDto>> findAllAccessibleNamespacesByPartial(@ApiParam(value = "The partial name of the namespaces to be searched with", required = true) @PathVariable String partial) {
if (Strings.nullToEmpty(partial).trim().isEmpty()) {
return new ResponseEntity<>(Collections.emptyList(), HttpStatus.OK);
}
IUserContext userContext = UserContext.user(SecurityContextHolder.getContext().getAuthentication());
Collection<NamespaceDto> result = namespaceRepository.findNamespaceByPartial(partial.toLowerCase()).stream().filter(n -> {
try {
return // all public namespaces
!n.getName().startsWith(NamespaceValidator.PRIVATE_NAMESPACE_PREFIX) || // or namespaces where user has a role
userNamespaceRoleService.hasAnyRole(userContext.getUsername(), n.getName());
// should never occur here
} catch (DoesNotExistException dnee) {
return false;
}
}).map(EntityDTOConverter::createNamespaceDTO).sorted(Comparator.comparing(NamespaceDto::getName)).collect(Collectors.toList());
return new ResponseEntity<>(result, HttpStatus.OK);
}
use of org.springframework.beans.factory.annotation.Value in project vorto by eclipse.
the class NamespaceController method requestAccessToNamespace.
@PostMapping("/requestAccess")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<OperationResult> requestAccessToNamespace(@RequestBody @ApiParam(value = "The request body specifying who initiates the request, the namespace, whom the request is intended for, and an optional collection of suggested roles", required = true) NamespaceAccessRequestDTO request) {
Optional<OperationResult> validationError = NamespaceValidator.validateAccessRequest(request);
if (validationError.isPresent()) {
return new ResponseEntity<>(validationError.get(), HttpStatus.BAD_REQUEST);
}
// checks namespace exists
// should only occur if namespace was deleted after user search, but before sending request
Namespace target;
try {
target = namespaceService.getByName(request.getNamespaceName());
} catch (DoesNotExistException dnee) {
return new ResponseEntity<>(OperationResult.failure("Namespace not found."), HttpStatus.NOT_FOUND);
}
// checks any admin with an e-mail address set
Set<User> adminsWithEmail = userNamespaceRoleRepository.findAllByNamespace(target).stream().map(UserNamespaceRoles::getUser).filter(u -> !Strings.nullToEmpty(u.getEmailAddress()).trim().isEmpty()).collect(Collectors.toSet());
if (adminsWithEmail.isEmpty()) {
return new ResponseEntity<>(OperationResult.failure(String.format("None of the users administrating namespace %s has set their own e-mail. Please contact them directly. ", request.getNamespaceName())), HttpStatus.PRECONDITION_FAILED);
}
int successCount = adminsWithEmail.size();
// attempts to send the e-mails
// ugly exception handling here, due to the way this was designed in the service
Collection<IMessage> messages = adminsWithEmail.stream().map(u -> new RequestAccessToNamespaceMessage(request, u, host)).collect(Collectors.toList());
for (IMessage message : messages) {
try {
emailNotificationService.sendNotification(message);
} catch (NotificationProblem np) {
successCount--;
}
}
// worked for all recipients
if (successCount == adminsWithEmail.size()) {
return new ResponseEntity<>(OperationResult.success(), HttpStatus.OK);
} else // worked for some recipients
if (successCount > 0) {
return new ResponseEntity<>(OperationResult.success("The message could not be sent to all administrators."), HttpStatus.OK);
} else // did not work for any recipient
{
return new ResponseEntity<>(OperationResult.failure("The message could not be sent to any administrator."), HttpStatus.SERVICE_UNAVAILABLE);
}
}
use of org.springframework.beans.factory.annotation.Value in project data-prep by Talend.
the class DataSetAPI method list.
@RequestMapping(value = "/api/datasets", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "List data sets.", produces = APPLICATION_JSON_VALUE, notes = "Returns a list of data sets the user can use.")
@Timed
public Stream<DatasetDTO> list(@ApiParam(value = "Sort key (by name or date), defaults to 'date'.") @RequestParam(defaultValue = "creationDate") Sort sort, @ApiParam(value = "Order for sort key (desc or asc), defaults to 'desc'.") @RequestParam(defaultValue = "desc") Order order, @ApiParam(value = "Filter on name containing the specified name") @RequestParam(defaultValue = "") String name, @ApiParam(value = "Filter on certified data sets") @RequestParam(defaultValue = "false") boolean certified, @ApiParam(value = "Filter on favorite data sets") @RequestParam(defaultValue = "false") boolean favorite, @ApiParam(value = "Filter on recent data sets") @RequestParam(defaultValue = "false") boolean limit) {
try {
CertificationState certification = certified ? CERTIFIED : null;
Boolean filterOnFavorite = favorite ? Boolean.TRUE : null;
Stream<DatasetDTO> datasetStream = datasetClient.listDataSetMetadata(certification, filterOnFavorite);
if (isNotBlank(name)) {
datasetStream = datasetStream.filter(ds -> containsIgnoreCase(ds.getName(), name));
}
if (certified) {
datasetStream = datasetStream.filter(dataset -> dataset.getCertification() == CERTIFIED);
}
if (limit) {
datasetStream = datasetStream.limit(datasetListLimit);
}
return //
datasetStream.sorted(SortAndOrderHelper.getDatasetDTOComparator(sort, order));
} finally {
LOG.info("listing datasets done [favorite: {}, certified: {}, name: {}, limit: {}]", favorite, certified, name, limit);
}
}
use of org.springframework.beans.factory.annotation.Value in project data-prep by Talend.
the class DataSetService method get.
/**
* Returns the <b>full</b> data set content for given id.
*
* @param metadata If <code>true</code>, includes data set metadata information.
* @param dataSetId A data set id.
* @return The full data set.
*/
@RequestMapping(value = "/datasets/{id}/content", method = RequestMethod.GET)
@ApiOperation(value = "Get a data set by id", notes = "Get a data set content based on provided id. Id should be a UUID returned by the list operation. Not valid or non existing data set id returns empty content.")
@Timed
@ResponseBody
public Callable<DataSet> get(@RequestParam(defaultValue = "true") @ApiParam(name = "metadata", value = "Include metadata information in the response") boolean metadata, @RequestParam(defaultValue = "false") @ApiParam(name = "includeInternalContent", value = "Include internal content in the response") boolean includeInternalContent, //
@RequestParam(defaultValue = "-1") @ApiParam(name = STORAGE_LIMIT, value = STORAGE_LIMIT) long limit, @ApiParam(value = "Filter for retrieved content.") @RequestParam(value = "filter", defaultValue = "") String filter, @PathVariable(value = "id") @ApiParam(name = "id", value = "Id of the requested data set") String dataSetId) {
return () -> {
final Marker marker = Markers.dataset(dataSetId);
LOG.debug(marker, "Get data set #{}", dataSetId);
Stream<DataSetRow> stream = null;
try {
DataSetMetadata dataSetMetadata = dataSetMetadataRepository.get(dataSetId);
assertDataSetMetadata(dataSetMetadata, dataSetId);
// Build the result
DataSet dataSet = new DataSet();
if (metadata) {
dataSet.setMetadata(conversionService.convert(dataSetMetadata, UserDataSetMetadata.class));
}
// Disable line limit
stream = contentStore.stream(dataSetMetadata, limit);
// on-demand analyzer for dataset (See TDP-4404, migration problems)
if (dataSetMetadata.getRowMetadata().getColumns().stream().anyMatch(c -> c.getStatistics().getWordPatternFrequencyTable().isEmpty())) {
stream = insertWordPatternAnalysis(dataSetMetadata, stream);
}
if (!includeInternalContent) {
LOG.debug("Skip internal content when serving data set #{} content.", dataSetId);
stream = stream.map(r -> {
final Map<String, Object> values = r.values();
final Map<String, Object> filteredValues = new HashMap<>(values);
// Remove technical properties from returned values.
values.forEach((k, v) -> {
if (k != null && k.startsWith(FlagNames.INTERNAL_PROPERTY_PREFIX)) {
filteredValues.remove(k);
}
});
// Include TDP_ID anyway
filteredValues.put(FlagNames.TDP_ID, r.getTdpId());
return new DataSetRow(r.getRowMetadata(), filteredValues);
});
}
// Filter content
stream = stream.filter(filterService.build(filter, dataSetMetadata.getRowMetadata()));
dataSet.setRecords(stream);
return dataSet;
} catch (Exception e) {
if (stream != null) {
stream.close();
}
throw e;
} finally {
LOG.debug(marker, "Get done.");
}
};
}
Aggregations