Search in sources :

Example 66 with RequestParam

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));
}
Also used : DhisApiVersion(org.hisp.dhis.common.DhisApiVersion) PathVariable(org.springframework.web.bind.annotation.PathVariable) ContextUtils.setNoStore(org.hisp.dhis.webapi.utils.ContextUtils.setNoStore) RequestParam(org.springframework.web.bind.annotation.RequestParam) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) RequiredArgsConstructor(lombok.RequiredArgsConstructor) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) TrackerImportService(org.hisp.dhis.tracker.TrackerImportService) Deque(java.util.Deque) StreamUtils(org.hisp.dhis.commons.util.StreamUtils) ApiVersion(org.hisp.dhis.webapi.mvc.annotation.ApiVersion) CurrentUser(org.hisp.dhis.user.CurrentUser) Notifier(org.hisp.dhis.system.notification.Notifier) RequestBody(org.springframework.web.bind.annotation.RequestBody) WebMessageUtils.ok(org.hisp.dhis.dxf2.webmessage.WebMessageUtils.ok) HttpServletRequest(javax.servlet.http.HttpServletRequest) TrackerStatus(org.hisp.dhis.tracker.report.TrackerStatus) TrackerImportReportRequest(org.hisp.dhis.webapi.controller.tracker.TrackerImportReportRequest) TrackerJobWebMessageResponse(org.hisp.dhis.tracker.job.TrackerJobWebMessageResponse) JobType(org.hisp.dhis.scheduling.JobType) User(org.hisp.dhis.user.User) GetMapping(org.springframework.web.bind.annotation.GetMapping) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) TrackerBundleParams(org.hisp.dhis.webapi.controller.tracker.TrackerBundleParams) Event(org.hisp.dhis.tracker.domain.Event) ContextUtils(org.hisp.dhis.webapi.utils.ContextUtils) PostMapping(org.springframework.web.bind.annotation.PostMapping) NotFoundException(org.hisp.dhis.webapi.controller.exception.NotFoundException) ContextService(org.hisp.dhis.webapi.service.ContextService) CsvEventService(org.hisp.dhis.dxf2.events.event.csv.CsvEventService) Notification(org.hisp.dhis.system.notification.Notification) TrackerImportStrategyHandler(org.hisp.dhis.webapi.strategy.tracker.imports.TrackerImportStrategyHandler) HttpServletResponse(javax.servlet.http.HttpServletResponse) TrackerImportReport(org.hisp.dhis.tracker.report.TrackerImportReport) IOException(java.io.IOException) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RestController(org.springframework.web.bind.annotation.RestController) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) TrackerBundleReportMode(org.hisp.dhis.tracker.TrackerBundleReportMode) ParseException(org.locationtech.jts.io.ParseException) Optional(java.util.Optional) RESOURCE_PATH(org.hisp.dhis.webapi.controller.tracker.TrackerControllerSupport.RESOURCE_PATH) CodeGenerator(org.hisp.dhis.common.CodeGenerator) ResponseEntity(org.springframework.http.ResponseEntity) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) InputStream(java.io.InputStream) TrackerBundleReportMode(org.hisp.dhis.tracker.TrackerBundleReportMode) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 67 with RequestParam

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());
}
Also used : Locale(java.util.Locale) RequestParam(org.springframework.web.bind.annotation.RequestParam) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) StringWriter(java.io.StringWriter) PrintWriter(java.io.PrintWriter) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) CtMethod(org.apache.ibatis.javassist.CtMethod) Objects(java.util.Objects) MethodParameter(org.springframework.core.MethodParameter) Parameter(java.lang.reflect.Parameter) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) MockMvcRequestBuilders(org.springframework.test.web.servlet.request.MockMvcRequestBuilders) MethodParameter(org.springframework.core.MethodParameter) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap) PathVariable(org.springframework.web.bind.annotation.PathVariable)

Example 68 with RequestParam

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);
    }
}
Also used : TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH(org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) RequestParam(org.springframework.web.bind.annotation.RequestParam) DeviceInfo(org.thingsboard.server.common.data.DeviceInfo) DEVICE_INFO_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.DEVICE_INFO_DESCRIPTION) Edge(org.thingsboard.server.common.data.edge.Edge) DEVICE_WITH_DEVICE_CREDENTIALS_PARAM_DESCRIPTION_MARKDOWN(org.thingsboard.server.controller.ControllerConstants.DEVICE_WITH_DEVICE_CREDENTIALS_PARAM_DESCRIPTION_MARKDOWN) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) SORT_ORDER_ALLOWABLE_VALUES(org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_ALLOWABLE_VALUES) ApiParam(io.swagger.annotations.ApiParam) CUSTOMER_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.CUSTOMER_ID_PARAM_DESCRIPTION) TenantId(org.thingsboard.server.common.data.id.TenantId) CUSTOMER_ID(org.thingsboard.server.controller.ControllerConstants.CUSTOMER_ID) DeviceCredentialsUpdateNotificationMsg(org.thingsboard.rule.engine.api.msg.DeviceCredentialsUpdateNotificationMsg) PostMapping(org.springframework.web.bind.annotation.PostMapping) PageLink(org.thingsboard.server.common.data.page.PageLink) TENANT_AUTHORITY_PARAGRAPH(org.thingsboard.server.controller.ControllerConstants.TENANT_AUTHORITY_PARAGRAPH) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) RestController(org.springframework.web.bind.annotation.RestController) EdgeEventActionType(org.thingsboard.server.common.data.edge.EdgeEventActionType) Slf4j(lombok.extern.slf4j.Slf4j) BulkImportResult(org.thingsboard.server.service.importing.BulkImportResult) GatewayNotificationsService(org.thingsboard.server.service.gateway_device.GatewayNotificationsService) Operation(org.thingsboard.server.service.security.permission.Operation) DeviceSearchQuery(org.thingsboard.server.common.data.device.DeviceSearchQuery) TENANT_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TENANT_ID_PARAM_DESCRIPTION) TbMsg(org.thingsboard.server.common.msg.TbMsg) Device(org.thingsboard.server.common.data.Device) DEVICE_PROFILE_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.DEVICE_PROFILE_ID_PARAM_DESCRIPTION) DeferredResult(org.springframework.web.context.request.async.DeferredResult) SaveDeviceWithCredentialsRequest(org.thingsboard.server.common.data.SaveDeviceWithCredentialsRequest) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) DEVICE_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.DEVICE_ID_PARAM_DESCRIPTION) DEVICE_TEXT_SEARCH_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.DEVICE_TEXT_SEARCH_DESCRIPTION) Nullable(javax.annotation.Nullable) DataConstants(org.thingsboard.server.common.data.DataConstants) EDGE_ASSIGN_ASYNC_FIRST_STEP_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_ASSIGN_ASYNC_FIRST_STEP_DESCRIPTION) DeviceCredentials(org.thingsboard.server.common.data.security.DeviceCredentials) IOException(java.io.IOException) DEVICE_SORT_PROPERTY_ALLOWABLE_VALUES(org.thingsboard.server.controller.ControllerConstants.DEVICE_SORT_PROPERTY_ALLOWABLE_VALUES) FutureCallback(com.google.common.util.concurrent.FutureCallback) OtaPackageType(org.thingsboard.server.common.data.ota.OtaPackageType) DEVICE_TYPE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.DEVICE_TYPE_DESCRIPTION) HttpStatus(org.springframework.http.HttpStatus) Futures(com.google.common.util.concurrent.Futures) EDGE_UNASSIGN_ASYNC_FIRST_STEP_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_UNASSIGN_ASYNC_FIRST_STEP_DESCRIPTION) PageData(org.thingsboard.server.common.data.page.PageData) Resource(org.thingsboard.server.service.security.permission.Resource) PathVariable(org.springframework.web.bind.annotation.PathVariable) TimePageLink(org.thingsboard.server.common.data.page.TimePageLink) CUSTOMER_AUTHORITY_PARAGRAPH(org.thingsboard.server.controller.ControllerConstants.CUSTOMER_AUTHORITY_PARAGRAPH) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Customer(org.thingsboard.server.common.data.Customer) DeviceProfileId(org.thingsboard.server.common.data.id.DeviceProfileId) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) ClaimResponse(org.thingsboard.server.dao.device.claim.ClaimResponse) DeviceBulkImportService(org.thingsboard.server.service.device.DeviceBulkImportService) ApiOperation(io.swagger.annotations.ApiOperation) EDGE_UNASSIGN_RECEIVE_STEP_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_UNASSIGN_RECEIVE_STEP_DESCRIPTION) EntityType(org.thingsboard.server.common.data.EntityType) ReclaimResult(org.thingsboard.server.dao.device.claim.ReclaimResult) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) EdgeId(org.thingsboard.server.common.data.id.EdgeId) ClaimRequest(org.thingsboard.server.common.data.ClaimRequest) DeviceId(org.thingsboard.server.common.data.id.DeviceId) MediaType(org.springframework.http.MediaType) PAGE_DATA_PARAMETERS(org.thingsboard.server.controller.ControllerConstants.PAGE_DATA_PARAMETERS) UUID_WIKI_LINK(org.thingsboard.server.controller.ControllerConstants.UUID_WIKI_LINK) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) List(java.util.List) ClaimResult(org.thingsboard.server.dao.device.claim.ClaimResult) DEVICE_NAME_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.DEVICE_NAME_DESCRIPTION) EDGE_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_ID_PARAM_DESCRIPTION) EntitySubtype(org.thingsboard.server.common.data.EntitySubtype) SORT_ORDER_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION) PAGE_NUMBER_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.PAGE_NUMBER_DESCRIPTION) CustomerId(org.thingsboard.server.common.data.id.CustomerId) ModelConstants(org.thingsboard.server.dao.model.ModelConstants) SORT_PROPERTY_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.SORT_PROPERTY_DESCRIPTION) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Tenant(org.thingsboard.server.common.data.Tenant) ActionType(org.thingsboard.server.common.data.audit.ActionType) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) PAGE_SIZE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.PAGE_SIZE_DESCRIPTION) EDGE_ID(org.thingsboard.server.controller.EdgeController.EDGE_ID) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) BulkImportRequest(org.thingsboard.server.service.importing.BulkImportRequest) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) EDGE_ASSIGN_RECEIVE_STEP_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_ASSIGN_RECEIVE_STEP_DESCRIPTION) TbMsgDataType(org.thingsboard.server.common.msg.TbMsgDataType) ThingsboardErrorCode(org.thingsboard.server.common.data.exception.ThingsboardErrorCode) ResponseEntity(org.springframework.http.ResponseEntity) TenantId(org.thingsboard.server.common.data.id.TenantId) PageData(org.thingsboard.server.common.data.page.PageData) Device(org.thingsboard.server.common.data.Device) EdgeId(org.thingsboard.server.common.data.id.EdgeId) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) TimePageLink(org.thingsboard.server.common.data.page.TimePageLink) IOException(java.io.IOException) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 69 with RequestParam

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);
    }
}
Also used : TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH(org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) Edge(org.thingsboard.server.common.data.edge.Edge) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) TimePageLink(org.thingsboard.server.common.data.page.TimePageLink) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Customer(org.thingsboard.server.common.data.Customer) SORT_ORDER_ALLOWABLE_VALUES(org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_ALLOWABLE_VALUES) ApiParam(io.swagger.annotations.ApiParam) CUSTOMER_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.CUSTOMER_ID_PARAM_DESCRIPTION) TenantId(org.thingsboard.server.common.data.id.TenantId) ApiOperation(io.swagger.annotations.ApiOperation) EDGE_UNASSIGN_RECEIVE_STEP_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_UNASSIGN_RECEIVE_STEP_DESCRIPTION) EntityType(org.thingsboard.server.common.data.EntityType) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) EdgeId(org.thingsboard.server.common.data.id.EdgeId) PostMapping(org.springframework.web.bind.annotation.PostMapping) PageLink(org.thingsboard.server.common.data.page.PageLink) TENANT_AUTHORITY_PARAGRAPH(org.thingsboard.server.controller.ControllerConstants.TENANT_AUTHORITY_PARAGRAPH) TB_SERVICE_QUEUE(org.thingsboard.server.dao.asset.BaseAssetService.TB_SERVICE_QUEUE) MediaType(org.springframework.http.MediaType) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) PAGE_DATA_PARAMETERS(org.thingsboard.server.controller.ControllerConstants.PAGE_DATA_PARAMETERS) UUID_WIKI_LINK(org.thingsboard.server.controller.ControllerConstants.UUID_WIKI_LINK) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) EdgeEventActionType(org.thingsboard.server.common.data.edge.EdgeEventActionType) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) BulkImportResult(org.thingsboard.server.service.importing.BulkImportResult) ASSET_SORT_PROPERTY_ALLOWABLE_VALUES(org.thingsboard.server.controller.ControllerConstants.ASSET_SORT_PROPERTY_ALLOWABLE_VALUES) ASSET_TEXT_SEARCH_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ASSET_TEXT_SEARCH_DESCRIPTION) EDGE_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_ID_PARAM_DESCRIPTION) Operation(org.thingsboard.server.service.security.permission.Operation) EntitySubtype(org.thingsboard.server.common.data.EntitySubtype) SORT_ORDER_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION) PAGE_NUMBER_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.PAGE_NUMBER_DESCRIPTION) CustomerId(org.thingsboard.server.common.data.id.CustomerId) ModelConstants(org.thingsboard.server.dao.model.ModelConstants) SORT_PROPERTY_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.SORT_PROPERTY_DESCRIPTION) ASSET_TYPE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ASSET_TYPE_DESCRIPTION) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AssetId(org.thingsboard.server.common.data.id.AssetId) AssetBulkImportService(org.thingsboard.server.service.asset.AssetBulkImportService) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ASSET_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ASSET_ID_PARAM_DESCRIPTION) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) ActionType(org.thingsboard.server.common.data.audit.ActionType) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) PAGE_SIZE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.PAGE_SIZE_DESCRIPTION) EDGE_ID(org.thingsboard.server.controller.EdgeController.EDGE_ID) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) BulkImportRequest(org.thingsboard.server.service.importing.BulkImportRequest) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) EDGE_ASSIGN_ASYNC_FIRST_STEP_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_ASSIGN_ASYNC_FIRST_STEP_DESCRIPTION) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) AssetSearchQuery(org.thingsboard.server.common.data.asset.AssetSearchQuery) HttpStatus(org.springframework.http.HttpStatus) ASSET_INFO_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ASSET_INFO_DESCRIPTION) EDGE_ASSIGN_RECEIVE_STEP_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_ASSIGN_RECEIVE_STEP_DESCRIPTION) EDGE_UNASSIGN_ASYNC_FIRST_STEP_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.EDGE_UNASSIGN_ASYNC_FIRST_STEP_DESCRIPTION) AssetInfo(org.thingsboard.server.common.data.asset.AssetInfo) PageData(org.thingsboard.server.common.data.page.PageData) ASSET_NAME_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ASSET_NAME_DESCRIPTION) ThingsboardErrorCode(org.thingsboard.server.common.data.exception.ThingsboardErrorCode) Resource(org.thingsboard.server.service.security.permission.Resource) Asset(org.thingsboard.server.common.data.asset.Asset) TenantId(org.thingsboard.server.common.data.id.TenantId) PageData(org.thingsboard.server.common.data.page.PageData) EdgeId(org.thingsboard.server.common.data.id.EdgeId) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) Asset(org.thingsboard.server.common.data.asset.Asset) TimePageLink(org.thingsboard.server.common.data.page.TimePageLink) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 70 with RequestParam

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);
    }
}
Also used : DatasetDTO(org.talend.dataprep.api.dataset.DatasetDTO) PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) UpdateDataSet(org.talend.dataprep.api.service.command.dataset.UpdateDataSet) StringUtils.containsIgnoreCase(org.apache.commons.lang3.StringUtils.containsIgnoreCase) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) Autowired(org.springframework.beans.factory.annotation.Autowired) ApiParam(io.swagger.annotations.ApiParam) SetFavorite(org.talend.dataprep.api.service.command.dataset.SetFavorite) DatasetDetailsDTO(org.talend.dataprep.api.dataset.DatasetDetailsDTO) CommandHelper.toStream(org.talend.dataprep.command.CommandHelper.toStream) DatasetDTO(org.talend.dataprep.api.dataset.DatasetDTO) TEXT_PLAIN_VALUE(org.springframework.http.MediaType.TEXT_PLAIN_VALUE) CommandHelper.toStreaming(org.talend.dataprep.command.CommandHelper.toStreaming) SemanticDomain(org.talend.dataprep.api.dataset.statistics.SemanticDomain) ApiOperation(io.swagger.annotations.ApiOperation) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) DataSet(org.talend.dataprep.api.dataset.DataSet) CertificationState(org.talend.dataprep.dataset.adapter.Dataset.CertificationState) Order(org.talend.dataprep.util.SortAndOrderHelper.Order) MediaType(org.springframework.http.MediaType) UpdateColumn(org.talend.dataprep.api.service.command.dataset.UpdateColumn) PublicAPI(org.talend.dataprep.security.PublicAPI) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) DataSetPreview(org.talend.dataprep.api.service.command.dataset.DataSetPreview) List(java.util.List) HystrixCommand(com.netflix.hystrix.HystrixCommand) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) Stream(java.util.stream.Stream) GetDataSetColumnTypes(org.talend.dataprep.api.service.command.dataset.GetDataSetColumnTypes) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) PreparationList(org.talend.dataprep.api.service.command.preparation.PreparationList) CopyDataSet(org.talend.dataprep.api.service.command.dataset.CopyDataSet) GenericCommand(org.talend.dataprep.command.GenericCommand) SuggestLookupActions(org.talend.dataprep.api.service.command.transformation.SuggestLookupActions) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Callable(java.util.concurrent.Callable) CreateOrUpdateDataSet(org.talend.dataprep.api.service.command.dataset.CreateOrUpdateDataSet) SortAndOrderHelper(org.talend.dataprep.util.SortAndOrderHelper) GET(org.springframework.web.bind.annotation.RequestMethod.GET) PreparationSearchByDataSetId(org.talend.dataprep.api.service.command.preparation.PreparationSearchByDataSetId) DatasetClient(org.talend.dataprep.dataset.adapter.DatasetClient) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) CONTENT_TYPE(org.springframework.http.HttpHeaders.CONTENT_TYPE) Charset(java.nio.charset.Charset) CompatibleDataSetList(org.talend.dataprep.api.service.command.dataset.CompatibleDataSetList) POST(org.springframework.web.bind.annotation.RequestMethod.POST) DataSetGetImportParameters(org.talend.dataprep.api.service.command.dataset.DataSetGetImportParameters) DELETE(org.springframework.web.bind.annotation.RequestMethod.DELETE) CreateDataSet(org.talend.dataprep.api.service.command.dataset.CreateDataSet) Sort(org.talend.dataprep.util.SortAndOrderHelper.Sort) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) StringsHelper(org.talend.dataprep.util.StringsHelper) ActionForm(org.talend.dataprep.api.action.ActionForm) PreparationDTO(org.talend.dataprep.api.preparation.PreparationDTO) DataSetDelete(org.talend.dataprep.api.service.command.dataset.DataSetDelete) CERTIFIED(org.talend.dataprep.dataset.adapter.Dataset.CertificationState.CERTIFIED) ResponseEntity(org.springframework.http.ResponseEntity) CommandHelper(org.talend.dataprep.command.CommandHelper) EncodingSupport(org.talend.dataprep.configuration.EncodingSupport) Timed(org.talend.dataprep.metrics.Timed) InputStream(java.io.InputStream) CertificationState(org.talend.dataprep.dataset.adapter.Dataset.CertificationState) Timed(org.talend.dataprep.metrics.Timed) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

RequestParam (org.springframework.web.bind.annotation.RequestParam)72 List (java.util.List)56 PathVariable (org.springframework.web.bind.annotation.PathVariable)52 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)49 Collectors (java.util.stream.Collectors)47 IOException (java.io.IOException)37 HttpServletRequest (javax.servlet.http.HttpServletRequest)35 HttpServletResponse (javax.servlet.http.HttpServletResponse)35 Autowired (org.springframework.beans.factory.annotation.Autowired)34 HttpStatus (org.springframework.http.HttpStatus)31 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)31 Map (java.util.Map)30 GetMapping (org.springframework.web.bind.annotation.GetMapping)30 MediaType (org.springframework.http.MediaType)28 Controller (org.springframework.stereotype.Controller)28 RestController (org.springframework.web.bind.annotation.RestController)28 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)27 Set (java.util.Set)21 RequestBody (org.springframework.web.bind.annotation.RequestBody)21 ArrayList (java.util.ArrayList)20