This is an automated email from the ASF dual-hosted git repository. riemer pushed a commit to branch migrate-rest-interfaces-to-spring in repository https://gitbox.apache.org/repos/asf/streampipes.git
commit 24ba94d52c3f87fa0d525e8b80123c5a1144dd88 Author: Dominik Riemer <[email protected]> AuthorDate: Mon Dec 4 12:47:02 2023 +0100 Fix request parameters --- .../streampipes/ps/DataLakeMeasureResourceV4.java | 4 +- .../apache/streampipes/ps/DataLakeResourceV4.java | 84 +++++++++++----------- .../rest/shared/exception/SpMessageException.java | 7 ++ .../rest/impl/AdapterMonitoringResource.java | 3 +- .../streampipes/rest/impl/PipelineElementFile.java | 39 ++++++---- .../streampipes/rest/impl/PipelineTemplate.java | 40 +++++------ .../streampipes/rest/impl/ResetResource.java | 2 +- .../rest/impl/admin/DataExportResource.java | 2 +- .../impl/admin/EmailConfigurationResource.java | 7 +- .../admin/ExtensionsServiceEndpointResource.java | 6 +- .../rest/impl/admin/MigrationResource.java | 5 +- .../rest/impl/admin/PipelineElementImport.java | 7 +- .../impl/admin/ServiceConfigurationResource.java | 11 ++- .../impl/admin/ServiceRegistrationResource.java | 9 ++- .../rest/impl/admin/UserGroupResource.java | 9 ++- .../impl/dashboard/AbstractDashboardResource.java | 2 +- streampipes-service-core/pom.xml | 5 ++ .../service/core/StreamPipesCoreApplication.java | 2 +- .../service/core/WebSecurityConfig.java | 7 ++ .../core/filter/TokenAuthenticationFilter.java | 6 ++ 20 files changed, 160 insertions(+), 97 deletions(-) diff --git a/streampipes-platform-services/src/main/java/org/apache/streampipes/ps/DataLakeMeasureResourceV4.java b/streampipes-platform-services/src/main/java/org/apache/streampipes/ps/DataLakeMeasureResourceV4.java index fbe0429fc..dfae8997a 100644 --- a/streampipes-platform-services/src/main/java/org/apache/streampipes/ps/DataLakeMeasureResourceV4.java +++ b/streampipes-platform-services/src/main/java/org/apache/streampipes/ps/DataLakeMeasureResourceV4.java @@ -55,13 +55,13 @@ public class DataLakeMeasureResourceV4 extends AbstractAuthGuardedSpringRestReso produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE ) - public ResponseEntity<DataLakeMeasure> addDataLake(DataLakeMeasure dataLakeMeasure) { + public ResponseEntity<DataLakeMeasure> addDataLake(@RequestBody DataLakeMeasure dataLakeMeasure) { DataLakeMeasure result = this.dataLakeMeasureManagement.createMeasurement(dataLakeMeasure); return ok(result); } @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<Map<String, Integer>> getDataLakeInfos(@RequestParam("filter") List<String> measurementNames) { + public ResponseEntity<Map<String, Integer>> getDataLakeInfos(@RequestParam(value = "filter", required = false) List<String> measurementNames) { var allMeasurements = this.dataLakeMeasureManagement.getAllMeasurements(); return ok(new DataLakeMeasurementCount(allMeasurements, measurementNames).countMeasurementSizes()); } diff --git a/streampipes-platform-services/src/main/java/org/apache/streampipes/ps/DataLakeResourceV4.java b/streampipes-platform-services/src/main/java/org/apache/streampipes/ps/DataLakeResourceV4.java index b4dd8af82..708ef2096 100644 --- a/streampipes-platform-services/src/main/java/org/apache/streampipes/ps/DataLakeResourceV4.java +++ b/streampipes-platform-services/src/main/java/org/apache/streampipes/ps/DataLakeResourceV4.java @@ -25,8 +25,10 @@ import org.apache.streampipes.dataexplorer.query.writer.OutputFormat; import org.apache.streampipes.model.datalake.DataLakeMeasure; import org.apache.streampipes.model.datalake.DataSeries; import org.apache.streampipes.model.datalake.SpQueryResult; +import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.model.monitoring.SpLogMessage; import org.apache.streampipes.rest.core.base.impl.AbstractSpringRestResource; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -145,7 +147,7 @@ public class DataLakeResourceV4 extends AbstractSpringRestResource { } } - @GetMapping(path = "/measurements", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping(path = "/measurements/", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Get a list of all measurement series", tags = {"Data Lake"}, responses = { @ApiResponse( @@ -178,49 +180,50 @@ public class DataLakeResourceV4 extends AbstractSpringRestResource { @Parameter(in = ParameterIn.PATH, description = "the id of the measurement series", required = true) @PathVariable("measurementID") String measurementID , @Parameter(in = ParameterIn.QUERY, description = "the columns to be selected (comma-separated)") - @RequestParam(QP_COLUMNS) String columns - , @Parameter(in = ParameterIn.QUERY, description = "start date for slicing operation") @RequestParam(QP_START_DATE) - Long startDate - , @Parameter(in = ParameterIn.QUERY, description = "end date for slicing operation") @RequestParam(QP_END_DATE) - Long endDate - , @Parameter(in = ParameterIn.QUERY, description = "page number for paging operation") @RequestParam(QP_PAGE) - Integer page + @RequestParam(value = QP_COLUMNS, required = false) String columns + , @Parameter(in = ParameterIn.QUERY, description = "start date for slicing operation") + @RequestParam(value = QP_START_DATE, required = false) Long startDate + , @Parameter(in = ParameterIn.QUERY, description = "end date for slicing operation") + @RequestParam(value = QP_END_DATE, required = false) Long endDate + , @Parameter(in = ParameterIn.QUERY, description = "page number for paging operation") + @RequestParam(value = QP_PAGE, required = false) Integer page , @Parameter(in = ParameterIn.QUERY, description = "maximum number of retrieved query results") - @RequestParam(QP_LIMIT) Integer limit - , @Parameter(in = ParameterIn.QUERY, description = "offset") @RequestParam(QP_OFFSET) Integer offset + @RequestParam(value = QP_LIMIT, required = false) Integer limit + , @Parameter(in = ParameterIn.QUERY, description = "offset") + @RequestParam(value = QP_OFFSET, required = false) Integer offset , @Parameter(in = ParameterIn.QUERY, description = "grouping tags (comma-separated) for grouping operation") - @RequestParam(QP_GROUP_BY) String groupBy + @RequestParam(value = QP_GROUP_BY, required = false) String groupBy , @Parameter( in = ParameterIn.QUERY, description = "ordering of retrieved query results (ASC or DESC - default is ASC)") - @RequestParam(QP_ORDER) String order + @RequestParam(value = QP_ORDER, required = false) String order , @Parameter(in = ParameterIn.QUERY, description = "name of aggregation function used for grouping operation") - @RequestParam(QP_AGGREGATION_FUNCTION) String aggregationFunction + @RequestParam(value = QP_AGGREGATION_FUNCTION, required = false) String aggregationFunction , @Parameter( in = ParameterIn.QUERY, description = "time interval for aggregation (e.g. 1m - one minute) for grouping operation") - @RequestParam(QP_TIME_INTERVAL) String timeInterval - , @Parameter(in = ParameterIn.QUERY, description = "only return the number of results") @RequestParam(QP_COUNT_ONLY) - String countOnly + @RequestParam(value = QP_TIME_INTERVAL, required = false) String timeInterval + , @Parameter(in = ParameterIn.QUERY, description = "only return the number of results") + @RequestParam(value = QP_COUNT_ONLY, required = false) String countOnly , @Parameter(in = ParameterIn.QUERY, description = "auto-aggregate the number of results to avoid browser overload") - @RequestParam(QP_AUTO_AGGREGATE) boolean autoAggregate + @RequestParam(value = QP_AUTO_AGGREGATE, required = false) boolean autoAggregate , @Parameter( in = ParameterIn.QUERY, description = "filter conditions (a comma-separated list of filter conditions" + "such as [field,operator,condition])") - @RequestParam(QP_FILTER) String filter + @RequestParam(value = QP_FILTER, required = false) String filter , @Parameter(in = ParameterIn.QUERY, description = "missingValueBehaviour (ignore or empty)") - @RequestParam(QP_MISSING_VALUE_BEHAVIOUR) String missingValueBehaviour + @RequestParam(value = QP_MISSING_VALUE_BEHAVIOUR, required = false) String missingValueBehaviour , @Parameter( in = ParameterIn.QUERY, description = "the maximum amount of resulting events," + "when too high the query status is set to TOO_MUCH_DATA") - @RequestParam(QP_MAXIMUM_AMOUNT_OF_EVENTS) Integer maximumAmountOfResults, + @RequestParam(value = QP_MAXIMUM_AMOUNT_OF_EVENTS, required = false) Integer maximumAmountOfResults, @RequestParam Map<String, String> queryParams) { if (!(checkProvidedQueryParams(queryParams))) { @@ -260,54 +263,55 @@ public class DataLakeResourceV4 extends AbstractSpringRestResource { @ApiResponse( responseCode = "200", description = "requested data", content = @Content(schema = @Schema(implementation = DataSeries.class)))}) - public ResponseEntity<?> downloadData( + public ResponseEntity<StreamingResponseBody> downloadData( @Parameter(in = ParameterIn.PATH, description = "the id of the measurement series", required = true) @PathVariable("measurementID") String measurementID , @Parameter(in = ParameterIn.QUERY, description = "the columns to be selected (comma-separated)") - @RequestParam(QP_COLUMNS) String columns - , @Parameter(in = ParameterIn.QUERY, description = "start date for slicing operation") @RequestParam(QP_START_DATE) - Long startDate - , @Parameter(in = ParameterIn.QUERY, description = "end date for slicing operation") @RequestParam(QP_END_DATE) - Long endDate - , @Parameter(in = ParameterIn.QUERY, description = "page number for paging operation") @RequestParam(QP_PAGE) - Integer page + @RequestParam(value = QP_COLUMNS, required = false) String columns + , @Parameter(in = ParameterIn.QUERY, description = "start date for slicing operation") + @RequestParam(value = QP_START_DATE, required = false) Long startDate + , @Parameter(in = ParameterIn.QUERY, description = "end date for slicing operation") + @RequestParam(value = QP_END_DATE, required = false) Long endDate + , @Parameter(in = ParameterIn.QUERY, description = "page number for paging operation") + @RequestParam(value = QP_PAGE, required = false) Integer page , @Parameter(in = ParameterIn.QUERY, description = "maximum number of retrieved query results") - @RequestParam(QP_LIMIT) Integer limit - , @Parameter(in = ParameterIn.QUERY, description = "offset") @RequestParam(QP_OFFSET) Integer offset + @RequestParam(value = QP_LIMIT, required = false) Integer limit + , @Parameter(in = ParameterIn.QUERY, description = "offset") + @RequestParam(value = QP_OFFSET, required = false) Integer offset , @Parameter(in = ParameterIn.QUERY, description = "grouping tags (comma-separated) for grouping operation") - @RequestParam(QP_GROUP_BY) String groupBy + @RequestParam(value = QP_GROUP_BY, required = false) String groupBy , @Parameter( in = ParameterIn.QUERY, description = "ordering of retrieved query results (ASC or DESC - default is ASC)") - @RequestParam(QP_ORDER) String order + @RequestParam(value = QP_ORDER, required = false) String order , @Parameter(in = ParameterIn.QUERY, description = "name of aggregation function used for grouping operation") - @RequestParam(QP_AGGREGATION_FUNCTION) String aggregationFunction + @RequestParam(value = QP_AGGREGATION_FUNCTION, required = false) String aggregationFunction , @Parameter( in = ParameterIn.QUERY, description = "time interval for aggregation (e.g. 1m - one minute) for grouping operation") - @RequestParam(QP_TIME_INTERVAL) String timeInterval + @RequestParam(value = QP_TIME_INTERVAL, required = false) String timeInterval , @Parameter( in = ParameterIn.QUERY, description = "format specification (csv, json - default is csv) for data download") - @RequestParam(QP_FORMAT) String format + @RequestParam(value = QP_FORMAT, required = false) String format , @Parameter(in = ParameterIn.QUERY, description = "csv delimiter (comma or semicolon)") - @RequestParam(QP_CSV_DELIMITER) String csvDelimiter + @RequestParam(value = QP_CSV_DELIMITER, required = false) String csvDelimiter , @Parameter(in = ParameterIn.QUERY, description = "missingValueBehaviour (ignore or empty)") - @RequestParam(QP_MISSING_VALUE_BEHAVIOUR) String missingValueBehaviour + @RequestParam(value = QP_MISSING_VALUE_BEHAVIOUR, required = false) String missingValueBehaviour , @Parameter( in = ParameterIn.QUERY, description = "filter conditions (a comma-separated list of filter conditions" + "such as [field,operator,condition])") - @RequestParam(QP_FILTER) String filter - , @RequestParam Map<String, String> queryParams) { + @RequestParam(value = QP_FILTER, required = false) String filter, + @RequestParam Map<String, String> queryParams) { if (!(checkProvidedQueryParams(queryParams))) { - return badRequest(); + throw new SpMessageException(HttpStatus.BAD_REQUEST, Notifications.error("Wrong query parameters provided")); } else { ProvidedRestQueryParams sanitizedParams = populate(measurementID, queryParams); if (format == null) { diff --git a/streampipes-rest-shared/src/main/java/org/apache/streampipes/rest/shared/exception/SpMessageException.java b/streampipes-rest-shared/src/main/java/org/apache/streampipes/rest/shared/exception/SpMessageException.java index f2a4a9048..2ade1d068 100644 --- a/streampipes-rest-shared/src/main/java/org/apache/streampipes/rest/shared/exception/SpMessageException.java +++ b/streampipes-rest-shared/src/main/java/org/apache/streampipes/rest/shared/exception/SpMessageException.java @@ -19,6 +19,7 @@ package org.apache.streampipes.rest.shared.exception; import org.apache.streampipes.model.message.Message; +import org.apache.streampipes.model.message.Notifications; import org.springframework.http.HttpStatus; @@ -33,6 +34,12 @@ public class SpMessageException extends RuntimeException { this.message = message; } + public SpMessageException(HttpStatus status, + Throwable throwable) { + this.status = status; + this.message = Notifications.error(throwable.getMessage()); + } + public Message getSpMessage() { return message; } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AdapterMonitoringResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AdapterMonitoringResource.java index b9a0cf70e..b3d91cda6 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AdapterMonitoringResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AdapterMonitoringResource.java @@ -22,7 +22,6 @@ package org.apache.streampipes.rest.impl; import org.apache.streampipes.manager.monitoring.pipeline.ExtensionsLogProvider; import org.apache.streampipes.model.monitoring.SpLogEntry; import org.apache.streampipes.model.monitoring.SpMetricsEntry; -import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -35,7 +34,7 @@ import java.util.List; @RestController @RequestMapping("/api/v2/adapter-monitoring") -public class AdapterMonitoringResource extends AbstractAuthGuardedSpringRestResource { +public class AdapterMonitoringResource extends AbstractMonitoringResource { @GetMapping(path = "adapter/{elementId}/logs", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<SpLogEntry>> getLogInfoForAdapter(@PathVariable("elementId") String elementId) { diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementFile.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementFile.java index fe3f4d055..a6049f617 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementFile.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementFile.java @@ -19,8 +19,10 @@ package org.apache.streampipes.rest.impl; import org.apache.streampipes.manager.file.FileManager; import org.apache.streampipes.model.file.FileMetadata; +import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.apache.streampipes.rest.security.AuthConstants; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -40,21 +42,23 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; +import java.io.File; import java.io.IOException; -import java.io.InputStream; +import java.nio.file.Files; import java.util.List; @RestController @RequestMapping("/api/v2/files") public class PipelineElementFile extends AbstractAuthGuardedSpringRestResource { - @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + @PostMapping( + consumes = MediaType.MULTIPART_FORM_DATA_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize(AuthConstants.IS_ADMIN_ROLE) - public ResponseEntity<?> storeFile(@RequestPart("file_upload") InputStream uploadedInputStream, - @RequestPart("file_upload") MultipartFile fileDetail) { + public ResponseEntity<?> storeFile(@RequestPart("file_upload") MultipartFile fileDetail) { try { FileMetadata metadata = - FileManager.storeFile(getAuthenticatedUsername(), fileDetail.getName(), fileDetail.getInputStream()); + FileManager.storeFile(getAuthenticatedUsername(), fileDetail.getOriginalFilename(), fileDetail.getInputStream()); return ok(metadata); } catch (Exception e) { return fail(); @@ -70,11 +74,11 @@ public class PipelineElementFile extends AbstractAuthGuardedSpringRestResource { @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize(AuthConstants.HAS_READ_FILE_PRIVILEGE) - public ResponseEntity<List<FileMetadata>> getFileInfo(@RequestParam("filetypes") String filetypes) { + public ResponseEntity<List<FileMetadata>> getFileInfo(@RequestParam(value = "filetypes", required = false) String filetypes) { return ok(FileManager.getAllFiles(filetypes)); } - @GetMapping(path = "/{filename}", produces = MediaType.APPLICATION_JSON_VALUE) + @GetMapping(path = "/{filename}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) @Operation( summary = "Get file content by file name." + "If multiple files with the same name exist, only the first is returned." @@ -88,7 +92,7 @@ public class PipelineElementFile extends AbstractAuthGuardedSpringRestResource { description = "No file with the given file name could be found") } ) - public ResponseEntity<?> getFile( + public ResponseEntity<byte[]> getFile( @Parameter( in = ParameterIn.PATH, description = "The name of the file to be retrieved", @@ -102,13 +106,20 @@ public class PipelineElementFile extends AbstractAuthGuardedSpringRestResource { ) @RequestParam(value = "isOriginalFilename", defaultValue = "false") boolean isOriginalFilename ) { - if (isOriginalFilename) { - try { - return ok(FileManager.getFileByOriginalName(filename)); - } catch (IOException e) { - return notFound(filename); + try { + if (isOriginalFilename) { + return ok(getFileContents(FileManager.getFileByOriginalName(filename))); + } else { + return ok(getFileContents(FileManager.getFile(filename))); } + } catch (IOException e) { + throw new SpMessageException( + org.springframework.http.HttpStatus.NOT_FOUND, + Notifications.error("File not found")); } - return ok(FileManager.getFile(filename)); + } + + private byte[] getFileContents(File file) throws IOException { + return Files.readAllBytes(file.toPath()); } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineTemplate.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineTemplate.java index eac197b65..5aa650899 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineTemplate.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineTemplate.java @@ -25,7 +25,9 @@ import org.apache.streampipes.model.pipeline.PipelineOperationStatus; import org.apache.streampipes.model.template.PipelineTemplateDescription; import org.apache.streampipes.model.template.PipelineTemplateInvocation; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; +import org.apache.streampipes.rest.shared.exception.SpMessageException; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -58,29 +60,27 @@ public class PipelineTemplate extends AbstractAuthGuardedSpringRestResource { @GetMapping( path = "/invocation", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<?> getPipelineTemplateInvocation(@RequestParam("streamId") String streamId, - @RequestParam("templateId") String pipelineTemplateId) { - if (pipelineTemplateId != null) { - SpDataStream dataStream = getDataStream(streamId); - var pipelineTemplateDescriptionOpt = getPipelineTemplateDescription(pipelineTemplateId); - if (pipelineTemplateDescriptionOpt.isPresent()) { - PipelineTemplateInvocation invocation = - Operations.getPipelineInvocationTemplate(dataStream, pipelineTemplateDescriptionOpt.get()); - PipelineTemplateInvocation clonedInvocation = new PipelineTemplateInvocation(invocation); - return ok(new PipelineTemplateInvocation(clonedInvocation)); - } else { - return badRequest(Notifications.error( - String.format( - "Could not create pipeline template %s - did you install all pipeline elements?", - pipelineTemplateId.substring(pipelineTemplateId.lastIndexOf(".") + 1)) - )); - } + public ResponseEntity<PipelineTemplateInvocation> getPipelineTemplateInvocation(@RequestParam(value = "streamId", required = false) String streamId, + @RequestParam(value = "templateId") String pipelineTemplateId) { + SpDataStream dataStream = getDataStream(streamId); + var pipelineTemplateDescriptionOpt = getPipelineTemplateDescription(pipelineTemplateId); + if (pipelineTemplateDescriptionOpt.isPresent()) { + PipelineTemplateInvocation invocation = + Operations.getPipelineInvocationTemplate(dataStream, pipelineTemplateDescriptionOpt.get()); + PipelineTemplateInvocation clonedInvocation = new PipelineTemplateInvocation(invocation); + return ok(new PipelineTemplateInvocation(clonedInvocation)); } else { - return fail(); + throw new SpMessageException(HttpStatus.BAD_REQUEST, Notifications.error( + String.format( + "Could not create pipeline template %s - did you install all pipeline elements?", + pipelineTemplateId.substring(pipelineTemplateId.lastIndexOf(".") + 1)) + )); } } - @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE) + @PostMapping( + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<PipelineOperationStatus> generatePipeline( @RequestBody PipelineTemplateInvocation pipelineTemplateInvocation) { @@ -88,10 +88,8 @@ public class PipelineTemplate extends AbstractAuthGuardedSpringRestResource { .handlePipelineTemplateInvocation(getAuthenticatedUserSid(), pipelineTemplateInvocation); return ok(status); - } - private Optional<PipelineTemplateDescription> getPipelineTemplateDescription(String pipelineTemplateId) { return Operations .getAllPipelineTemplates() diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/ResetResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/ResetResource.java index 61acd2155..f41862ec3 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/ResetResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/ResetResource.java @@ -38,7 +38,7 @@ import java.util.ArrayList; @RequestMapping("/api/v2/reset") public class ResetResource extends AbstractAuthGuardedSpringRestResource { - @PostMapping(path = MediaType.APPLICATION_JSON_VALUE) + @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE) @Operation(summary = "Resets StreamPipes instance") public ResponseEntity<SuccessMessage> reset() { ResetManagement.reset(getAuthenticatedUsername()); diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/DataExportResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/DataExportResource.java index 144b3e70d..6a9bcf383 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/DataExportResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/DataExportResource.java @@ -42,7 +42,7 @@ public class DataExportResource extends AbstractAuthGuardedSpringRestResource { path = "/preview", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<?> getExportPreview(List<String> selectedAssetIds) { + public ResponseEntity<ExportConfiguration> getExportPreview(List<String> selectedAssetIds) { var exportConfig = ExportManager.getExportPreview(selectedAssetIds); return ok(exportConfig); } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/EmailConfigurationResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/EmailConfigurationResource.java index e8bbd3a44..556cdf40e 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/EmailConfigurationResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/EmailConfigurationResource.java @@ -20,11 +20,14 @@ package org.apache.streampipes.rest.impl.admin; import org.apache.streampipes.mail.MailTester; import org.apache.streampipes.model.configuration.EmailConfig; import org.apache.streampipes.model.configuration.EmailTemplateConfig; +import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.apache.streampipes.rest.security.AuthConstants; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import org.apache.streampipes.user.management.encryption.SecretEncryptionManager; import org.simplejavamail.MailException; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -85,12 +88,12 @@ public class EmailConfigurationResource extends AbstractAuthGuardedSpringRestRes @PostMapping(path = "/test", consumes = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize(AuthConstants.IS_ADMIN_ROLE) - public ResponseEntity<?> sendTestMail(@RequestBody EmailConfig config) { + public ResponseEntity<Void> sendTestMail(@RequestBody EmailConfig config) { try { new MailTester().sendTestMail(config); return ok(); } catch (MailException | IllegalArgumentException | IOException e) { - return badRequest(e); + throw new SpMessageException(HttpStatus.BAD_REQUEST, Notifications.error(e.getMessage())); } } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ExtensionsServiceEndpointResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ExtensionsServiceEndpointResource.java index a50c4b187..bfecb46c0 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ExtensionsServiceEndpointResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ExtensionsServiceEndpointResource.java @@ -29,10 +29,12 @@ import org.apache.streampipes.model.graph.DataProcessorDescription; import org.apache.streampipes.model.graph.DataSinkDescription; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.apache.streampipes.rest.security.AuthConstants; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import org.apache.streampipes.sdk.utils.Assets; import org.apache.streampipes.storage.api.IExtensionsServiceEndpointStorage; import org.apache.http.client.fluent.Request; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -99,12 +101,12 @@ public class ExtensionsServiceEndpointResource extends AbstractAuthGuardedSpring } @PostMapping(path = "/items/icon", produces = "image/png") - public ResponseEntity<?> getEndpointItemIcon(@RequestBody ExtensionsServiceEndpointItem endpointItem) { + public ResponseEntity<byte[]> getEndpointItemIcon(@RequestBody ExtensionsServiceEndpointItem endpointItem) { try { byte[] imageBytes = Request.Get(makeIconUrl(endpointItem)).execute().returnContent().asBytes(); return ok(imageBytes); } catch (IOException e) { - return fail(); + throw new SpMessageException(HttpStatus.BAD_REQUEST, e); } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/MigrationResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/MigrationResource.java index 010c39567..26f7d5c5f 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/MigrationResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/MigrationResource.java @@ -30,6 +30,7 @@ import org.apache.streampipes.model.extensions.svcdiscovery.SpServiceTagPrefix; import org.apache.streampipes.model.migration.ModelMigratorConfig; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.apache.streampipes.rest.security.AuthConstants; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import org.apache.streampipes.storage.api.CRUDStorage; import org.apache.streampipes.storage.api.IAdapterStorage; import org.apache.streampipes.storage.api.IDataProcessorStorage; @@ -86,7 +87,7 @@ public class MigrationResource extends AbstractAuthGuardedSpringRestResource { + "the corresponding actions are taken.") } ) - public ResponseEntity<?> performMigrations( + public ResponseEntity<Void> performMigrations( @Parameter( in = ParameterIn.PATH, description = "the id of the extensions service that requests migrations", @@ -136,7 +137,7 @@ public class MigrationResource extends AbstractAuthGuardedSpringRestResource { return ok(); } catch (IllegalArgumentException e) { LOG.warn("Refusing migration request since the service {} is not registered.", serviceId); - return notFound(); + throw new SpMessageException(org.springframework.http.HttpStatus.NOT_FOUND, e); } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/PipelineElementImport.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/PipelineElementImport.java index b1ce058ff..0bc37fbcd 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/PipelineElementImport.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/PipelineElementImport.java @@ -28,10 +28,13 @@ import org.apache.streampipes.model.base.NamedStreamPipesEntity; import org.apache.streampipes.model.message.Message; import org.apache.streampipes.model.message.Notification; import org.apache.streampipes.model.message.NotificationType; +import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.apache.streampipes.rest.security.AuthConstants; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import org.apache.streampipes.storage.api.IPipelineElementDescriptionStorage; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -55,7 +58,7 @@ public class PipelineElementImport extends AbstractAuthGuardedSpringRestResource @PostMapping( consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<?> addElement(@RequestBody MultiValueMap<String, String> formDataMap) { + public ResponseEntity<Message> addElement(@RequestBody MultiValueMap<String, String> formDataMap) { if (formDataMap.containsKey("uri") && formDataMap.containsKey("publicElement")) { return ok(verifyAndAddElement( formDataMap.get("uri").get(0), @@ -63,7 +66,7 @@ public class PipelineElementImport extends AbstractAuthGuardedSpringRestResource Boolean.parseBoolean(formDataMap.get("publicElement").get(0)) )); } else { - return badRequest(); + throw new SpMessageException(HttpStatus.BAD_REQUEST, Notifications.error("Invalid input")); } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ServiceConfigurationResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ServiceConfigurationResource.java index 2a906ffbc..ec3796ba0 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ServiceConfigurationResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ServiceConfigurationResource.java @@ -19,10 +19,13 @@ package org.apache.streampipes.rest.impl.admin; import org.apache.streampipes.model.extensions.configuration.SpServiceConfiguration; +import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.apache.streampipes.rest.security.AuthConstants; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import org.apache.streampipes.storage.api.CRUDStorage; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -51,9 +54,13 @@ public class ServiceConfigurationResource extends AbstractAuthGuardedSpringRestR } @GetMapping(path = "{serviceGroup}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<?> getServiceConfiguration(@PathVariable("serviceGroup") String serviceGroup) { + public ResponseEntity<SpServiceConfiguration> getServiceConfiguration(@PathVariable("serviceGroup") String serviceGroup) { var config = extensionsServicesConfigStorage.getElementById(serviceGroup); - return config != null ? ok(config) : notFound(); + if (config != null) { + return ok(config); + } else { + throw new SpMessageException(HttpStatus.NOT_FOUND, Notifications.error("Configuration not found")); + } } @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ServiceRegistrationResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ServiceRegistrationResource.java index 26b5a6cd7..7872912c6 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ServiceRegistrationResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ServiceRegistrationResource.java @@ -21,12 +21,15 @@ package org.apache.streampipes.rest.impl.admin; import org.apache.streampipes.manager.health.ServiceRegistrationManager; import org.apache.streampipes.model.extensions.svcdiscovery.SpServiceRegistration; import org.apache.streampipes.model.extensions.svcdiscovery.SpServiceStatus; +import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.apache.streampipes.rest.security.AuthConstants; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import org.apache.streampipes.storage.api.CRUDStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -62,12 +65,14 @@ public class ServiceRegistrationResource extends AbstractAuthGuardedSpringRestRe } @PostMapping(path = "/{serviceId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity<?> unregisterService(@PathVariable("serviceId") String serviceId) { + public ResponseEntity<Void> unregisterService(@PathVariable("serviceId") String serviceId) { try { new ServiceRegistrationManager(extensionsServiceStorage).removeService(serviceId); return ok(); } catch (IllegalArgumentException e) { - return badRequest("Could not find registered service with id " + serviceId); + throw new SpMessageException( + HttpStatus.BAD_REQUEST, + Notifications.error("Could not find registered service with id " + serviceId)); } } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/UserGroupResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/UserGroupResource.java index ca0cc7023..68ec26b59 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/UserGroupResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/UserGroupResource.java @@ -18,10 +18,13 @@ package org.apache.streampipes.rest.impl.admin; import org.apache.streampipes.model.client.user.Group; +import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedSpringRestResource; import org.apache.streampipes.rest.security.AuthConstants; +import org.apache.streampipes.rest.shared.exception.SpMessageException; import org.apache.streampipes.storage.api.IUserGroupStorage; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -55,10 +58,12 @@ public class UserGroupResource extends AbstractAuthGuardedSpringRestResource { @PutMapping(path = "{groupId}", consumes = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize(AuthConstants.IS_ADMIN_ROLE) - public ResponseEntity<?> updateUserGroup(@PathVariable("groupId") String groupId, + public ResponseEntity<Group> updateUserGroup(@PathVariable("groupId") String groupId, @RequestBody Group group) { if (!groupId.equals(group.getGroupId())) { - return badRequest(); + throw new SpMessageException( + HttpStatus.BAD_REQUEST, + Notifications.error("Wrong group id provided")); } else { return ok(getUserGroupStorage().updateElement(group)); } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/AbstractDashboardResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/AbstractDashboardResource.java index cef3f53bd..d9b909d52 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/AbstractDashboardResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/AbstractDashboardResource.java @@ -66,7 +66,7 @@ public abstract class AbstractDashboardResource extends AbstractAuthGuardedSprin @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("this.hasWriteAuthority()") - public ResponseEntity<Void> createDashboard(DashboardModel dashboardModel) { + public ResponseEntity<Void> createDashboard(@RequestBody DashboardModel dashboardModel) { getResourceManager().create(dashboardModel, getAuthenticatedUserSid()); return ok(); } diff --git a/streampipes-service-core/pom.xml b/streampipes-service-core/pom.xml index 09023a1d6..e29167a95 100644 --- a/streampipes-service-core/pom.xml +++ b/streampipes-service-core/pom.xml @@ -94,6 +94,11 @@ <artifactId>streampipes-platform-services</artifactId> <version>0.95.0-SNAPSHOT</version> </dependency> + <dependency> + <groupId>org.springframework.security</groupId> + <artifactId>spring-security-web</artifactId> + <version>6.1.2</version> + </dependency> <!-- External dependencies --> <dependency> <groupId>io.swagger.core.v3</groupId> diff --git a/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/StreamPipesCoreApplication.java b/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/StreamPipesCoreApplication.java index 05d4bfaab..b8310076f 100644 --- a/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/StreamPipesCoreApplication.java +++ b/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/StreamPipesCoreApplication.java @@ -70,7 +70,7 @@ import java.util.concurrent.TimeUnit; SpPermissionEvaluator.class, StreamPipesPrometheusConfig.class }) -@ComponentScan({"org.apache.streampipes.rest.*"}) +@ComponentScan({"org.apache.streampipes.rest.*", "org.apache.streampipes.ps"}) public class StreamPipesCoreApplication extends StreamPipesServiceBase { private static final Logger LOG = LoggerFactory.getLogger(StreamPipesCoreApplication.class.getCanonicalName()); diff --git a/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/WebSecurityConfig.java b/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/WebSecurityConfig.java index 214b21b9d..88ae5e694 100644 --- a/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/WebSecurityConfig.java +++ b/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/WebSecurityConfig.java @@ -36,6 +36,7 @@ import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @@ -99,4 +100,10 @@ public class WebSecurityConfig { return authConfig.getAuthenticationManager(); } + @Bean + public RequestAttributeSecurityContextRepository getRequestAttributeSecurityContextRepository() { + return new RequestAttributeSecurityContextRepository(); + } + + } diff --git a/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/filter/TokenAuthenticationFilter.java b/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/filter/TokenAuthenticationFilter.java index e389f4afb..e6a327a87 100644 --- a/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/filter/TokenAuthenticationFilter.java +++ b/streampipes-service-core/src/main/java/org/apache/streampipes/service/core/filter/TokenAuthenticationFilter.java @@ -34,8 +34,10 @@ import org.apache.streampipes.user.management.util.TokenUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -51,6 +53,8 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter { private final JwtTokenProvider tokenProvider; private final IUserStorage userStorage; + private RequestAttributeSecurityContextRepository repo = new RequestAttributeSecurityContextRepository(); + private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class); public TokenAuthenticationFilter() { @@ -68,6 +72,8 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter { if (StringUtils.hasText(jwt) && tokenProvider.validateJwtToken(jwt)) { String username = tokenProvider.getUserIdFromToken(jwt); applySuccessfulAuth(request, username); + SecurityContext context = SecurityContextHolder.getContext(); + repo.saveContext(context, request, response); } else { String apiKey = getApiKeyFromRequest(request); String apiUser = getApiUserFromRequest(request);
