use of org.springframework.web.bind.annotation.RequestParam in project dhis2-core by dhis2.
the class TrackerImportController method getJobReport.
@GetMapping(value = "/jobs/{uid}/report", produces = APPLICATION_JSON_VALUE)
public TrackerImportReport getJobReport(@PathVariable String uid, @RequestParam(defaultValue = "errors", required = false) String reportMode, HttpServletResponse response) throws HttpStatusCodeException, NotFoundException {
TrackerBundleReportMode trackerBundleReportMode = TrackerBundleReportMode.getTrackerBundleReportMode(reportMode);
setNoStore(response);
return Optional.ofNullable(notifier.getJobSummaryByJobId(JobType.TRACKER_IMPORT_JOB, uid)).map(report -> trackerImportService.buildImportReport((TrackerImportReport) report, trackerBundleReportMode)).orElseThrow(() -> NotFoundException.notFoundUid(uid));
}
use of org.springframework.web.bind.annotation.RequestParam in project judge by zjnu-acm.
the class MockGenerator method generate.
private void generate(Class<?> key, RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod, String url, TestClass testClass, String lowerMethod) {
Method method = handlerMethod.getMethod();
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
out.println("/**");
out.println(" * Test of " + method.getName() + " method, of class " + key.getSimpleName() + ".");
for (Class<?> type : method.getParameterTypes()) {
testClass.addImport(type);
}
out.println(" *");
out.println(" * {@link " + key.getSimpleName() + "#" + method.getName() + Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName).collect(Collectors.joining(", ", "(", ")}")));
out.println(" */");
testClass.addImport(Test.class);
out.println("@Test");
out.println("public void test" + StringUtils.capitalize(method.getName()) + "() throws Exception {");
out.println("\tlog.info(\"" + method.getName() + "\");");
List<String> variableDeclares = new ArrayList<>(4);
Map<String, Class<?>> params = new LinkedHashMap<>(4);
String body = null;
Class<?> bodyType = null;
MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
Parameter[] parameters = method.getParameters();
List<String> files = new ArrayList<>(4);
List<String> pathVariables = new ArrayList<>(4);
Map<String, String> headers = Maps.newTreeMap();
String locale = null;
for (MethodParameter methodParameter : methodParameters) {
Class<?> type = methodParameter.getParameterType();
String typeName = type.getSimpleName();
String name = "";
testClass.addImport(type);
boolean unknown = false;
RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
PathVariable pathVariable = methodParameter.getParameterAnnotation(PathVariable.class);
RequestHeader requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class);
if (requestParam != null) {
name = requestParam.value();
if (name.isEmpty()) {
name = requestParam.name();
}
} else if (pathVariable != null) {
name = pathVariable.value();
if (name.isEmpty()) {
name = pathVariable.name();
}
if (name.isEmpty()) {
name = parameters[methodParameter.getParameterIndex()].getName();
}
pathVariables.add(name);
variableDeclares.add("\t" + typeName + " " + name + " = " + getDefaultValue(type) + ";");
continue;
} else if (methodParameter.hasParameterAnnotation(RequestBody.class)) {
body = "request";
bodyType = type;
variableDeclares.add("\t" + typeName + " request = " + getDefaultValue(type) + ";");
continue;
} else if (requestHeader != null) {
name = requestHeader.value();
if (name.isEmpty()) {
name = requestHeader.name();
}
if (name.isEmpty()) {
name = parameters[methodParameter.getParameterIndex()].getName();
}
String camelCase = camelCase(name);
headers.put(name, camelCase);
variableDeclares.add("\t" + typeName + " " + camelCase + " = " + getDefaultValue(type) + ";");
continue;
} else if (HttpServletResponse.class == type || HttpServletRequest.class == type) {
continue;
} else if (Locale.class == type) {
locale = "locale";
variableDeclares.add("\t" + typeName + " " + locale + " = Locale.getDefault();");
continue;
} else {
unknown = true;
}
if (name.isEmpty()) {
name = parameters[methodParameter.getParameterIndex()].getName();
}
if (unknown && type.getClassLoader() != null && type != MultipartFile.class) {
ReflectionUtils.doWithFields(type, field -> process(field.getName(), camelCase(field.getName()), field.getType(), params, files, variableDeclares, testClass, method, lowerMethod), field -> !Modifier.isStatic(field.getModifiers()));
continue;
} else if (unknown) {
System.err.println("param " + methodParameter.getParameterIndex() + " with type " + typeName + " in " + method + " has no annotation");
}
process(name, camelCase(name), type, params, files, variableDeclares, testClass, method, lowerMethod);
}
for (String variableDeclare : variableDeclares) {
out.println(variableDeclare);
}
testClass.addImport(MvcResult.class);
if (files.isEmpty()) {
testClass.addStaticImport(MockMvcRequestBuilders.class, lowerMethod);
out.print("\tMvcResult result = mvc.perform(" + lowerMethod + "(" + url);
for (String pathVariable : pathVariables) {
out.print(", " + pathVariable);
}
out.print(")");
} else {
String methodName = "multipart";
if (!ClassUtils.hasMethod(MockMvcRequestBuilders.class, "multipart", String.class, String[].class)) {
methodName = "fileUpload";
}
testClass.addStaticImport(MockMvcRequestBuilders.class, methodName);
out.print("\tMvcResult result = mvc.perform(" + methodName + "(" + url);
for (String pathVariable : pathVariables) {
out.print(", " + pathVariable);
}
out.print(")");
for (String file : files) {
out.print(".file(" + file + ")");
}
}
boolean newLine = params.size() >= 2;
for (Map.Entry<String, Class<?>> entry : params.entrySet()) {
String paramName = entry.getKey();
String variableName = camelCase(paramName);
Class<?> paramType = entry.getValue();
String value;
if (paramType.isPrimitive()) {
value = com.google.common.primitives.Primitives.wrap(paramType).getSimpleName() + ".toString(" + variableName + ")";
} else if (paramType == String.class) {
value = variableName;
} else {
testClass.addImport(Objects.class);
value = "Objects.toString(" + variableName + ", \"\")";
}
if (newLine) {
out.println();
out.print("\t\t\t");
}
out.print(".param(\"" + paramName + "\", " + value + ")");
}
for (Map.Entry<String, String> entry : headers.entrySet()) {
out.println();
out.print("\t\t\t.header(\"" + entry.getKey() + "\", " + entry.getValue() + ")");
}
if (locale != null) {
out.println();
out.print("\t\t\t.locale(" + locale + ")");
}
switch(lowerMethod) {
case "get":
case "delete":
if (body != null) {
System.err.println("RequestBody annotation found on " + method + " with request method " + lowerMethod);
}
if (!requestMappingInfo.getConsumesCondition().isEmpty()) {
System.err.println("request consumes " + requestMappingInfo.getConsumesCondition() + " found on " + method);
}
}
if (body != null) {
out.println();
if (bodyType == String.class || bodyType == byte[].class) {
out.print("\t\t\t.content(" + body + ")");
} else {
testClass.addField(ObjectMapper.class, "objectMapper", "@Autowired");
out.print("\t\t\t.content(objectMapper.writeValueAsString(" + body + "))");
}
testClass.addImport(MediaType.class);
out.print(".contentType(MediaType.APPLICATION_JSON)");
}
testClass.addStaticImport(MockMvcResultMatchers.class, "status");
out.println(")");
out.println("\t\t\t.andExpect(status().isOk())");
out.println("\t\t\t.andReturn();");
out.println("}");
testClass.addMethod(sw.toString());
}
use of org.springframework.web.bind.annotation.RequestParam in project thingsboard by thingsboard.
the class DeviceController method getEdgeDevices.
@ApiOperation(value = "Get devices assigned to edge (getEdgeDevices)", notes = "Returns a page of devices assigned to edge. " + PAGE_DATA_PARAMETERS + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/edge/{edgeId}/devices", params = { "pageSize", "page" }, method = RequestMethod.GET)
@ResponseBody
public PageData<Device> getEdgeDevices(@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 = DEVICE_TYPE_DESCRIPTION) @RequestParam(required = false) String type, @ApiParam(value = DEVICE_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = DEVICE_SORT_PROPERTY_ALLOWABLE_VALUES) @RequestParam(required = false) String sortProperty, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder, @ApiParam(value = "Timestamp. Devices with creation time before it won't be queried") @RequestParam(required = false) Long startTime, @ApiParam(value = "Timestamp. Devices with creation time after it won't be queried") @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<Device> nonFilteredResult;
if (type != null && type.trim().length() > 0) {
nonFilteredResult = deviceService.findDevicesByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
} else {
nonFilteredResult = deviceService.findDevicesByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
}
List<Device> filteredDevices = nonFilteredResult.getData().stream().filter(device -> {
try {
accessControlService.checkPermission(getCurrentUser(), Resource.DEVICE, Operation.READ, device.getId(), device);
return true;
} catch (ThingsboardException e) {
return false;
}
}).collect(Collectors.toList());
PageData<Device> filteredResult = new PageData<>(filteredDevices, nonFilteredResult.getTotalPages(), nonFilteredResult.getTotalElements(), nonFilteredResult.hasNext());
return checkNotNull(filteredResult);
} catch (Exception e) {
throw handleException(e);
}
}
use of org.springframework.web.bind.annotation.RequestParam in project thingsboard by thingsboard.
the class AssetController method getEdgeAssets.
@ApiOperation(value = "Get assets assigned to edge (getEdgeAssets)", notes = "Returns a page of assets assigned to edge. " + PAGE_DATA_PARAMETERS, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/edge/{edgeId}/assets", params = { "pageSize", "page" }, method = RequestMethod.GET)
@ResponseBody
public PageData<Asset> getEdgeAssets(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = PAGE_SIZE_DESCRIPTION) @RequestParam int pageSize, @ApiParam(value = PAGE_NUMBER_DESCRIPTION) @RequestParam int page, @ApiParam(value = ASSET_TYPE_DESCRIPTION) @RequestParam(required = false) String type, @ApiParam(value = ASSET_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = ASSET_SORT_PROPERTY_ALLOWABLE_VALUES) @RequestParam(required = false) String sortProperty, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder, @ApiParam(value = "Timestamp. Assets with creation time before it won't be queried") @RequestParam(required = false) Long startTime, @ApiParam(value = "Timestamp. Assets with creation time after it won't be queried") @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<Asset> nonFilteredResult;
if (type != null && type.trim().length() > 0) {
nonFilteredResult = assetService.findAssetsByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
} else {
nonFilteredResult = assetService.findAssetsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
}
List<Asset> filteredAssets = nonFilteredResult.getData().stream().filter(asset -> {
try {
accessControlService.checkPermission(getCurrentUser(), Resource.ASSET, Operation.READ, asset.getId(), asset);
return true;
} catch (ThingsboardException e) {
return false;
}
}).collect(Collectors.toList());
PageData<Asset> filteredResult = new PageData<>(filteredAssets, nonFilteredResult.getTotalPages(), nonFilteredResult.getTotalElements(), nonFilteredResult.hasNext());
return checkNotNull(filteredResult);
} catch (Exception e) {
throw handleException(e);
}
}
use of org.springframework.web.bind.annotation.RequestParam 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);
}
}
Aggregations