Browse Source

Merge pull request #16561 from vvlladd28/fix/openapi-response-types

Fixed REST API documentation of paging parameters, alarm assignment, entity alias filters and error codes
pull/16608/head
Viacheslav Klimov 4 weeks ago
committed by GitHub
parent
commit
eebd997b5a
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 46
      application/src/main/java/org/thingsboard/server/config/SwaggerConfiguration.java
  2. 12
      application/src/main/java/org/thingsboard/server/controller/AlarmController.java
  3. 2
      application/src/main/java/org/thingsboard/server/controller/EdgeController.java
  4. 23
      common/data/src/main/java/org/thingsboard/server/common/data/query/AliasEntityId.java
  5. 55
      common/data/src/test/java/org/thingsboard/server/common/data/query/AliasEntityIdTest.java

46
application/src/main/java/org/thingsboard/server/config/SwaggerConfiguration.java

@ -37,6 +37,7 @@ import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springdoc.core.customizers.ParameterCustomizer;
import org.springdoc.core.discoverer.SpringDocParameterNameDiscoverer;
import org.springdoc.core.models.GroupedOpenApi;
import org.springdoc.core.properties.SpringDocConfigProperties;
@ -49,11 +50,14 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.util.ClassUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.ai.model.chat.AiChatModelConfig;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.query.AliasEntityType;
import org.thingsboard.server.exception.ThingsboardCredentialsExpiredResponse;
import org.thingsboard.server.exception.ThingsboardErrorResponse;
import org.thingsboard.server.service.security.auth.rest.LoginRequest;
@ -292,6 +296,38 @@ public class SwaggerConfiguration {
.build();
}
// springdoc infers the parameter type from the Java type only when @Parameter(schema = @Schema(...))
// sets neither type nor implementation; otherwise (e.g. schema = @Schema(minimum = "1")) it falls back
// to "string". Restore integer/int32 or integer/int64 for int and long parameters, keeping the rest of the schema.
@Bean
public ParameterCustomizer integerParameterCustomizer() {
return (parameter, methodParameter) -> {
if (parameter == null || parameter.getSchema() == null) {
return parameter;
}
Schema<?> schema = parameter.getSchema();
boolean isString = "string".equals(schema.getType()) || Set.of("string").equals(schema.getTypes());
String format = integerFormat(methodParameter);
if (isString && format != null && schema.getFormat() == null) {
schema.setType("integer");
schema.setTypes(Set.of("integer"));
schema.setFormat(format);
}
return parameter;
};
}
private static String integerFormat(MethodParameter methodParameter) {
Class<?> type = ClassUtils.resolvePrimitiveIfNecessary(methodParameter.getParameterType());
if (Integer.class.equals(type)) {
return "int32";
}
if (Long.class.equals(type)) {
return "int64";
}
return null;
}
@Bean
@Lazy(false)
ModelConverter mapAwareConverter() {
@ -362,9 +398,11 @@ public class SwaggerConfiguration {
};
}
// The document is OpenAPI 3.1 (see springDocProperties above), which serializes
// Schema.types; a schema built with Schema.type(...) is written without a type.
private void addDefaultSchemas(OpenAPI openAPI) {
Schema<?> errorCodeSchema = new Schema<>()
.type("integer")
.types(Set.of("integer"))
.description("Platform error code")
._enum(Arrays.stream(ThingsboardErrorCode.values())
.map(ThingsboardErrorCode::getErrorCode)
@ -375,6 +413,12 @@ public class SwaggerConfiguration {
registerSchema(components, "ThingsboardErrorResponse", ThingsboardErrorResponse.class);
registerSchema(components, "ThingsboardCredentialsExpiredResponse", ThingsboardCredentialsExpiredResponse.class);
components.addSchemas("ThingsboardErrorCode", errorCodeSchema);
// AliasEntityId.entityType is a plain string, so no schema references AliasEntityType;
// register it to keep the alias names in the spec and in generated clients.
components.addSchemas("AliasEntityType", new Schema<String>()
.types(Set.of("string"))
.description("Alias for an entity of the current user, used as AliasEntityId.entityType")
._enum(Arrays.stream(AliasEntityType.values()).map(Enum::name).toList()));
registerSchema(components, "AiChatModelConfig", AiChatModelConfig.class);
}

12
application/src/main/java/org/thingsboard/server/controller/AlarmController.java

@ -191,10 +191,10 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/alarm/{alarmId}/assign/{assigneeId}")
@ResponseStatus(value = HttpStatus.OK)
public Alarm assignAlarm(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION)
@PathVariable(ALARM_ID) String strAlarmId,
@Parameter(description = ASSIGN_ID_PARAM_DESCRIPTION)
@PathVariable(ASSIGNEE_ID) String strAssigneeId
public AlarmInfo assignAlarm(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION)
@PathVariable(ALARM_ID) String strAlarmId,
@Parameter(description = ASSIGN_ID_PARAM_DESCRIPTION)
@PathVariable(ASSIGNEE_ID) String strAssigneeId
) throws Exception {
checkParameter(ALARM_ID, strAlarmId);
checkParameter(ASSIGNEE_ID, strAssigneeId);
@ -212,8 +212,8 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@DeleteMapping(value = "/alarm/{alarmId}/assign")
@ResponseStatus(value = HttpStatus.OK)
public Alarm unassignAlarm(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION)
@PathVariable(ALARM_ID) String strAlarmId
public AlarmInfo unassignAlarm(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION)
@PathVariable(ALARM_ID) String strAlarmId
) throws Exception {
checkParameter(ALARM_ID, strAlarmId);
AlarmId alarmId = new AlarmId(toUUID(strAlarmId));

2
application/src/main/java/org/thingsboard/server/controller/EdgeController.java

@ -546,7 +546,7 @@ public class EdgeController extends BaseController {
@PathVariable(ENTITY_GROUP_ID) String strEntityGroupId,
@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true, schema = @Schema(minimum = "1"))
@RequestParam int pageSize,
@Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true, schema = @Schema(minimum = "1"))
@Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true, schema = @Schema(minimum = "0"))
@RequestParam int page,
@Parameter(description = EDGE_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch,

23
common/data/src/main/java/org/thingsboard/server/common/data/query/AliasEntityId.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.common.data.query;
import com.fasterxml.jackson.annotation.JsonIgnore;
@ -11,11 +12,31 @@ import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import java.util.UUID;
@JsonDeserialize(using = AliasEntityIdDeserializer.class)
@JsonSerialize(using = AliasEntityIdSerializer.class)
@Schema
public interface AliasEntityId extends EntityId {
// The schema follows AliasEntityIdSerializer/AliasEntityIdDeserializer rather
// than the getters: entityType carries either an EntityType or an
// AliasEntityType name, id is only required for an EntityType, and
// aliasEntityType is never written.
@Override
@Schema(implementation = String.class, requiredMode = Schema.RequiredMode.REQUIRED,
description = "Entity type: an EntityType value, or an AliasEntityType value resolved for the current user",
example = "DEVICE")
EntityType getEntityType();
@Override
@Schema(requiredMode = Schema.RequiredMode.NOT_REQUIRED,
description = "ID of the entity, time-based UUID v1. Required for an entity type; for " +
"CURRENT_CUSTOMER, the customer used when the current user does not belong to one",
example = "784f394c-42b6-435a-983c-b7beff2784f9")
UUID getId();
@Schema(hidden = true)
AliasEntityType getAliasEntityType();
EntityId defaultEntityId();

55
common/data/src/test/java/org/thingsboard/server/common/data/query/AliasEntityIdTest.java

@ -0,0 +1,55 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.common.data.query;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
// The OpenAPI schema of AliasEntityId describes this wire format, not the getters:
// entityType holds an EntityType or an AliasEntityType name, and id is optional for an alias.
class AliasEntityIdTest {
private static final ObjectMapper mapper = new ObjectMapper();
private static final UUID ID = UUID.fromString("784f394c-42b6-435a-983c-b7beff2784f9");
@Test
void entityIdRoundTrip() throws Exception {
AliasEntityId entityId = AliasEntityId.fromEntityId(new DeviceId(ID));
String json = mapper.writeValueAsString(entityId);
assertThat(mapper.readTree(json)).isEqualTo(mapper.readTree("{\"entityType\":\"DEVICE\",\"id\":\"" + ID + "\"}"));
AliasEntityId parsed = mapper.readValue(json, AliasEntityId.class);
assertThat(parsed.isAliasEntityId()).isFalse();
assertThat(parsed.getEntityType()).isEqualTo(EntityType.DEVICE);
assertThat(parsed.getId()).isEqualTo(ID);
}
@Test
void aliasWithoutIdRoundTrip() throws Exception {
String json = mapper.writeValueAsString(new AliasEntityIdImpl(AliasEntityType.CURRENT_USER, null));
assertThat(mapper.readTree(json)).isEqualTo(mapper.readTree("{\"entityType\":\"CURRENT_USER\"}"));
AliasEntityId parsed = mapper.readValue(json, AliasEntityId.class);
assertThat(parsed.getAliasEntityType()).isEqualTo(AliasEntityType.CURRENT_USER);
assertThat(parsed.getId()).isNull();
}
@Test
void currentCustomerAliasCarriesDefaultCustomerId() throws Exception {
String json = mapper.writeValueAsString(new AliasEntityIdImpl(AliasEntityType.CURRENT_CUSTOMER, ID));
assertThat(mapper.readTree(json)).isEqualTo(mapper.readTree("{\"entityType\":\"CURRENT_CUSTOMER\",\"id\":\"" + ID + "\"}"));
AliasEntityId parsed = mapper.readValue(json, AliasEntityId.class);
assertThat(parsed.getAliasEntityType()).isEqualTo(AliasEntityType.CURRENT_CUSTOMER);
assertThat(parsed.defaultEntityId()).isEqualTo(new CustomerId(ID));
}
}
Loading…
Cancel
Save