use of org.springframework.web.bind.annotation.PathVariable in project thingsboard by thingsboard.
the class TelemetryController method getTimeseries.
@ApiOperation(value = "Get time-series data (getTimeseries)", notes = "Returns a range of time-series values for specified entity. " + "Returns not aggregated data by default. " + "Use aggregation function ('agg') and aggregation interval ('interval') to enable aggregation of the results on the database / server side. " + "The aggregation is generally more efficient then fetching all records. \n\n" + MARKDOWN_CODE_BLOCK_START + TS_STRICT_DATA_EXAMPLE + MARKDOWN_CODE_BLOCK_END + "\n\n" + INVALID_ENTITY_ID_OR_ENTITY_TYPE_DESCRIPTION + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/{entityType}/{entityId}/values/timeseries", method = RequestMethod.GET, params = { "keys", "startTs", "endTs" })
@ResponseBody
public DeferredResult<ResponseEntity> getTimeseries(@ApiParam(value = ENTITY_TYPE_PARAM_DESCRIPTION, required = true, defaultValue = "DEVICE") @PathVariable("entityType") String entityType, @ApiParam(value = ENTITY_ID_PARAM_DESCRIPTION, required = true) @PathVariable("entityId") String entityIdStr, @ApiParam(value = TELEMETRY_KEYS_BASE_DESCRIPTION, required = true) @RequestParam(name = "keys") String keys, @ApiParam(value = "A long value representing the start timestamp of the time range in milliseconds, UTC.") @RequestParam(name = "startTs") Long startTs, @ApiParam(value = "A long value representing the end timestamp of the time range in milliseconds, UTC.") @RequestParam(name = "endTs") Long endTs, @ApiParam(value = "A long value representing the aggregation interval range in milliseconds.") @RequestParam(name = "interval", defaultValue = "0") Long interval, @ApiParam(value = "An integer value that represents a max number of timeseries data points to fetch." + " This parameter is used only in the case if 'agg' parameter is set to 'NONE'.", defaultValue = "100") @RequestParam(name = "limit", defaultValue = "100") Integer limit, @ApiParam(value = "A string value representing the aggregation function. " + "If the interval is not specified, 'agg' parameter will use 'NONE' value.", allowableValues = "MIN, MAX, AVG, SUM, COUNT, NONE") @RequestParam(name = "agg", defaultValue = "NONE") String aggStr, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(name = "orderBy", defaultValue = "DESC") String orderBy, @ApiParam(value = STRICT_DATA_TYPES_DESCRIPTION) @RequestParam(name = "useStrictDataTypes", required = false, defaultValue = "false") Boolean useStrictDataTypes) throws ThingsboardException {
try {
return accessValidator.validateEntityAndCallback(getCurrentUser(), Operation.READ_TELEMETRY, entityType, entityIdStr, (result, tenantId, entityId) -> {
// If interval is 0, convert this to a NONE aggregation, which is probably what the user really wanted
Aggregation agg = interval == 0L ? Aggregation.valueOf(Aggregation.NONE.name()) : Aggregation.valueOf(aggStr);
List<ReadTsKvQuery> queries = toKeysList(keys).stream().map(key -> new BaseReadTsKvQuery(key, startTs, endTs, interval, limit, agg, orderBy)).collect(Collectors.toList());
Futures.addCallback(tsService.findAll(tenantId, entityId, queries), getTsKvListCallback(result, useStrictDataTypes), MoreExecutors.directExecutor());
});
} catch (Exception e) {
throw handleException(e);
}
}
use of org.springframework.web.bind.annotation.PathVariable in project thingsboard by thingsboard.
the class EntityViewController method getEdgeEntityViews.
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/edge/{edgeId}/entityViews", params = { "pageSize", "page" }, method = RequestMethod.GET)
@ResponseBody
public PageData<EntityView> getEdgeEntityViews(@PathVariable(EDGE_ID) String strEdgeId, @RequestParam int pageSize, @RequestParam int page, @RequestParam(required = false) String type, @RequestParam(required = false) String textSearch, @RequestParam(required = false) String sortProperty, @RequestParam(required = false) String sortOrder, @RequestParam(required = false) Long startTime, @RequestParam(required = false) Long endTime) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
try {
TenantId tenantId = getCurrentUser().getTenantId();
EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
checkEdgeId(edgeId, Operation.READ);
TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
PageData<EntityView> nonFilteredResult;
if (type != null && type.trim().length() > 0) {
nonFilteredResult = entityViewService.findEntityViewsByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
} else {
nonFilteredResult = entityViewService.findEntityViewsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
}
List<EntityView> filteredEntityViews = nonFilteredResult.getData().stream().filter(entityView -> {
try {
accessControlService.checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.READ, entityView.getId(), entityView);
return true;
} catch (ThingsboardException e) {
return false;
}
}).collect(Collectors.toList());
PageData<EntityView> filteredResult = new PageData<>(filteredEntityViews, nonFilteredResult.getTotalPages(), nonFilteredResult.getTotalElements(), nonFilteredResult.hasNext());
return checkNotNull(filteredResult);
} catch (Exception e) {
throw handleException(e);
}
}
use of org.springframework.web.bind.annotation.PathVariable in project thingsboard by thingsboard.
the class DashboardController method getEdgeDashboards.
@ApiOperation(value = "Get Edge Dashboards (getEdgeDashboards)", notes = "Returns a page of dashboard info objects assigned to the specified edge. " + DASHBOARD_INFO_DEFINITION + " " + PAGE_DATA_PARAMETERS + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/edge/{edgeId}/dashboards", params = { "pageSize", "page" }, method = RequestMethod.GET)
@ResponseBody
public PageData<DashboardInfo> getEdgeDashboards(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @ApiParam(value = DASHBOARD_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = DASHBOARD_SORT_PROPERTY_ALLOWABLE_VALUES) @RequestParam(required = false) String sortProperty, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("edgeId", strEdgeId);
try {
TenantId tenantId = getCurrentUser().getTenantId();
EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
checkEdgeId(edgeId, Operation.READ);
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
PageData<DashboardInfo> nonFilteredResult = dashboardService.findDashboardsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
List<DashboardInfo> filteredDashboards = nonFilteredResult.getData().stream().filter(dashboardInfo -> {
try {
accessControlService.checkPermission(getCurrentUser(), Resource.DASHBOARD, Operation.READ, dashboardInfo.getId(), dashboardInfo);
return true;
} catch (ThingsboardException e) {
return false;
}
}).collect(Collectors.toList());
PageData<DashboardInfo> filteredResult = new PageData<>(filteredDashboards, nonFilteredResult.getTotalPages(), nonFilteredResult.getTotalElements(), nonFilteredResult.hasNext());
return checkNotNull(filteredResult);
} catch (Exception e) {
throw handleException(e);
}
}
use of org.springframework.web.bind.annotation.PathVariable in project dhis2-core by dhis2.
the class AbstractCrudController method getCollectionItem.
//--------------------------------------------------------------------------
// Identifiable object collections add, delete
//--------------------------------------------------------------------------
@RequestMapping(value = "/{uid}/{property}/{itemId}", method = RequestMethod.GET)
@ResponseBody
public RootNode getCollectionItem(@PathVariable("uid") String pvUid, @PathVariable("property") String pvProperty, @PathVariable("itemId") String pvItemId, @RequestParam Map<String, String> parameters, TranslateParams translateParams, HttpServletRequest request, HttpServletResponse response) throws Exception {
User user = currentUserService.getCurrentUser();
setUserContext(user, translateParams);
if (!aclService.canRead(user, getEntityClass())) {
throw new ReadAccessDeniedException("You don't have the proper permissions to read objects of this type.");
}
RootNode rootNode = getObjectInternal(pvUid, parameters, Lists.newArrayList(), Lists.newArrayList(pvProperty + "[:all]"), user);
// TODO optimize this using field filter (collection filtering)
if (!rootNode.getChildren().isEmpty() && rootNode.getChildren().get(0).isCollection()) {
rootNode.getChildren().get(0).getChildren().stream().filter(Node::isComplex).forEach(node -> {
node.getChildren().stream().filter(child -> child.isSimple() && child.getName().equals("id") && !((SimpleNode) child).getValue().equals(pvItemId)).forEach(child -> rootNode.getChildren().get(0).removeChild(node));
});
}
if (rootNode.getChildren().isEmpty() || rootNode.getChildren().get(0).getChildren().isEmpty()) {
throw new WebMessageException(WebMessageUtils.notFound(pvProperty + " with ID " + pvItemId + " could not be found."));
}
return rootNode;
}
use of org.springframework.web.bind.annotation.PathVariable in project alf.io by alfio-event.
the class MvcConfiguration method getEventLocaleSetterInterceptor.
@Bean
public HandlerInterceptor getEventLocaleSetterInterceptor() {
return new HandlerInterceptorAdapter() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = ((HandlerMethod) handler);
RequestMapping reqMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
// check if the request mapping value has the form "/event/{something}"
Pattern eventPattern = Pattern.compile("^/event/\\{(\\w+)}/{0,1}.*");
if (reqMapping != null && reqMapping.value().length == 1 && eventPattern.matcher(reqMapping.value()[0]).matches()) {
Matcher m = eventPattern.matcher(reqMapping.value()[0]);
m.matches();
String pathVariableName = m.group(1);
// extract the parameter name
Arrays.stream(handlerMethod.getMethodParameters()).map(methodParameter -> methodParameter.getParameterAnnotation(PathVariable.class)).filter(Objects::nonNull).map(PathVariable::value).filter(pathVariableName::equals).findFirst().ifPresent((val) -> {
// fetch the parameter value
@SuppressWarnings("unchecked") String eventName = Optional.ofNullable(((Map<String, Object>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE)).get(val)).orElse("").toString();
LocaleResolver resolver = RequestContextUtils.getLocaleResolver(request);
Locale locale = resolver.resolveLocale(request);
List<ContentLanguage> cl = i18nManager.getEventLanguages(eventName);
request.setAttribute("ALFIO_EVENT_NAME", eventName);
if (cl.stream().noneMatch(contentLanguage -> contentLanguage.getLanguage().equals(Optional.ofNullable(locale).orElse(Locale.ENGLISH).getLanguage()))) {
// override the user locale if it's not in the one permitted by the event
resolver.setLocale(request, response, cl.stream().findFirst().map(ContentLanguage::getLocale).orElse(Locale.ENGLISH));
} else {
resolver.setLocale(request, response, locale);
}
});
}
}
return true;
}
};
}
Aggregations