use of org.springframework.web.bind.annotation.RequestParam in project mica2 by obiba.
the class CompareController method get.
@GetMapping("/compare")
public ModelAndView get(@RequestParam(required = false) String type, @RequestParam(required = false) String ids, @RequestParam(required = false) String query) {
Subject subject = SecurityUtils.getSubject();
MicaConfig config = micaConfigService.getConfig();
String documentType = Strings.isNullOrEmpty(type) ? "studies" : type.toLowerCase();
Set<String> documentIds = Sets.newTreeSet();
List<Study> individualStudies = Lists.newArrayList();
List<HarmonizationStudy> harmonizationStudies = Lists.newArrayList();
List<Network> networks = Lists.newArrayList();
String searchQuery = "";
Map<String, Object> params = newParameters();
if (!Strings.isNullOrEmpty(ids))
documentIds.addAll(Splitter.on(",").splitToList(ids));
if (!Strings.isNullOrEmpty(query)) {
if ("studies".equals(documentType) && config.isStudiesCompareEnabled()) {
documentIds.addAll(queryStudyIds(query));
} else if ("networks".equals(documentType) && config.isStudiesCompareEnabled()) {
documentIds.addAll(queryNetworkIds(query));
}
}
if (documentIds.isEmpty() && subject.isAuthenticated()) {
if ("studies".equals(documentType)) {
documentIds.addAll(studySetService.getCartCurrentUser().getIdentifiers());
} else if ("networks".equals(documentType)) {
documentIds.addAll(networkSetService.getCartCurrentUser().getIdentifiers());
}
}
params.put("type", documentType);
params.put("ids", documentIds);
if (!documentIds.isEmpty()) {
if ("studies".equals(documentType) && config.isStudiesCompareEnabled()) {
List<BaseStudy> studies = publishedStudyService.findByIds(Lists.newArrayList(documentIds).subList(0, Math.min(documentIds.size(), config.getMaxItemsPerCompare())));
individualStudies = studies.stream().filter(study -> study instanceof Study).map(study -> (Study) study).collect(Collectors.toList());
harmonizationStudies = studies.stream().filter(study -> study instanceof HarmonizationStudy).map(study -> (HarmonizationStudy) study).collect(Collectors.toList());
searchQuery = String.format("study(in(Mica_study.id,(%s)))", Joiner.on(",").join(documentIds));
} else if ("networks".equals(documentType) && config.isNetworksCompareEnabled()) {
networks = publishedNetworkService.findByIds(Lists.newArrayList(documentIds).subList(0, Math.min(documentIds.size(), config.getMaxItemsPerCompare())));
searchQuery = String.format("network(in(Mica_network.id,(%s)))", Joiner.on(",").join(documentIds));
}
}
params.put("individualStudies", individualStudies);
params.put("harmonizationStudies", harmonizationStudies);
params.put("networks", networks);
params.put("query", searchQuery);
return new ModelAndView("compare", params);
}
use of org.springframework.web.bind.annotation.RequestParam in project data-prep by Talend.
the class FolderService method list.
/**
* Get folders. If parentId is supplied, it will be used as filter.
*
* @param parentId the parent folder id parameter
* @return direct sub folders for the given id.
*/
// @formatter:off
@RequestMapping(value = "/folders", method = GET)
@ApiOperation(value = "List children folders of the parameter if null list root children.", notes = "List all child folders of the one as parameter")
@Timed
public Stream<Folder> list(@RequestParam(required = false) @ApiParam(value = "Parent id filter.") String parentId, @RequestParam(defaultValue = "lastModificationDate") @ApiParam(value = "Sort key (by name or date).") Sort sort, @RequestParam(defaultValue = "desc") @ApiParam(value = "Order for sort key (desc or asc).") Order order) {
// @formatter:on
Stream<Folder> children;
if (parentId != null) {
if (!folderRepository.exists(parentId)) {
throw new TDPException(FOLDER_NOT_FOUND, build().put("id", parentId));
}
children = folderRepository.children(parentId);
} else {
// This will list all folders
children = folderRepository.searchFolders("", false);
}
final AtomicInteger folderCount = new AtomicInteger();
// update the number of preparations in each children
children = children.peek(f -> {
final long count = folderRepository.count(f.getId(), PREPARATION);
f.setNbPreparations(count);
folderCount.addAndGet(1);
});
LOGGER.info("Found {} children for parentId: {}", folderCount.get(), parentId);
// sort the folders
return children.sorted(getFolderComparator(sort, order));
}
use of org.springframework.web.bind.annotation.RequestParam in project data-prep by Talend.
the class DataSetService method preview.
/**
* Returns preview of the the data set content for given id (first 100 rows). Service might return
* {@link org.apache.http.HttpStatus#SC_ACCEPTED} if the data set exists but analysis is not yet fully
* completed so content is not yet ready to be served.
*
* @param metadata If <code>true</code>, includes data set metadata information.
* @param sheetName the sheet name to preview
* @param dataSetId A data set id.
*/
@RequestMapping(value = "/datasets/{id}/preview", method = RequestMethod.GET)
@ApiOperation(value = "Get a data preview set by id", notes = "Get a data set preview content based on provided id. Not valid or non existing data set id returns empty content. Data set not in drat status will return a redirect 301")
@Timed
@ResponseBody
public DataSet preview(@RequestParam(defaultValue = "true") @ApiParam(name = "metadata", value = "Include metadata information in the response") boolean metadata, @RequestParam(defaultValue = "") @ApiParam(name = "sheetName", value = "Sheet name to preview") String sheetName, @PathVariable(value = "id") @ApiParam(name = "id", value = "Id of the requested data set") String dataSetId) {
DataSetMetadata dataSetMetadata = dataSetMetadataRepository.get(dataSetId);
if (dataSetMetadata == null) {
HttpResponseContext.status(HttpStatus.NO_CONTENT);
// No data set, returns empty content.
return DataSet.empty();
}
if (!dataSetMetadata.isDraft()) {
// Moved to get data set content operation
HttpResponseContext.status(HttpStatus.MOVED_PERMANENTLY);
HttpResponseContext.header("Location", "/datasets/" + dataSetId + "/content");
// dataset not anymore a draft so preview doesn't make sense.
return DataSet.empty();
}
if (StringUtils.isNotEmpty(sheetName)) {
dataSetMetadata.setSheetName(sheetName);
}
// take care of previous data without schema parser result
if (dataSetMetadata.getSchemaParserResult() != null) {
// sheet not yet set correctly so use the first one
if (StringUtils.isEmpty(dataSetMetadata.getSheetName())) {
String theSheetName = dataSetMetadata.getSchemaParserResult().getSheetContents().get(0).getName();
LOG.debug("preview for dataSetMetadata: {} with sheetName: {}", dataSetId, theSheetName);
dataSetMetadata.setSheetName(theSheetName);
}
String theSheetName = dataSetMetadata.getSheetName();
Optional<Schema.SheetContent> sheetContentFound = dataSetMetadata.getSchemaParserResult().getSheetContents().stream().filter(//
sheetContent -> theSheetName.equals(sheetContent.getName())).findFirst();
if (!sheetContentFound.isPresent()) {
HttpResponseContext.status(HttpStatus.NO_CONTENT);
// No sheet found, returns empty content.
return DataSet.empty();
}
List<ColumnMetadata> columnMetadatas = sheetContentFound.get().getColumnMetadatas();
if (dataSetMetadata.getRowMetadata() == null) {
dataSetMetadata.setRowMetadata(new RowMetadata(emptyList()));
}
dataSetMetadata.getRowMetadata().setColumns(columnMetadatas);
} else {
LOG.warn("dataset#{} has draft status but any SchemaParserResult", dataSetId);
}
// Build the result
DataSet dataSet = new DataSet();
if (metadata) {
dataSet.setMetadata(conversionService.convert(dataSetMetadata, UserDataSetMetadata.class));
}
dataSet.setRecords(contentStore.stream(dataSetMetadata).limit(100));
return dataSet;
}
use of org.springframework.web.bind.annotation.RequestParam 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.RequestParam 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);
}
}
Aggregations