From 7f2a8be8846928febbf4a456814c02c27e6c9b11 Mon Sep 17 00:00:00 2001 From: Philipp Zehnder Date: Thu, 1 Dec 2022 13:27:17 +0100 Subject: [PATCH 01/10] Enable checkstyle for streampipes-rest (#820) --- streampipes-rest/pom.xml | 22 ++ .../streampipes/rest/ResetManagement.java | 175 ++++++------ .../rest/api/IPipelineElement.java | 36 --- .../rest/api/IPipelineMonitoring.java | 29 -- .../filter/TokenAuthenticationFilter.java | 132 ++++----- .../rest/impl/AccountActivationResource.java | 6 +- .../rest/impl/AssetDashboardResource.java | 14 +- .../rest/impl/AssetManagementResource.java | 13 +- .../streampipes/rest/impl/Authentication.java | 19 +- .../streampipes/rest/impl/AutoComplete.java | 12 +- .../rest/impl/CategoryResource.java | 146 +++++----- .../streampipes/rest/impl/EmailResource.java | 3 +- .../rest/impl/FunctionsResource.java | 9 +- .../rest/impl/GenericStorageResource.java | 159 ++++++----- .../streampipes/rest/impl/LabelResource.java | 198 ++++++------- .../rest/impl/MeasurementUnitResource.java | 26 +- .../streampipes/rest/impl/Notification.java | 134 ++++----- .../rest/impl/OntologyMeasurementUnit.java | 52 ++-- .../streampipes/rest/impl/PipelineCache.java | 6 +- .../impl/PipelineCanvasMetadataCache.java | 8 +- .../impl/PipelineCanvasMetadataResource.java | 15 +- .../rest/impl/PipelineCategory.java | 78 ++--- .../rest/impl/PipelineElementAsset.java | 4 +- .../rest/impl/PipelineElementCategory.java | 71 ++--- .../rest/impl/PipelineElementFile.java | 14 +- .../rest/impl/PipelineElementPreview.java | 8 +- .../rest/impl/PipelineElementRuntimeInfo.java | 3 +- .../rest/impl/PipelineMonitoring.java | 5 +- .../rest/impl/PipelineResource.java | 17 +- .../rest/impl/PipelineTemplate.java | 44 +-- .../streampipes/rest/impl/ResetResource.java | 23 +- .../rest/impl/RestorePasswordResource.java | 8 +- .../apache/streampipes/rest/impl/Setup.java | 4 +- .../streampipes/rest/impl/UserResource.java | 53 ++-- .../rest/impl/admin/ConsulConfig.java | 26 +- .../rest/impl/admin/DataExportResource.java | 6 +- .../rest/impl/admin/DataImportResource.java | 7 +- .../admin/EmailConfigurationResource.java | 9 +- .../ExtensionsServiceEndpointResource.java | 57 ++-- .../admin/GeneralConfigurationResource.java | 12 +- .../rest/impl/admin/PermissionResource.java | 2 + .../impl/admin/PipelineElementImport.java | 16 +- .../rest/impl/admin/UserGroupResource.java | 8 +- .../rest/impl/connect/AdapterResource.java | 1 + .../impl/connect/DescriptionResource.java | 267 +++++++++--------- .../rest/impl/connect/GuessResource.java | 26 +- .../connect/RuntimeResolvableResource.java | 63 +++-- .../rest/impl/connect/SourcesResource.java | 67 +++-- .../rest/impl/connect/UnitResource.java | 35 +-- .../rest/impl/connect/WelcomePageMaster.java | 98 +++---- .../connect/WorkerAdministrationResource.java | 23 +- .../dashboard/AbstractDashboardResource.java | 10 +- .../AbstractPipelineExtractionResource.java | 49 ++-- .../rest/impl/dashboard/Dashboard.java | 41 ++- .../rest/impl/dashboard/DashboardWidget.java | 9 +- .../VisualizablePipelineResource.java | 10 +- .../datalake/DataLakeDashboardResource.java | 40 +-- .../impl/datalake/DataLakeWidgetResource.java | 9 +- .../datalake/PersistedDataStreamResource.java | 5 +- .../nouser/PipelineElementImportNoUser.java | 10 +- .../rest/impl/pe/DataProcessorResource.java | 86 +++--- .../rest/impl/pe/DataSinkResource.java | 8 +- .../rest/security/AuthConstants.java | 93 ++++-- .../rest/security/SpPermissionEvaluator.java | 13 +- .../v4/params/WhereStatementParamsTest.java | 68 ++--- 65 files changed, 1505 insertions(+), 1215 deletions(-) delete mode 100644 streampipes-rest/src/main/java/org/apache/streampipes/rest/api/IPipelineElement.java delete mode 100644 streampipes-rest/src/main/java/org/apache/streampipes/rest/api/IPipelineMonitoring.java diff --git a/streampipes-rest/pom.xml b/streampipes-rest/pom.xml index 4daa8622af..c8545d7dd0 100644 --- a/streampipes-rest/pom.xml +++ b/streampipes-rest/pom.xml @@ -163,4 +163,26 @@ test + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + validate + validate + + check + + + + + true + true + + + + diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/ResetManagement.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/ResetManagement.java index faa8bf4229..2b5b724686 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/ResetManagement.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/ResetManagement.java @@ -25,106 +25,111 @@ import org.apache.streampipes.manager.pipeline.PipelineCacheManager; import org.apache.streampipes.manager.pipeline.PipelineCanvasMetadataCacheManager; import org.apache.streampipes.manager.pipeline.PipelineManager; -import org.apache.streampipes.resource.management.UserResourceManager; -import org.apache.streampipes.model.file.FileMetadata; import org.apache.streampipes.model.connect.adapter.AdapterDescription; import org.apache.streampipes.model.datalake.DataLakeMeasure; +import org.apache.streampipes.model.file.FileMetadata; import org.apache.streampipes.model.pipeline.Pipeline; +import org.apache.streampipes.resource.management.UserResourceManager; import org.apache.streampipes.storage.api.IDashboardStorage; import org.apache.streampipes.storage.api.IDashboardWidgetStorage; import org.apache.streampipes.storage.api.IDataExplorerWidgetStorage; import org.apache.streampipes.storage.management.StorageDispatcher; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class ResetManagement { - // This class should be moved into another package. I moved it here because I got a cyclic maven - // dependency between this package and streampipes-pipeline-management - // See in issue [STREAMPIPES-405] - - private static final Logger logger = LoggerFactory.getLogger(ResetManagement.class); - - /** - * Remove all configurations for this user. This includes: - * [pipeline assembly cache, pipelines, adapters, files] - * @param username - */ - public static void reset(String username) { - logger.info("Start resetting the system"); - - // Set hide tutorial to false for user - UserResourceManager.setHideTutorial(username, true); - - // Clear pipeline assembly Cache - PipelineCacheManager.removeCachedPipeline(username); - PipelineCanvasMetadataCacheManager.removeCanvasMetadataFromCache(username); - - // Stop and delete all pipelines - List allPipelines = PipelineManager.getAllPipelines(); - allPipelines.forEach(pipeline -> { - PipelineManager.stopPipeline(pipeline.getPipelineId(), true); - PipelineManager.deletePipeline(pipeline.getPipelineId()); - }); - - // Stop and delete all adapters - AdapterMasterManagement adapterMasterManagement = new AdapterMasterManagement(); - + // This class should be moved into another package. I moved it here because I got a cyclic maven + // dependency between this package and streampipes-pipeline-management + // See in issue [STREAMPIPES-405] + + private static final Logger logger = LoggerFactory.getLogger(ResetManagement.class); + + /** + * Remove all configurations for this user. This includes: + * [pipeline assembly cache, pipelines, adapters, files] + * + * @param username + */ + public static void reset(String username) { + logger.info("Start resetting the system"); + + // Set hide tutorial to false for user + UserResourceManager.setHideTutorial(username, true); + + // Clear pipeline assembly Cache + PipelineCacheManager.removeCachedPipeline(username); + PipelineCanvasMetadataCacheManager.removeCanvasMetadataFromCache(username); + + // Stop and delete all pipelines + List allPipelines = PipelineManager.getAllPipelines(); + allPipelines.forEach(pipeline -> { + PipelineManager.stopPipeline(pipeline.getPipelineId(), true); + PipelineManager.deletePipeline(pipeline.getPipelineId()); + }); + + // Stop and delete all adapters + AdapterMasterManagement adapterMasterManagement = new AdapterMasterManagement(); + + try { + List allAdapters = adapterMasterManagement.getAllAdapterInstances(); + allAdapters.forEach(adapterDescription -> { try { - List allAdapters = adapterMasterManagement.getAllAdapterInstances(); - allAdapters.forEach(adapterDescription -> { - try { - adapterMasterManagement.deleteAdapter(adapterDescription.getElementId()); - } catch (AdapterException e) { - logger.error("Failed to delete adapter with id: " + adapterDescription.getElementId(), e); - } - }); + adapterMasterManagement.deleteAdapter(adapterDescription.getElementId()); } catch (AdapterException e) { - logger.error("Failed to load all adapter descriptions", e); + logger.error("Failed to delete adapter with id: " + adapterDescription.getElementId(), e); } - - // Stop and delete all files - List allFiles = FileManager.getAllFiles(); - allFiles.forEach(fileMetadata -> { - FileManager.deleteFile(fileMetadata.getFileId()); - }); - - // Remove all data in data lake - DataLakeManagementV4 dataLakeManagementV4 = new DataLakeManagementV4(); - List allMeasurements = dataLakeManagementV4.getAllMeasurements(); - allMeasurements.forEach(measurement -> { - boolean isSuccessDataLake = dataLakeManagementV4.removeMeasurement(measurement.getMeasureName()); - - if (isSuccessDataLake) { - dataLakeManagementV4.removeEventProperty(measurement.getMeasureName()); - } - }); - - // Remove all data views widgets - IDataExplorerWidgetStorage widgetStorage = StorageDispatcher.INSTANCE.getNoSqlStore().getDataExplorerWidgetStorage(); - widgetStorage.getAllDataExplorerWidgets().forEach(widget -> { - widgetStorage.deleteDataExplorerWidget(widget.getId()); - }); - - // Remove all data views - IDashboardStorage dataLakeDashboardStorage = StorageDispatcher.INSTANCE.getNoSqlStore().getDataExplorerDashboardStorage(); - dataLakeDashboardStorage.getAllDashboards().forEach(dashboard -> { - dataLakeDashboardStorage.deleteDashboard(dashboard.getCouchDbId()); - }); - - // Remove all dashboard widgets - IDashboardWidgetStorage dashobardWidgetStorage = StorageDispatcher.INSTANCE.getNoSqlStore().getDashboardWidgetStorage(); - dashobardWidgetStorage.getAllDashboardWidgets().forEach(widget -> { - dashobardWidgetStorage.deleteDashboardWidget(widget.getId()); - }); - - // Remove all dashboards - IDashboardStorage dashboardStorage = StorageDispatcher.INSTANCE.getNoSqlStore().getDashboardStorage(); - dashboardStorage.getAllDashboards().forEach(dashboard -> { - dashboardStorage.deleteDashboard(dashboard.getCouchDbId()); - }); - - logger.info("Resetting the system was completed"); + }); + } catch (AdapterException e) { + logger.error("Failed to load all adapter descriptions", e); } + + // Stop and delete all files + List allFiles = FileManager.getAllFiles(); + allFiles.forEach(fileMetadata -> { + FileManager.deleteFile(fileMetadata.getFileId()); + }); + + // Remove all data in data lake + DataLakeManagementV4 dataLakeManagementV4 = new DataLakeManagementV4(); + List allMeasurements = dataLakeManagementV4.getAllMeasurements(); + allMeasurements.forEach(measurement -> { + boolean isSuccessDataLake = dataLakeManagementV4.removeMeasurement(measurement.getMeasureName()); + + if (isSuccessDataLake) { + dataLakeManagementV4.removeEventProperty(measurement.getMeasureName()); + } + }); + + // Remove all data views widgets + IDataExplorerWidgetStorage widgetStorage = + StorageDispatcher.INSTANCE.getNoSqlStore().getDataExplorerWidgetStorage(); + widgetStorage.getAllDataExplorerWidgets().forEach(widget -> { + widgetStorage.deleteDataExplorerWidget(widget.getId()); + }); + + // Remove all data views + IDashboardStorage dataLakeDashboardStorage = + StorageDispatcher.INSTANCE.getNoSqlStore().getDataExplorerDashboardStorage(); + dataLakeDashboardStorage.getAllDashboards().forEach(dashboard -> { + dataLakeDashboardStorage.deleteDashboard(dashboard.getCouchDbId()); + }); + + // Remove all dashboard widgets + IDashboardWidgetStorage dashobardWidgetStorage = + StorageDispatcher.INSTANCE.getNoSqlStore().getDashboardWidgetStorage(); + dashobardWidgetStorage.getAllDashboardWidgets().forEach(widget -> { + dashobardWidgetStorage.deleteDashboardWidget(widget.getId()); + }); + + // Remove all dashboards + IDashboardStorage dashboardStorage = StorageDispatcher.INSTANCE.getNoSqlStore().getDashboardStorage(); + dashboardStorage.getAllDashboards().forEach(dashboard -> { + dashboardStorage.deleteDashboard(dashboard.getCouchDbId()); + }); + + logger.info("Resetting the system was completed"); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/IPipelineElement.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/IPipelineElement.java deleted file mode 100644 index 01cf383eee..0000000000 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/IPipelineElement.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.apache.streampipes.rest.api; - - -import org.apache.streampipes.model.base.NamedStreamPipesEntity; - -import javax.ws.rs.core.Response; - -public interface IPipelineElement { - - Response getAvailable(); - Response getOwn(); - - Response removeOwn(String elementUri); - - Response getElement(String elementUri); - - -} diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/IPipelineMonitoring.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/IPipelineMonitoring.java deleted file mode 100644 index 7c81afd5a3..0000000000 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/IPipelineMonitoring.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.streampipes.rest.api; - -import javax.ws.rs.core.Response; - -public interface IPipelineMonitoring { - - Response getLogInfoForPipeline(String pipelineId); - - Response getMetricsInfoForPipeline(String pipelineId); - - Response triggerMonitoringUpdate(); -} diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/filter/TokenAuthenticationFilter.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/filter/TokenAuthenticationFilter.java index 2a1cd9b77a..42b890b902 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/filter/TokenAuthenticationFilter.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/filter/TokenAuthenticationFilter.java @@ -30,6 +30,7 @@ import org.apache.streampipes.user.management.model.UserAccountDetails; import org.apache.streampipes.user.management.service.TokenService; import org.apache.streampipes.user.management.util.TokenUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -42,72 +43,75 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import java.io.IOException; public class TokenAuthenticationFilter extends OncePerRequestFilter { - private final JwtTokenProvider tokenProvider; - private final IUserStorage userStorage; - - private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class); - - public TokenAuthenticationFilter() { - this.tokenProvider = new JwtTokenProvider(); - this.userStorage = StorageDispatcher.INSTANCE.getNoSqlStore().getUserStorageAPI(); - } - - @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain) throws ServletException, IOException { - try { - String jwt = getJwtFromRequest(request); - - if (StringUtils.hasText(jwt) && tokenProvider.validateJwtToken(jwt)) { - String username = tokenProvider.getUserIdFromToken(jwt); - applySuccessfulAuth(request, username); - } else { - String apiKey = getApiKeyFromRequest(request); - String apiUser = getApiUserFromRequest(request); - if (StringUtils.hasText(apiKey) && StringUtils.hasText(apiUser)) { - String hashedToken = TokenUtil.hashToken(apiKey); - boolean hasValidToken = new TokenService().hasValidToken(apiUser, hashedToken); - if (hasValidToken) { - applySuccessfulAuth(request, apiUser); - } - } - } - } catch (Exception ex) { - logger.error("Could not set user authentication in security context", ex); - } - - filterChain.doFilter(request, response); - } - - private void applySuccessfulAuth(HttpServletRequest request, - String username) { - Principal user = userStorage.getUser(username); - PrincipalUserDetails userDetails = user instanceof UserAccount ? new UserAccountDetails((UserAccount) user) : new ServiceAccountDetails((ServiceAccount) user); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - - SecurityContextHolder.getContext().setAuthentication(authentication); - } - - - private String getJwtFromRequest(HttpServletRequest request) { - String bearerToken = request.getHeader(HttpConstants.AUTHORIZATION); - if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(HttpConstants.BEARER)) { - return bearerToken.substring(7); - } - return null; - } - - private String getApiKeyFromRequest(HttpServletRequest request) { - return request.getHeader(HttpConstants.X_API_KEY); - } - - private String getApiUserFromRequest(HttpServletRequest request) { - return request.getHeader(HttpConstants.X_API_USER); - } + private final JwtTokenProvider tokenProvider; + private final IUserStorage userStorage; + + private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class); + + public TokenAuthenticationFilter() { + this.tokenProvider = new JwtTokenProvider(); + this.userStorage = StorageDispatcher.INSTANCE.getNoSqlStore().getUserStorageAPI(); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, + HttpServletResponse response, + FilterChain filterChain) throws ServletException, IOException { + try { + String jwt = getJwtFromRequest(request); + + if (StringUtils.hasText(jwt) && tokenProvider.validateJwtToken(jwt)) { + String username = tokenProvider.getUserIdFromToken(jwt); + applySuccessfulAuth(request, username); + } else { + String apiKey = getApiKeyFromRequest(request); + String apiUser = getApiUserFromRequest(request); + if (StringUtils.hasText(apiKey) && StringUtils.hasText(apiUser)) { + String hashedToken = TokenUtil.hashToken(apiKey); + boolean hasValidToken = new TokenService().hasValidToken(apiUser, hashedToken); + if (hasValidToken) { + applySuccessfulAuth(request, apiUser); + } + } + } + } catch (Exception ex) { + logger.error("Could not set user authentication in security context", ex); + } + + filterChain.doFilter(request, response); + } + + private void applySuccessfulAuth(HttpServletRequest request, + String username) { + Principal user = userStorage.getUser(username); + PrincipalUserDetails userDetails = user instanceof UserAccount ? new UserAccountDetails((UserAccount) user) : + new ServiceAccountDetails((ServiceAccount) user); + UsernamePasswordAuthenticationToken authentication = + new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + + private String getJwtFromRequest(HttpServletRequest request) { + String bearerToken = request.getHeader(HttpConstants.AUTHORIZATION); + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(HttpConstants.BEARER)) { + return bearerToken.substring(7); + } + return null; + } + + private String getApiKeyFromRequest(HttpServletRequest request) { + return request.getHeader(HttpConstants.X_API_KEY); + } + + private String getApiUserFromRequest(HttpServletRequest request) { + return request.getHeader(HttpConstants.X_API_USER); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AccountActivationResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AccountActivationResource.java index 5215dd0370..9737178455 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AccountActivationResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AccountActivationResource.java @@ -20,7 +20,11 @@ import org.apache.streampipes.commons.exceptions.UserNotFoundException; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AssetDashboardResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AssetDashboardResource.java index 5fa37a7921..9c4f5acf85 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AssetDashboardResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AssetDashboardResource.java @@ -17,17 +17,25 @@ */ package org.apache.streampipes.rest.impl; -import org.apache.commons.io.FileUtils; import org.apache.streampipes.model.client.assetdashboard.AssetDashboardConfig; import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; import org.apache.streampipes.storage.api.IAssetDashboardStorage; import org.apache.streampipes.storage.management.StorageDispatcher; + +import org.apache.commons.io.FileUtils; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -119,7 +127,7 @@ public Response storeDashboardImage(@FormDataParam("file_upload") InputStream up private String getTargetDirectory() { return System.getProperty("user.home") + File.separator + ".streampipes" - + File.separator + "assets" + File.separator + APP_ID; + + File.separator + "assets" + File.separator + APP_ID; } private String getTargetFile(String filename) { diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AssetManagementResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AssetManagementResource.java index bbbc0a8bf7..6d42cac697 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AssetManagementResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AssetManagementResource.java @@ -22,14 +22,23 @@ import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.storage.api.IGenericStorage; import org.apache.streampipes.storage.management.StorageDispatcher; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; import java.util.List; import java.util.Map; @@ -47,7 +56,7 @@ public class AssetManagementResource extends AbstractAuthGuardedRestResource { @Produces(MediaType.APPLICATION_JSON) @PreAuthorize(AuthConstants.HAS_READ_ASSETS_PRIVILEGE) public List> getAll() throws IOException { - return getGenericStorage().findAll(APP_DOC_TYPE); + return getGenericStorage().findAll(APP_DOC_TYPE); } @POST diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Authentication.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Authentication.java index 679257c963..d385365249 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Authentication.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Authentication.java @@ -22,7 +22,11 @@ import org.apache.streampipes.commons.exceptions.UsernameAlreadyTakenException; import org.apache.streampipes.config.backend.BackendConfig; import org.apache.streampipes.config.backend.model.GeneralConfig; -import org.apache.streampipes.model.client.user.*; +import org.apache.streampipes.model.client.user.JwtAuthenticationResponse; +import org.apache.streampipes.model.client.user.LoginRequest; +import org.apache.streampipes.model.client.user.Principal; +import org.apache.streampipes.model.client.user.RegistrationData; +import org.apache.streampipes.model.client.user.UserAccount; import org.apache.streampipes.model.message.ErrorMessage; import org.apache.streampipes.model.message.NotificationType; import org.apache.streampipes.model.message.Notifications; @@ -31,15 +35,23 @@ import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.user.management.jwt.JwtTokenProvider; import org.apache.streampipes.user.management.model.PrincipalUserDetails; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.HashMap; import java.util.Map; @@ -56,7 +68,8 @@ public class Authentication extends AbstractRestResource { @Path("/login") public Response doLogin(LoginRequest token) { try { - org.springframework.security.core.Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(token.getUsername(), token.getPassword())); + org.springframework.security.core.Authentication authentication = authenticationManager.authenticate( + new UsernamePasswordAuthenticationToken(token.getUsername(), token.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); return processAuth(authentication); } catch (BadCredentialsException e) { diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AutoComplete.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AutoComplete.java index b18c4a36d9..27d2a475e8 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AutoComplete.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/AutoComplete.java @@ -31,11 +31,11 @@ @Path("/v2/autocomplete") public class AutoComplete extends AbstractRestResource { - @GET - @Path("semantic-type") - @Produces(MediaType.APPLICATION_JSON) - public Response getSemanticTypes(@QueryParam("text") String text) { - return ok(SemanticTypeRegistry.INSTANCE.matches(text)); - } + @GET + @Path("semantic-type") + @Produces(MediaType.APPLICATION_JSON) + public Response getSemanticTypes(@QueryParam("text") String text) { + return ok(SemanticTypeRegistry.INSTANCE.matches(text)); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/CategoryResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/CategoryResource.java index 5bc62d4284..d958662281 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/CategoryResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/CategoryResource.java @@ -24,9 +24,17 @@ import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.storage.management.StorageDispatcher; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.HashMap; import java.util.Map; @@ -34,78 +42,78 @@ public class CategoryResource extends AbstractRestResource { - @GET - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getAll() { - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI() - .getAllCategories() - ); - } + @GET + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getAll() { + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI() + .getAllCategories() + ); + } - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response add(Category category) { - String categoryId = StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI() - .storeCategory(category); + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response add(Category category) { + String categoryId = StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI() + .storeCategory(category); - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI().getCategory(categoryId)); - } + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI().getCategory(categoryId)); + } - @GET - @Path("/{categoryId}") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getCategory(@PathParam("categoryId") String categoryId) { - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI() - .getCategory(categoryId)); - } + @GET + @Path("/{categoryId}") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getCategory(@PathParam("categoryId") String categoryId) { + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI() + .getCategory(categoryId)); + } - @PUT - @Path("/{categoryId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response update(@PathParam("categoryId") String categoryId, Category category) { - if (!categoryId.equals(category.getId())) { - String resString = "CategoryId not the same as in message body"; - Map errorDetails = new HashMap<>(); - errorDetails.put("message", resString); - return badRequest(errorDetails); - } - StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI() - .updateCategory(category); - - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI().getCategory(categoryId)); + @PUT + @Path("/{categoryId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response update(@PathParam("categoryId") String categoryId, Category category) { + if (!categoryId.equals(category.getId())) { + String resString = "CategoryId not the same as in message body"; + Map errorDetails = new HashMap<>(); + errorDetails.put("message", resString); + return badRequest(errorDetails); } + StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI() + .updateCategory(category); - @DELETE - @Path("/{categoryId}") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response delete(@PathParam("categoryId") String key) { - StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI() - .deleteCategory(key); - StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .deleteAllForCategory(key); - return ok(); - } + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI().getCategory(categoryId)); + } + + @DELETE + @Path("/{categoryId}") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response delete(@PathParam("categoryId") String key) { + StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI() + .deleteCategory(key); + StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .deleteAllForCategory(key); + return ok(); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/EmailResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/EmailResource.java index 6ecd9d6fc1..021c4961ff 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/EmailResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/EmailResource.java @@ -39,7 +39,8 @@ public Response sendEmail(SpEmail email) { new MailSender().sendEmail(email); return ok(); } else { - return serverError("Could not send email - no valid mail configuration provided in StreamPipes (go to settings -> mail)"); + return serverError( + "Could not send email - no valid mail configuration provided in StreamPipes (go to settings -> mail)"); } } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/FunctionsResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/FunctionsResource.java index 04ee09b871..029708d096 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/FunctionsResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/FunctionsResource.java @@ -24,9 +24,16 @@ import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.List; @Path("/v2/functions") diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/GenericStorageResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/GenericStorageResource.java index 5f140a465e..694abaa2c5 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/GenericStorageResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/GenericStorageResource.java @@ -22,14 +22,23 @@ import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.storage.api.IGenericStorage; import org.apache.streampipes.storage.management.StorageDispatcher; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; import java.util.List; import java.util.Map; @@ -38,90 +47,90 @@ @Component public class GenericStorageResource extends AbstractAuthGuardedRestResource { - public static final String APP_DOC_NAME = "appDocName"; + public static final String APP_DOC_NAME = "appDocName"; - private static final Logger LOG = LoggerFactory.getLogger(GenericStorageResource.class); + private static final Logger LOG = LoggerFactory.getLogger(GenericStorageResource.class); - @GET - @Path("{appDocName}") - @Produces(MediaType.APPLICATION_JSON) - @PreAuthorize(AuthConstants.HAS_READ_GENERIC_STORAGE_PRIVILEGE) - public Response getAll(@PathParam(APP_DOC_NAME) String appDocName) { - try { - List> assets = getGenericStorage().findAll(appDocName); - return ok(assets); - } catch (IOException e) { - LOG.error("Could not connect to storage", e); - return fail(); - } - } - - @POST - @Path("{appDocName}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @PreAuthorize(AuthConstants.HAS_WRITE_GENERIC_STORAGE_PRIVILEGE) - public Response create(@PathParam(APP_DOC_NAME) String appDocName, - String document) { - try { - Map obj = getGenericStorage().create(document); - return ok(obj); - } catch (IOException e) { - LOG.error("Could not connect to storage", e); - return fail(); - } + @GET + @Path("{appDocName}") + @Produces(MediaType.APPLICATION_JSON) + @PreAuthorize(AuthConstants.HAS_READ_GENERIC_STORAGE_PRIVILEGE) + public Response getAll(@PathParam(APP_DOC_NAME) String appDocName) { + try { + List> assets = getGenericStorage().findAll(appDocName); + return ok(assets); + } catch (IOException e) { + LOG.error("Could not connect to storage", e); + return fail(); } + } - @GET - @Path("{appDocName}/{id}") - @Produces(MediaType.APPLICATION_JSON) - @PreAuthorize(AuthConstants.HAS_READ_GENERIC_STORAGE_PRIVILEGE) - public Response getCategory(@PathParam(APP_DOC_NAME) String appDocName, - @PathParam("id") String documentId) { - try { - Map obj = getGenericStorage().findOne(documentId); - return ok(obj); - } catch (IOException e) { - LOG.error("Could not connect to storage", e); - return fail(); - } + @POST + @Path("{appDocName}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @PreAuthorize(AuthConstants.HAS_WRITE_GENERIC_STORAGE_PRIVILEGE) + public Response create(@PathParam(APP_DOC_NAME) String appDocName, + String document) { + try { + Map obj = getGenericStorage().create(document); + return ok(obj); + } catch (IOException e) { + LOG.error("Could not connect to storage", e); + return fail(); } + } - @PUT - @Path("{appDocName}/{id}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @PreAuthorize(AuthConstants.HAS_WRITE_GENERIC_STORAGE_PRIVILEGE) - public Response update(@PathParam(APP_DOC_NAME) String appDocName, - @PathParam("id") String documentId, - String document) { - try { - Map obj = getGenericStorage().update(documentId, document); - return ok(obj); - } catch (IOException e) { - LOG.error("Could not connect to storage", e); - return fail(); - } + @GET + @Path("{appDocName}/{id}") + @Produces(MediaType.APPLICATION_JSON) + @PreAuthorize(AuthConstants.HAS_READ_GENERIC_STORAGE_PRIVILEGE) + public Response getCategory(@PathParam(APP_DOC_NAME) String appDocName, + @PathParam("id") String documentId) { + try { + Map obj = getGenericStorage().findOne(documentId); + return ok(obj); + } catch (IOException e) { + LOG.error("Could not connect to storage", e); + return fail(); } + } - @DELETE - @Path("{appDocName}/{id}/{rev}") - @Produces(MediaType.APPLICATION_JSON) - @PreAuthorize(AuthConstants.HAS_WRITE_GENERIC_STORAGE_PRIVILEGE) - public Response delete(@PathParam(APP_DOC_NAME) String appDocName, - @PathParam("id") String documentId, - @PathParam("rev") String rev) { - try { - getGenericStorage().delete(documentId, rev); - return ok(); - } catch (IOException e) { - LOG.error("Could not connect to storage", e); - return fail(); - } + @PUT + @Path("{appDocName}/{id}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @PreAuthorize(AuthConstants.HAS_WRITE_GENERIC_STORAGE_PRIVILEGE) + public Response update(@PathParam(APP_DOC_NAME) String appDocName, + @PathParam("id") String documentId, + String document) { + try { + Map obj = getGenericStorage().update(documentId, document); + return ok(obj); + } catch (IOException e) { + LOG.error("Could not connect to storage", e); + return fail(); } + } - private IGenericStorage getGenericStorage() { - return StorageDispatcher.INSTANCE.getNoSqlStore().getGenericStorage(); + @DELETE + @Path("{appDocName}/{id}/{rev}") + @Produces(MediaType.APPLICATION_JSON) + @PreAuthorize(AuthConstants.HAS_WRITE_GENERIC_STORAGE_PRIVILEGE) + public Response delete(@PathParam(APP_DOC_NAME) String appDocName, + @PathParam("id") String documentId, + @PathParam("rev") String rev) { + try { + getGenericStorage().delete(documentId, rev); + return ok(); + } catch (IOException e) { + LOG.error("Could not connect to storage", e); + return fail(); } + } + private IGenericStorage getGenericStorage() { + return StorageDispatcher.INSTANCE.getNoSqlStore().getGenericStorage(); } + +} diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/LabelResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/LabelResource.java index 0f80f59224..3046469368 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/LabelResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/LabelResource.java @@ -24,115 +24,123 @@ import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.storage.management.StorageDispatcher; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.HashMap; import java.util.Map; @Path("/v2/labeling/label") public class LabelResource extends AbstractRestResource { - @GET - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getAllLabels() { - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .getAllLabels()); - } - - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response addLabel(Label label) { - Category categoryForLabel = StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI() - .getCategory(label.getCategoryId()); - if (categoryForLabel == null) { - String resString = String.format("Category with categoryId %s does not exist", label.getCategoryId()); - Map errorDetails = new HashMap<>(); - errorDetails.put("message", resString); - return badRequest(errorDetails); - } - String labelId = StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .storeLabel(label); + @GET + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getAllLabels() { + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .getAllLabels()); + } - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .getLabel(labelId)); + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response addLabel(Label label) { + Category categoryForLabel = StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI() + .getCategory(label.getCategoryId()); + if (categoryForLabel == null) { + String resString = String.format("Category with categoryId %s does not exist", label.getCategoryId()); + Map errorDetails = new HashMap<>(); + errorDetails.put("message", resString); + return badRequest(errorDetails); } + String labelId = StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .storeLabel(label); - @GET - @Path("/{labelId}") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getLabel(@PathParam("labelId") String labelId) { - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .getLabel(labelId)); - } + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .getLabel(labelId)); + } - @PUT - @Path("/{labelId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response updateLabel(@PathParam("labelId") String labelId, Label label) { - if (!labelId.equals(label.getId())) { - String resString = "LabelId not the same as in message body"; - Map errorDetails = new HashMap<>(); - errorDetails.put("message", resString); - return badRequest(errorDetails); - } - Category categoryForLabel = StorageDispatcher.INSTANCE - .getNoSqlStore() - .getCategoryStorageAPI() - .getCategory(label.getCategoryId()); - if (categoryForLabel == null) { - String resString = String.format("Category with categoryId %s does not exist", label.getCategoryId()); - Map errorDetails = new HashMap<>(); - errorDetails.put("message", resString); - return badRequest(errorDetails); - } - StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .updateLabel(label); + @GET + @Path("/{labelId}") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getLabel(@PathParam("labelId") String labelId) { + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .getLabel(labelId)); + } - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .getLabel(labelId)); + @PUT + @Path("/{labelId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response updateLabel(@PathParam("labelId") String labelId, Label label) { + if (!labelId.equals(label.getId())) { + String resString = "LabelId not the same as in message body"; + Map errorDetails = new HashMap<>(); + errorDetails.put("message", resString); + return badRequest(errorDetails); } - - @DELETE - @Path("/{labelId}") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response deleteLabel(@PathParam("labelId") String labelId) { - StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .deleteLabel(labelId); - return ok(); + Category categoryForLabel = StorageDispatcher.INSTANCE + .getNoSqlStore() + .getCategoryStorageAPI() + .getCategory(label.getCategoryId()); + if (categoryForLabel == null) { + String resString = String.format("Category with categoryId %s does not exist", label.getCategoryId()); + Map errorDetails = new HashMap<>(); + errorDetails.put("message", resString); + return badRequest(errorDetails); } + StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .updateLabel(label); - @GET - @Path("category/{categoryId}") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getLabelsForCategory(@PathParam("categoryId") String categoryId) { - return ok(StorageDispatcher.INSTANCE - .getNoSqlStore() - .getLabelStorageAPI() - .getAllForCategory(categoryId)); - } + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .getLabel(labelId)); + } + + @DELETE + @Path("/{labelId}") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response deleteLabel(@PathParam("labelId") String labelId) { + StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .deleteLabel(labelId); + return ok(); + } + + @GET + @Path("category/{categoryId}") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getLabelsForCategory(@PathParam("categoryId") String categoryId) { + return ok(StorageDispatcher.INSTANCE + .getNoSqlStore() + .getLabelStorageAPI() + .getAllForCategory(categoryId)); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/MeasurementUnitResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/MeasurementUnitResource.java index 50682b02fd..75a095f4f0 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/MeasurementUnitResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/MeasurementUnitResource.java @@ -1,19 +1,21 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ + package org.apache.streampipes.rest.impl; import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Notification.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Notification.java index 14925bd2df..5ae43d0d10 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Notification.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Notification.java @@ -22,81 +22,89 @@ import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/v2/notifications") public class Notification extends AbstractAuthGuardedRestResource { - @POST - @Consumes(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response addNotification(org.apache.streampipes.model.Notification notification) { - getNotificationStorage().addNotification(notification); - return ok(); - } + @POST + @Consumes(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response addNotification(org.apache.streampipes.model.Notification notification) { + getNotificationStorage().addNotification(notification); + return ok(); + } - @GET - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - @Path("/offset") - public Response getNotifications(@QueryParam("notificationType") String notificationTypeId, - @QueryParam("offset") Integer offset, - @QueryParam("count") Integer count) { - return ok(getNotificationStorage() - .getAllNotifications(notificationTypeId, offset, count)); - } + @GET + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + @Path("/offset") + public Response getNotifications(@QueryParam("notificationType") String notificationTypeId, + @QueryParam("offset") Integer offset, + @QueryParam("count") Integer count) { + return ok(getNotificationStorage() + .getAllNotifications(notificationTypeId, offset, count)); + } - @GET - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - @Path("/time") - public Response getNotifications(@QueryParam("startTime") long startTime) { - return ok(getNotificationStorage() - .getAllNotificationsFromTimestamp(startTime)); - } + @GET + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + @Path("/time") + public Response getNotifications(@QueryParam("startTime") long startTime) { + return ok(getNotificationStorage() + .getAllNotificationsFromTimestamp(startTime)); + } - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/count") - public Response getUnreadNotificationsCount() { - return ok(getNotificationStorage() - .getUnreadNotificationsCount(getAuthenticatedUserSid())); - } + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/count") + public Response getUnreadNotificationsCount() { + return ok(getNotificationStorage() + .getUnreadNotificationsCount(getAuthenticatedUserSid())); + } - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/unread") - public Response getUnreadNotifications() { - return ok(getNotificationStorage() - .getUnreadNotifications()); - } - - @DELETE - @Produces(MediaType.APPLICATION_JSON) - @Path("/{notificationId}") - public Response deleteNotification(@PathParam("notificationId") String notificationId) { - boolean success = getNotificationStorage() - .deleteNotification(notificationId); - if (success) { - return ok(Notifications.success("Notification deleted")); - } else { - return ok(Notifications.error("Could not delete notification")); - } + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/unread") + public Response getUnreadNotifications() { + return ok(getNotificationStorage() + .getUnreadNotifications()); + } + @DELETE + @Produces(MediaType.APPLICATION_JSON) + @Path("/{notificationId}") + public Response deleteNotification(@PathParam("notificationId") String notificationId) { + boolean success = getNotificationStorage() + .deleteNotification(notificationId); + if (success) { + return ok(Notifications.success("Notification deleted")); + } else { + return ok(Notifications.error("Could not delete notification")); } - @PUT - @Produces(MediaType.APPLICATION_JSON) - @Path("/{notificationId}") - public Response modifyNotificationStatus(@PathParam("notificationId") String notificationId) { - boolean success = getNotificationStorage() - .changeNotificationStatus(notificationId); - if (success) { - return ok(Notifications.success("Ok")); - } else { - return ok(Notifications.error("Error")); - } + } + + @PUT + @Produces(MediaType.APPLICATION_JSON) + @Path("/{notificationId}") + public Response modifyNotificationStatus(@PathParam("notificationId") String notificationId) { + boolean success = getNotificationStorage() + .changeNotificationStatus(notificationId); + if (success) { + return ok(Notifications.success("Ok")); + } else { + return ok(Notifications.error("Error")); } + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/OntologyMeasurementUnit.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/OntologyMeasurementUnit.java index a6056e6917..e89c49e62a 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/OntologyMeasurementUnit.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/OntologyMeasurementUnit.java @@ -31,31 +31,31 @@ @Path("/v2/units") public class OntologyMeasurementUnit extends AbstractRestResource { - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/instances") - public Response getAllUnits() { - return ok(UnitProvider - .INSTANCE - .getAvailableUnits()); - } - - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/types") - public Response getAllUnitTypes() { - return ok(UnitProvider - .INSTANCE - .getAvailableUnitTypes()); - } - - @GET - @Path("/instances/{resourceId}") - @Produces(MediaType.APPLICATION_JSON) - public Response getUnit(@PathParam("resourceId") String resourceUri) { - return ok(UnitProvider - .INSTANCE - .getUnit(resourceUri)); - } + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/instances") + public Response getAllUnits() { + return ok(UnitProvider + .INSTANCE + .getAvailableUnits()); + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/types") + public Response getAllUnitTypes() { + return ok(UnitProvider + .INSTANCE + .getAvailableUnitTypes()); + } + + @GET + @Path("/instances/{resourceId}") + @Produces(MediaType.APPLICATION_JSON) + public Response getUnit(@PathParam("resourceId") String resourceUri) { + return ok(UnitProvider + .INSTANCE + .getUnit(resourceUri)); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCache.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCache.java index f2b8d16eb0..55739a0dca 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCache.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCache.java @@ -20,7 +20,11 @@ import org.apache.streampipes.manager.pipeline.PipelineCacheManager; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCanvasMetadataCache.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCanvasMetadataCache.java index 4659b76ce5..492b5bbc89 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCanvasMetadataCache.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCanvasMetadataCache.java @@ -20,7 +20,11 @@ import org.apache.streampipes.manager.pipeline.PipelineCanvasMetadataCacheManager; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -37,7 +41,7 @@ public Response updateCachedCanvasMetadata(String canvasMetadata) { @GET @Produces(MediaType.APPLICATION_JSON) public Response getCachedCanvasMetadata() { - String result = PipelineCanvasMetadataCacheManager.getCachedCanvasMetadata(getAuthenticatedUsername()); + String result = PipelineCanvasMetadataCacheManager.getCachedCanvasMetadata(getAuthenticatedUsername()); if (result != null) { return ok(result); } else { diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCanvasMetadataResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCanvasMetadataResource.java index 2ecf4c6b8b..52f89c7c2f 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCanvasMetadataResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCanvasMetadataResource.java @@ -22,7 +22,13 @@ import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.storage.api.IPipelineCanvasMetadataStorage; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -36,7 +42,7 @@ public class PipelineCanvasMetadataResource extends AbstractRestResource { public Response getPipelineCanvasMetadataForPipeline(@PathParam("pipelineId") String pipelineId) { try { return ok(getPipelineCanvasMetadataStorage() - .getPipelineCanvasMetadataForPipeline(pipelineId)); + .getPipelineCanvasMetadataForPipeline(pipelineId)); } catch (IllegalArgumentException e) { return badRequest(); } @@ -49,7 +55,7 @@ public Response getPipelineCanvasMetadataForPipeline(@PathParam("pipelineId") St public Response getPipelineCanvasMetadata(@PathParam("canvasId") String pipelineCanvasId) { try { return ok(getPipelineCanvasMetadataStorage() - .getElementById(pipelineCanvasId)); + .getElementById(pipelineCanvasId)); } catch (IllegalArgumentException e) { return badRequest(); } @@ -78,7 +84,8 @@ public Response deletePipelineCanvasMetadata(@PathParam("canvasId") String pipel @Path("/pipeline/{pipelineId}") @JacksonSerialized public Response deletePipelineCanvasMetadataForPipeline(@PathParam("pipelineId") String pipelineId) { - PipelineCanvasMetadata metadata = getPipelineCanvasMetadataStorage().getPipelineCanvasMetadataForPipeline(pipelineId); + PipelineCanvasMetadata metadata = + getPipelineCanvasMetadataStorage().getPipelineCanvasMetadataForPipeline(pipelineId); getPipelineCanvasMetadataStorage().deleteElement(metadata); return ok(); } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCategory.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCategory.java index 9ef53d92de..d6ac7b2d46 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCategory.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineCategory.java @@ -23,44 +23,56 @@ import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.storage.api.IPipelineCategoryStorage; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/v2/pipelinecategories") public class PipelineCategory extends AbstractRestResource { - @GET - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getCategories() { - return ok(getPipelineCategoryStorage() - .getPipelineCategories()); - } - - @POST - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response addCategory(org.apache.streampipes.model.pipeline.PipelineCategory pipelineCategory) { - boolean success = getPipelineCategoryStorage() - .addPipelineCategory(pipelineCategory); - if (success) return ok(Notifications.success("Category successfully stored. ")); - else return ok(Notifications.error("Could not create category.")); - } - - @DELETE - @Path("/{categoryId}") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response removeCategory(@PathParam("categoryId") String categoryId) { - boolean success = getPipelineCategoryStorage() - .deletePipelineCategory(categoryId); - if (success) return ok(Notifications.success("Category successfully deleted. ")); - else return ok(Notifications.error("Could not delete category.")); - } + @GET + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getCategories() { + return ok(getPipelineCategoryStorage() + .getPipelineCategories()); + } - private IPipelineCategoryStorage getPipelineCategoryStorage() { - return getNoSqlStorage().getPipelineCategoryStorageApi(); - } + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response addCategory(org.apache.streampipes.model.pipeline.PipelineCategory pipelineCategory) { + boolean success = getPipelineCategoryStorage() + .addPipelineCategory(pipelineCategory); + if (success) { + return ok(Notifications.success("Category successfully stored. ")); + } else { + return ok(Notifications.error("Could not create category.")); + } + } + + @DELETE + @Path("/{categoryId}") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response removeCategory(@PathParam("categoryId") String categoryId) { + boolean success = getPipelineCategoryStorage() + .deletePipelineCategory(categoryId); + if (success) { + return ok(Notifications.success("Category successfully deleted. ")); + } else { + return ok(Notifications.error("Could not delete category.")); + } + } + + private IPipelineCategoryStorage getPipelineCategoryStorage() { + return getNoSqlStorage().getPipelineCategoryStorageApi(); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementAsset.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementAsset.java index 68e14324ae..ff099540e0 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementAsset.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementAsset.java @@ -19,6 +19,7 @@ import org.apache.streampipes.manager.assets.AssetManager; import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +29,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; @Path("/v2/pe") @@ -61,7 +63,7 @@ public Response getDocumentationAsset(@PathParam("appId") String appId) { @Path("{appId}/assets/{assetName}") @Produces("image/png") public Response getAsset(@PathParam("appId") String appId, @PathParam("assetName") String - assetName) { + assetName) { try { byte[] asset = AssetManager.getAsset(appId, assetName); return ok(asset); diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementCategory.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementCategory.java index 715c843665..99add2d68d 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementCategory.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementCategory.java @@ -32,48 +32,49 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.List; import java.util.stream.Collectors; @Path("/v2/categories") public class PipelineElementCategory extends AbstractRestResource { - @GET - @Path("/ep") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getEps() { - return ok(makeCategories(StorageManager.INSTANCE.getPipelineElementStorage().getAllDataStreams())); - } + @GET + @Path("/ep") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getEps() { + return ok(makeCategories(StorageManager.INSTANCE.getPipelineElementStorage().getAllDataStreams())); + } + + @GET + @Path("/epa") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getEpaCategories() { + return ok(DataProcessorType.values()); + } - @GET - @Path("/epa") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getEpaCategories() { - return ok(DataProcessorType.values()); - } + @GET + @Path("/adapter") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getAdapterCategories() { + return ok(AdapterType.values()); + } - @GET - @Path("/adapter") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getAdapterCategories() { - return ok(AdapterType.values()); - } + @GET + @Path("/ec") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + public Response getEcCategories() { + return ok(DataSinkType.values()); + } - @GET - @Path("/ec") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - public Response getEcCategories() { - return ok(DataSinkType.values()); - } - - private List makeCategories(List streams) { - return streams - .stream() - .map(p -> new Category(p.getElementId(), p.getName(), p.getDescription())) - .collect(Collectors.toList()); - } + private List makeCategories(List streams) { + return streams + .stream() + .map(p -> new Category(p.getElementId(), p.getName(), p.getDescription())) + .collect(Collectors.toList()); + } } 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 6c07af6c76..19330b36b6 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 @@ -21,14 +21,23 @@ import org.apache.streampipes.model.file.FileMetadata; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; + import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.InputStream; @Path("/v2/files") @@ -41,7 +50,8 @@ public class PipelineElementFile extends AbstractAuthGuardedRestResource { public Response storeFile(@FormDataParam("file_upload") InputStream uploadedInputStream, @FormDataParam("file_upload") FormDataContentDisposition fileDetail) { try { - FileMetadata metadata = FileManager.storeFile(getAuthenticatedUsername(), fileDetail.getFileName(), uploadedInputStream); + FileMetadata metadata = + FileManager.storeFile(getAuthenticatedUsername(), fileDetail.getFileName(), uploadedInputStream); return ok(metadata); } catch (Exception e) { return fail(); diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementPreview.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementPreview.java index bd91ca347b..319dadc0e8 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementPreview.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementPreview.java @@ -23,7 +23,13 @@ import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementRuntimeInfo.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementRuntimeInfo.java index 7806bca17e..ebb880ae9b 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementRuntimeInfo.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineElementRuntimeInfo.java @@ -39,7 +39,8 @@ public class PipelineElementRuntimeInfo extends AbstractRestResource { @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response getRuntimeInfo(SpDataStream spDataStream) { - // TODO currently only supported for data streams. For data sets, a dummy pipeline needs to be generated to get runtime values. + // TODO currently only supported for data streams. + // For data sets, a dummy pipeline needs to be generated to get runtime values. try { return ok(Operations.getRuntimeInfo(spDataStream)); } catch (SpRuntimeException e) { diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineMonitoring.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineMonitoring.java index 90be6c1986..86ccc8d3d2 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineMonitoring.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineMonitoring.java @@ -18,7 +18,6 @@ package org.apache.streampipes.rest.impl; import org.apache.streampipes.manager.monitoring.pipeline.ExtensionsLogProvider; -import org.apache.streampipes.rest.api.IPipelineMonitoring; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -28,12 +27,11 @@ import javax.ws.rs.core.Response; @Path("/v2/pipeline-monitoring") -public class PipelineMonitoring extends AbstractMonitoringResource implements IPipelineMonitoring { +public class PipelineMonitoring extends AbstractMonitoringResource { @Path("pipeline/{pipelineId}/logs") @GET @Produces(MediaType.APPLICATION_JSON) - @Override public Response getLogInfoForPipeline(@PathParam("pipelineId") String pipelineId) { return ok(ExtensionsLogProvider.INSTANCE.getLogInfosForPipeline(pipelineId)); } @@ -41,7 +39,6 @@ public Response getLogInfoForPipeline(@PathParam("pipelineId") String pipelineId @Path("pipeline/{pipelineId}/metrics") @GET @Produces(MediaType.APPLICATION_JSON) - @Override public Response getMetricsInfoForPipeline(@PathParam("pipelineId") String pipelineId) { return ok(ExtensionsLogProvider.INSTANCE.getMetricInfosForPipeline(pipelineId)); } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineResource.java index fe7bb1afa1..c82482bf3a 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineResource.java @@ -18,13 +18,8 @@ package org.apache.streampipes.rest.impl; -import com.google.gson.JsonSyntaxException; -import io.swagger.v3.oas.annotations.Hidden; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.media.ArraySchema; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; + + import org.apache.streampipes.commons.exceptions.NoMatchingFormatException; import org.apache.streampipes.commons.exceptions.NoMatchingJsonSchemaException; import org.apache.streampipes.commons.exceptions.NoMatchingProtocolException; @@ -46,6 +41,14 @@ import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + +import com.google.gson.JsonSyntaxException; +import io.swagger.v3.oas.annotations.Hidden; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; 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 94f08be16b..2afc10fd10 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 @@ -26,9 +26,14 @@ import org.apache.streampipes.model.template.PipelineTemplateInvocation; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; -import javax.ws.rs.*; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.ArrayList; import java.util.List; @@ -43,9 +48,9 @@ public Response getAvailableDataStreams() { List datasets = new ArrayList<>(); sources.stream() - .filter(stream -> !(stream instanceof SpDataSet)) - .map(SpDataStream::new) - .forEach(datasets::add); + .filter(stream -> !(stream instanceof SpDataSet)) + .map(SpDataStream::new) + .forEach(datasets::add); return ok((new SpDataStreamContainer(datasets))); } @@ -59,10 +64,10 @@ public Response getAvailableDataSets() { List datasets = new ArrayList<>(); sources - .stream() - .filter(stream -> stream instanceof SpDataSet) - .map(stream -> new SpDataSet((SpDataSet) stream)) - .forEach(datasets::add); + .stream() + .filter(stream -> stream instanceof SpDataSet) + .map(stream -> new SpDataSet((SpDataSet) stream)) + .forEach(datasets::add); return ok(new SpDataStreamContainer(datasets)); } @@ -75,7 +80,8 @@ public Response getPipelineTemplateInvocation(@QueryParam("streamId") String str if (pipelineTemplateId != null) { SpDataStream dataStream = getDataStream(streamId); PipelineTemplateDescription pipelineTemplateDescription = getPipelineTemplateDescription(pipelineTemplateId); - PipelineTemplateInvocation invocation = Operations.getPipelineInvocationTemplate(dataStream, pipelineTemplateDescription); + PipelineTemplateInvocation invocation = + Operations.getPipelineInvocationTemplate(dataStream, pipelineTemplateDescription); PipelineTemplateInvocation clonedInvocation = new PipelineTemplateInvocation(invocation); return ok(new PipelineTemplateInvocation(clonedInvocation)); } else { @@ -88,7 +94,7 @@ public Response getPipelineTemplateInvocation(@QueryParam("streamId") String str public Response generatePipeline(PipelineTemplateInvocation pipelineTemplateInvocation) { PipelineOperationStatus status = Operations - .handlePipelineTemplateInvocation(getAuthenticatedUserSid(), pipelineTemplateInvocation); + .handlePipelineTemplateInvocation(getAuthenticatedUserSid(), pipelineTemplateInvocation); return ok(status); @@ -97,11 +103,11 @@ public Response generatePipeline(PipelineTemplateInvocation pipelineTemplateInvo private PipelineTemplateDescription getPipelineTemplateDescription(String pipelineTemplateId) { return Operations - .getAllPipelineTemplates() - .stream() - .filter(pt -> pt.getAppId().equals(pipelineTemplateId)) - .findFirst() - .get(); + .getAllPipelineTemplates() + .stream() + .filter(pt -> pt.getAppId().equals(pipelineTemplateId)) + .findFirst() + .get(); } private List getAllDataStreams() { @@ -110,9 +116,9 @@ private List getAllDataStreams() { private SpDataStream getDataStream(String streamId) { return getAllDataStreams() - .stream() - .filter(sp -> sp.getElementId().equals(streamId)) - .findFirst() - .get(); + .stream() + .filter(sp -> sp.getElementId().equals(streamId)) + .findFirst() + .get(); } } 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 a37296c45f..f7b0d83abb 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 @@ -18,12 +18,13 @@ package org.apache.streampipes.rest.impl; -import io.swagger.v3.oas.annotations.Operation; import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.model.message.SuccessMessage; import org.apache.streampipes.rest.ResetManagement; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + +import io.swagger.v3.oas.annotations.Operation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,16 +36,16 @@ @Path("/v2/reset") public class ResetResource extends AbstractAuthGuardedRestResource { - private static final Logger logger = LoggerFactory.getLogger(ResetResource.class); + private static final Logger logger = LoggerFactory.getLogger(ResetResource.class); - @POST - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - @Operation(summary = "Resets StreamPipes instance") - public Response reset() { - ResetManagement.reset(getAuthenticatedUsername()); - SuccessMessage message = Notifications.success("Reset of system successfully performed"); - return ok(message); - } + @POST + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + @Operation(summary = "Resets StreamPipes instance") + public Response reset() { + ResetManagement.reset(getAuthenticatedUsername()); + SuccessMessage message = Notifications.success("Reset of system successfully performed"); + return ok(message); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/RestorePasswordResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/RestorePasswordResource.java index 1897e29363..0f4a9bfb3c 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/RestorePasswordResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/RestorePasswordResource.java @@ -20,9 +20,15 @@ import org.apache.streampipes.model.client.user.RegistrationData; import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Setup.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Setup.java index 9badbcfd59..595cbf04b6 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Setup.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Setup.java @@ -18,10 +18,12 @@ package org.apache.streampipes.rest.impl; -import com.google.gson.JsonObject; + import org.apache.streampipes.config.backend.BackendConfig; import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; +import com.google.gson.JsonObject; + import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/UserResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/UserResource.java index 7ee83dd182..976c22ab3b 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/UserResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/UserResource.java @@ -18,7 +18,13 @@ package org.apache.streampipes.rest.impl; import org.apache.streampipes.mail.MailSender; -import org.apache.streampipes.model.client.user.*; +import org.apache.streampipes.model.client.user.ChangePasswordRequest; +import org.apache.streampipes.model.client.user.Principal; +import org.apache.streampipes.model.client.user.PrincipalType; +import org.apache.streampipes.model.client.user.RawUserApiToken; +import org.apache.streampipes.model.client.user.Role; +import org.apache.streampipes.model.client.user.ServiceAccount; +import org.apache.streampipes.model.client.user.UserAccount; import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; @@ -26,13 +32,23 @@ import org.apache.streampipes.user.management.encryption.SecretEncryptionManager; import org.apache.streampipes.user.management.service.TokenService; import org.apache.streampipes.user.management.util.PasswordUtil; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; @@ -183,7 +199,7 @@ public Response createNewApiToken(@PathParam("userId") String userId, @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateUserAccountDetails(@PathParam("principalId") String principalId, - UserAccount user) { + UserAccount user) { String authenticatedUserId = getAuthenticatedUsername(); if (user != null && (authenticatedUserId.equals(principalId) || isAdmin())) { UserAccount existingUser = (UserAccount) getPrincipalById(principalId); @@ -208,7 +224,8 @@ public Response updateUsername(@PathParam("principalId") String principalId, try { if (PasswordUtil.validatePassword(user.getPassword(), existingUser.getPassword())) { existingUser.setUsername(user.getUsername()); - if (getUserStorage().getAllUserAccounts().stream().noneMatch(u -> u.getUsername().equals(user.getUsername()))) { + if (getUserStorage().getAllUserAccounts().stream() + .noneMatch(u -> u.getUsername().equals(user.getUsername()))) { updateUser(existingUser, user, isAdmin(), existingUser.getPassword()); getUserStorage().updateUser(existingUser); return ok(); @@ -234,7 +251,7 @@ public Response updatePassword(@PathParam("principalId") String principalId, ChangePasswordRequest passwordRequest) { String authenticatedUserId = getAuthenticatedUsername(); UserAccount existingUser = (UserAccount) getPrincipalById(principalId); - if (principalId.equals(authenticatedUserId) || isAdmin()) { + if (principalId.equals(authenticatedUserId) || isAdmin()) { try { String existingPw = passwordRequest.getExistingPassword(); if (PasswordUtil.validatePassword(existingPw, existingUser.getPassword())) { @@ -259,7 +276,7 @@ public Response updatePassword(@PathParam("principalId") String principalId, @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateServiceAccountDetails(@PathParam("principalId") String principalId, - ServiceAccount user) { + ServiceAccount user) { String authenticatedUserId = getAuthenticatedUsername(); if (user != null && (authenticatedUserId.equals(principalId) || isAdmin())) { Principal existingUser = getPrincipalById(principalId); @@ -280,11 +297,11 @@ public Response updateServiceAccountDetails(@PathParam("principalId") String pri private boolean isAdmin() { return SecurityContextHolder - .getContext() - .getAuthentication() - .getAuthorities() - .stream() - .anyMatch(r -> r.getAuthority().equals(Role.ROLE_ADMIN.name())); + .getContext() + .getAuthentication() + .getAuthorities() + .stream() + .anyMatch(r -> r.getAuthority().equals(Role.ROLE_ADMIN.name())); } private void updateUser(UserAccount existingUser, @@ -296,14 +313,14 @@ private void updateUser(UserAccount existingUser, replacePermissions(user, existingUser); } user.setUserApiTokens(existingUser - .getUserApiTokens() + .getUserApiTokens() + .stream() + .filter(existingToken -> user.getUserApiTokens() .stream() - .filter(existingToken -> user.getUserApiTokens() - .stream() - .anyMatch(updatedToken -> existingToken - .getTokenId() - .equals(updatedToken.getTokenId()))) - .collect(Collectors.toList())); + .anyMatch(updatedToken -> existingToken + .getTokenId() + .equals(updatedToken.getTokenId()))) + .collect(Collectors.toList())); } private void encryptAndStore(UserAccount userAccount, diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ConsulConfig.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ConsulConfig.java index 3ef8ed8bd9..858577370e 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ConsulConfig.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/ConsulConfig.java @@ -18,8 +18,7 @@ package org.apache.streampipes.rest.impl.admin; -import com.google.gson.Gson; -import com.google.gson.JsonObject; + import org.apache.streampipes.config.backend.BackendConfig; import org.apache.streampipes.config.backend.MessagingSettings; import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; @@ -29,14 +28,23 @@ import org.apache.streampipes.svcdiscovery.api.model.ConfigItem; import org.apache.streampipes.svcdiscovery.api.model.PeConfig; import org.apache.streampipes.svcdiscovery.consul.ConsulSpConfig; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -46,7 +54,7 @@ @Component public class ConsulConfig extends AbstractRestResource { - private static Logger LOG = LoggerFactory.getLogger(ConsulConfig.class); + private static final Logger LOG = LoggerFactory.getLogger(ConsulConfig.class); @GET @Produces(MediaType.APPLICATION_JSON) @@ -101,7 +109,7 @@ public Response saveServiceConfig(PeConfig peConfig) { if (!("true".equals(value) || "false".equals(value))) { LOG.error(value + " is not from the type: xs:boolean"); return Response.status(Response.Status.BAD_REQUEST) - .entity(value + " is not from the type: xs:boolean").build(); + .entity(value + " is not from the type: xs:boolean").build(); } break; case "xs:integer": @@ -110,7 +118,7 @@ public Response saveServiceConfig(PeConfig peConfig) { } catch (java.lang.NumberFormatException e) { LOG.error(value + " is not from the type: xs:integer"); return Response.status(Response.Status.BAD_REQUEST) - .entity(value + " is not from the type: xs:integer").build(); + .entity(value + " is not from the type: xs:integer").build(); } break; case "xs:double": @@ -119,7 +127,7 @@ public Response saveServiceConfig(PeConfig peConfig) { } catch (java.lang.NumberFormatException e) { LOG.error(value + " is not from the type: xs:double"); return Response.status(Response.Status.BAD_REQUEST) - .entity(value + " is not from the type: xs:double").build(); + .entity(value + " is not from the type: xs:double").build(); } break; case "xs:string": @@ -127,7 +135,7 @@ public Response saveServiceConfig(PeConfig peConfig) { default: LOG.error(configItem.getValueType() + " is not a supported type"); return Response.status(Response.Status.BAD_REQUEST) - .entity(configItem.getValueType() + " is not a supported type").build(); + .entity(configItem.getValueType() + " is not a supported type").build(); } } @@ -137,7 +145,7 @@ public Response saveServiceConfig(PeConfig peConfig) { JsonObject jsonObj = new Gson().toJsonTree(configItem).getAsJsonObject(); jsonObj.entrySet().removeIf(e -> e.getKey().equals("key")); keyValueStore.updateConfig(configItem.getKey(), jsonObj.toString(), - configItem.isPassword()); + configItem.isPassword()); } return Response.status(Response.Status.OK).build(); } 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 fff79451b8..25d4f8171e 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 @@ -22,6 +22,7 @@ import org.apache.streampipes.model.export.ExportConfiguration; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; @@ -31,6 +32,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; import java.util.List; @@ -53,8 +55,8 @@ public Response getExportPreview(List selectedAssetIds) { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response getExportPreview(ExportConfiguration exportConfiguration) throws IOException { - var applicationPackage = ExportManager.getExportPackage(exportConfiguration); - return ok(applicationPackage); + var applicationPackage = ExportManager.getExportPackage(exportConfiguration); + return ok(applicationPackage); } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/DataImportResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/DataImportResource.java index 61b8b4f5be..0d1da02f5b 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/DataImportResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/DataImportResource.java @@ -22,6 +22,7 @@ import org.apache.streampipes.model.export.AssetExportConfiguration; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; + import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; import org.slf4j.Logger; @@ -35,6 +36,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; import java.io.InputStream; @@ -50,8 +52,9 @@ public class DataImportResource extends AbstractAuthGuardedRestResource { @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public Response getImportPreview(@FormDataParam("file_upload") InputStream uploadedInputStream, - @FormDataParam("file_upload") FormDataContentDisposition fileDetail) throws IOException { - var importConfig = ImportManager.getImportPreview(uploadedInputStream); + @FormDataParam("file_upload") FormDataContentDisposition fileDetail) + throws IOException { + var importConfig = ImportManager.getImportPreview(uploadedInputStream); return ok(importConfig); } 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 ad9d3c5072..b8bdd53b44 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 @@ -24,13 +24,20 @@ import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.user.management.encryption.SecretEncryptionManager; + import org.simplejavamail.MailException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; @Path("/v2/admin/mail-config") 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 18a20acff4..254d1375d8 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 @@ -18,7 +18,6 @@ package org.apache.streampipes.rest.impl.admin; -import org.apache.http.client.fluent.Request; import org.apache.streampipes.manager.endpoint.EndpointFetcher; import org.apache.streampipes.manager.operations.Operations; import org.apache.streampipes.model.SpDataSet; @@ -30,12 +29,21 @@ import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.sdk.utils.Assets; import org.apache.streampipes.storage.api.IExtensionsServiceEndpointStorage; + +import org.apache.http.client.fluent.Request; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -59,7 +67,7 @@ public Response getAllEndpoints() { @JacksonSerialized public Response addRdfEndpoint(ExtensionsServiceEndpoint extensionsServiceEndpoint) { getRdfEndpointStorage() - .addExtensionsServiceEndpoint(extensionsServiceEndpoint); + .addExtensionsServiceEndpoint(extensionsServiceEndpoint); return Response.status(Response.Status.OK).build(); } @@ -72,7 +80,7 @@ public Response addRdfEndpoint(ExtensionsServiceEndpoint extensionsServiceEndpoi @JacksonSerialized public Response removeRdfEndpoint(@PathParam("rdfEndpointId") String rdfEndpointId) { getRdfEndpointStorage() - .removeExtensionsServiceEndpoint(rdfEndpointId); + .removeExtensionsServiceEndpoint(rdfEndpointId); return Response.status(Response.Status.OK).build(); } @@ -118,8 +126,8 @@ private List getEndpoints() { private boolean isInstalled(String elementId) { return getAllPipelineElements() - .stream() - .anyMatch(e -> e.equals(elementId)); + .stream() + .anyMatch(e -> e.equals(elementId)); } private List getAllPipelineElements() { @@ -131,32 +139,33 @@ private List getAllPipelineElements() { } private List getAllDataStreamEndpoints(String username, - List existingItems) { + List existingItems) { return getAllDataStreamUris() - .stream() - .filter(s -> existingItems.stream().noneMatch(item -> s.equals(item.getElementId()))) - .map(s -> getPipelineElementStorage().getDataStreamById(s)) - .map(stream -> makeItem(stream, stream instanceof SpDataSet ? "set" : "stream")) - .collect(Collectors.toList()); + .stream() + .filter(s -> existingItems.stream().noneMatch(item -> s.equals(item.getElementId()))) + .map(s -> getPipelineElementStorage().getDataStreamById(s)) + .map(stream -> makeItem(stream, stream instanceof SpDataSet ? "set" : "stream")) + .collect(Collectors.toList()); } private List getAllDataProcessorEndpoints(String username, - List existingItems) { + List existingItems) { return getAllDataProcessorUris() - .stream() - .filter(s -> existingItems.stream().noneMatch(item -> s.equals(item.getElementId()))) - .map(s -> getPipelineElementStorage().getDataProcessorById(s)) - .map(source -> makeItem(source, "sepa")) - .collect(Collectors.toList()); + .stream() + .filter(s -> existingItems.stream().noneMatch(item -> s.equals(item.getElementId()))) + .map(s -> getPipelineElementStorage().getDataProcessorById(s)) + .map(source -> makeItem(source, "sepa")) + .collect(Collectors.toList()); } - private List getAllDataSinkEndpoints(String username, List existingItems) { + private List getAllDataSinkEndpoints(String username, + List existingItems) { return getAllDataSinkUris() - .stream() - .filter(s -> existingItems.stream().noneMatch(item -> s.equals(item.getElementId()))) - .map(s -> getPipelineElementStorage().getDataSinkById(s)) - .map(source -> makeItem(source, "action")) - .collect(Collectors.toList()); + .stream() + .filter(s -> existingItems.stream().noneMatch(item -> s.equals(item.getElementId()))) + .map(s -> getPipelineElementStorage().getDataSinkById(s)) + .map(source -> makeItem(source, "action")) + .collect(Collectors.toList()); } private ExtensionsServiceEndpointItem makeItem(NamedStreamPipesEntity entity, String type) { diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/GeneralConfigurationResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/GeneralConfigurationResource.java index 91cd5ab9d0..90bee48776 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/GeneralConfigurationResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/GeneralConfigurationResource.java @@ -22,14 +22,20 @@ import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + import org.glassfish.jersey.media.multipart.BodyPart; import org.glassfish.jersey.media.multipart.MultiPart; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.StringWriter; import java.security.Key; import java.security.KeyPair; @@ -72,8 +78,8 @@ public Response generateKeyPair() throws Exception { String privateKeyPem = exportKeyAsPem(keyPair.getPrivate(), "PRIVATE"); MultiPart multiPartEntity = new MultiPart() - .bodyPart(new BodyPart().entity(publicKeyPem)) - .bodyPart(new BodyPart().entity(privateKeyPem)); + .bodyPart(new BodyPart().entity(publicKeyPem)) + .bodyPart(new BodyPart().entity(privateKeyPem)); return Response.ok(multiPartEntity).build(); } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/PermissionResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/PermissionResource.java index 6637860ed3..72bfdb565f 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/PermissionResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/admin/PermissionResource.java @@ -20,6 +20,7 @@ import org.apache.streampipes.model.client.user.Permission; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; @@ -27,6 +28,7 @@ import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; + import java.util.List; @Path("/v2/admin/permissions") 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 b097027f19..fdfc54f200 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 @@ -31,14 +31,22 @@ import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.storage.api.IPipelineElementDescriptionStorageCache; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.FormParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; import java.net.URISyntaxException; @@ -83,18 +91,18 @@ public Response deleteElement(@PathParam("id") String elementId) { getSpResourceManager().manageDataProcessors().delete(elementId); } else if (requestor.existsDataStream(elementId)) { appId = requestor.getDataStreamById(elementId).getAppId(); - getSpResourceManager().manageDataStreams().delete(elementId); + getSpResourceManager().manageDataStreams().delete(elementId); } else if (requestor.existsDataSink(elementId)) { appId = requestor.getDataSinkById(elementId).getAppId(); getSpResourceManager().manageDataSinks().delete(elementId); } else { return constructErrorMessage(new Notification(NotificationType.STORAGE_ERROR.title(), - NotificationType.STORAGE_ERROR.description())); + NotificationType.STORAGE_ERROR.description())); } AssetManager.deleteAsset(appId); } catch (IOException e) { return constructErrorMessage(new Notification(NotificationType.STORAGE_ERROR.title(), - NotificationType.STORAGE_ERROR.description())); + NotificationType.STORAGE_ERROR.description())); } return constructSuccessMessage(NotificationType.STORAGE_SUCCESS.uiNotification()); } 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 125569428a..cd2c35de4f 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 @@ -21,10 +21,16 @@ import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.storage.api.IUserGroupStorage; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; @Path("/v2/usergroups") diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/AdapterResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/AdapterResource.java index 069551da91..5eb759a286 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/AdapterResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/AdapterResource.java @@ -26,6 +26,7 @@ import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.storage.management.StorageDispatcher; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/DescriptionResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/DescriptionResource.java index 56819527e6..3c2eeb21bd 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/DescriptionResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/DescriptionResource.java @@ -1,18 +1,19 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.rest.impl.connect; @@ -25,142 +26,148 @@ import org.apache.streampipes.model.connect.adapter.AdapterDescription; import org.apache.streampipes.model.connect.grounding.FormatDescription; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.List; import java.util.Optional; @Path("/v2/connect/master/description") public class DescriptionResource extends AbstractAdapterResource { - private static final Logger LOG = LoggerFactory.getLogger(DescriptionResource.class); - private WorkerUrlProvider workerUrlProvider; - - public DescriptionResource() { - super(DescriptionManagement::new); - workerUrlProvider = new WorkerUrlProvider(); - } - - @GET - @JacksonSerialized - @Path("/formats") - @Produces(MediaType.APPLICATION_JSON) - public Response getFormats() { - List result = managementService.getFormats(); - + private static final Logger LOG = LoggerFactory.getLogger(DescriptionResource.class); + private WorkerUrlProvider workerUrlProvider; + + public DescriptionResource() { + super(DescriptionManagement::new); + workerUrlProvider = new WorkerUrlProvider(); + } + + @GET + @JacksonSerialized + @Path("/formats") + @Produces(MediaType.APPLICATION_JSON) + public Response getFormats() { + List result = managementService.getFormats(); + + return ok(result); + } + + @GET + @JacksonSerialized + @Path("/adapters") + @Produces(MediaType.APPLICATION_JSON) + public Response getAdapters() { + List result = managementService.getAdapters(); + + return ok(result); + } + + @GET + @Path("/{id}/assets") + @Produces("application/zip") + public Response getAdapterAssets(@PathParam("id") String id) { + try { + String result = null; + + Optional adapterDescriptionOptional = managementService.getAdapter(id); + if (adapterDescriptionOptional.isPresent()) { + AdapterDescription adapterDescription = adapterDescriptionOptional.get(); + String workerUrl = workerUrlProvider.getWorkerUrl(adapterDescription.getAppId()); + + result = managementService.getAssets(workerUrl); + } + + if (result == null) { + LOG.error("Not found adapter with id " + id); + return fail(); + } else { return ok(result); + } + } catch (AdapterException e) { + LOG.error("Not found adapter with id " + id, e); + return fail(); + } catch (NoServiceEndpointsAvailableException e) { + return fail(); } + } - @GET - @JacksonSerialized - @Path("/adapters") - @Produces(MediaType.APPLICATION_JSON) - public Response getAdapters() { - List result = managementService.getAdapters(); + @GET + @Path("/{id}/assets/icon") + @Produces("image/png") + public Response getAdapterIconAsset(@PathParam("id") String id) { + try { - return ok(result); - } + byte[] result = null; - @GET - @Path("/{id}/assets") - @Produces("application/zip") - public Response getAdapterAssets(@PathParam("id") String id) { - try { - String result = null; - - Optional adapterDescriptionOptional = managementService.getAdapter(id); - if (adapterDescriptionOptional.isPresent()) { - AdapterDescription adapterDescription = adapterDescriptionOptional.get(); - String workerUrl = workerUrlProvider.getWorkerUrl(adapterDescription.getAppId()); - - result = managementService.getAssets(workerUrl); - } - - if (result == null) { - LOG.error("Not found adapter with id " + id); - return fail(); - } else { - return ok(result); - } - } catch (AdapterException e) { - LOG.error("Not found adapter with id " + id, e); - return fail(); - } catch (NoServiceEndpointsAvailableException e) { - return fail(); - } - } + Optional adapterDescriptionOptional = managementService.getAdapter(id); + if (adapterDescriptionOptional.isPresent()) { + AdapterDescription adapterDescription = adapterDescriptionOptional.get(); + String workerUrl = workerUrlProvider.getWorkerUrl(adapterDescription.getAppId()); - @GET - @Path("/{id}/assets/icon") - @Produces("image/png") - public Response getAdapterIconAsset(@PathParam("id") String id) { - try { - - byte[] result = null; - - Optional adapterDescriptionOptional = managementService.getAdapter(id); - if (adapterDescriptionOptional.isPresent()) { - AdapterDescription adapterDescription = adapterDescriptionOptional.get(); - String workerUrl = workerUrlProvider.getWorkerUrl(adapterDescription.getAppId()); - - result = managementService.getIconAsset(workerUrl); - } - - if (result == null) { - LOG.error("Not found adapter with id " + id); - return fail(); - } else { - return ok(result); - } - } catch (AdapterException e) { - LOG.error("Not found adapter with id " + id); - return fail(); - } catch (NoServiceEndpointsAvailableException e) { - return fail(); - } - } + result = managementService.getIconAsset(workerUrl); + } - @GET - @Path("/{id}/assets/documentation") - @Produces(MediaType.TEXT_PLAIN) - public Response getAdapterDocumentationAsset(@PathParam("id") String id) { - try { - String result = null; - - Optional adapterDescriptionOptional = managementService.getAdapter(id); - if (adapterDescriptionOptional.isPresent()) { - AdapterDescription adapterDescription = adapterDescriptionOptional.get(); - String workerUrl = workerUrlProvider.getWorkerUrl(adapterDescription.getAppId()); - - result = managementService.getDocumentationAsset(workerUrl); - } - - if (result == null) { - LOG.error("Not found adapter with id " + id); - return fail(); - } else { - return ok(result); - } - } catch (AdapterException e) { - LOG.error("Not found adapter with id " + id, e); - return fail(); - } catch (NoServiceEndpointsAvailableException e) { - return fail(); - } + if (result == null) { + LOG.error("Not found adapter with id " + id); + return fail(); + } else { + return ok(result); + } + } catch (AdapterException e) { + LOG.error("Not found adapter with id " + id); + return fail(); + } catch (NoServiceEndpointsAvailableException e) { + return fail(); } - - @DELETE - @Path("{adapterId}") - public Response deleteAdapter(@PathParam("adapterId") String adapterId) { - try { - this.managementService.deleteAdapterDescription(adapterId); - return ok(); - } catch (SpRuntimeException e) { - return badRequest(e); - } + } + + @GET + @Path("/{id}/assets/documentation") + @Produces(MediaType.TEXT_PLAIN) + public Response getAdapterDocumentationAsset(@PathParam("id") String id) { + try { + String result = null; + + Optional adapterDescriptionOptional = managementService.getAdapter(id); + if (adapterDescriptionOptional.isPresent()) { + AdapterDescription adapterDescription = adapterDescriptionOptional.get(); + String workerUrl = workerUrlProvider.getWorkerUrl(adapterDescription.getAppId()); + + result = managementService.getDocumentationAsset(workerUrl); + } + + if (result == null) { + LOG.error("Not found adapter with id " + id); + return fail(); + } else { + return ok(result); + } + } catch (AdapterException e) { + LOG.error("Not found adapter with id " + id, e); + return fail(); + } catch (NoServiceEndpointsAvailableException e) { + return fail(); + } + } + + @DELETE + @Path("{adapterId}") + public Response deleteAdapter(@PathParam("adapterId") String adapterId) { + try { + this.managementService.deleteAdapterDescription(adapterId); + return ok(); + } catch (SpRuntimeException e) { + return badRequest(e); } + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/GuessResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/GuessResource.java index b678b9eab3..96ef1fddda 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/GuessResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/GuessResource.java @@ -27,6 +27,7 @@ import org.apache.streampipes.model.connect.guess.AdapterEventPreview; import org.apache.streampipes.model.connect.guess.GuessSchema; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,6 +37,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; @@ -54,19 +56,19 @@ public GuessResource() { @Produces(MediaType.APPLICATION_JSON) public Response guessSchema(AdapterDescription adapterDescription) { - try { - GuessSchema result = managementService.guessSchema(adapterDescription); + try { + GuessSchema result = managementService.guessSchema(adapterDescription); - return ok(result); - } catch (ParseException e) { - LOG.error("Error while parsing events: ", e); - return badRequest(StreamPipesErrorMessage.from(e)); - } catch (WorkerAdapterException e) { - return serverError(StreamPipesErrorMessage.from(e)); - } catch (NoServiceEndpointsAvailableException | IOException e) { - LOG.error(e.getMessage()); - return serverError(StreamPipesErrorMessage.from(e)); - } + return ok(result); + } catch (ParseException e) { + LOG.error("Error while parsing events: ", e); + return badRequest(StreamPipesErrorMessage.from(e)); + } catch (WorkerAdapterException e) { + return serverError(StreamPipesErrorMessage.from(e)); + } catch (NoServiceEndpointsAvailableException | IOException e) { + LOG.error(e.getMessage()); + return serverError(StreamPipesErrorMessage.from(e)); + } } @POST diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/RuntimeResolvableResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/RuntimeResolvableResource.java index 5f3fe1f67e..773b8e0999 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/RuntimeResolvableResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/RuntimeResolvableResource.java @@ -28,50 +28,55 @@ import org.apache.streampipes.model.runtime.RuntimeOptionsRequest; import org.apache.streampipes.model.runtime.RuntimeOptionsResponse; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/v2/connect/master/resolvable") public class RuntimeResolvableResource extends AbstractAdapterResource { - private static final Logger LOG = LoggerFactory.getLogger(RuntimeResolvableResource.class); + private static final Logger LOG = LoggerFactory.getLogger(RuntimeResolvableResource.class); - private final WorkerUrlProvider workerUrlProvider; + private final WorkerUrlProvider workerUrlProvider; - public RuntimeResolvableResource() { - super(WorkerAdministrationManagement::new); - this.workerUrlProvider = new WorkerUrlProvider(); - } + public RuntimeResolvableResource() { + super(WorkerAdministrationManagement::new); + this.workerUrlProvider = new WorkerUrlProvider(); + } - @POST - @Path("{id}/configurations") - @JacksonSerialized - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - public Response fetchConfigurations(@PathParam("id") String appId, - RuntimeOptionsRequest runtimeOptionsRequest) { + @POST + @Path("{id}/configurations") + @JacksonSerialized + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + public Response fetchConfigurations(@PathParam("id") String appId, + RuntimeOptionsRequest runtimeOptionsRequest) { - // TODO add solution for formats + // TODO add solution for formats - try { - String workerEndpoint = workerUrlProvider.getWorkerBaseUrl(appId); - RuntimeOptionsResponse result = WorkerRestClient.getConfiguration(workerEndpoint, appId, runtimeOptionsRequest); + try { + String workerEndpoint = workerUrlProvider.getWorkerBaseUrl(appId); + RuntimeOptionsResponse result = WorkerRestClient.getConfiguration(workerEndpoint, appId, runtimeOptionsRequest); - return ok(result); - } catch (AdapterException e) { - LOG.error("Adapter exception occurred", e); - return serverError(StreamPipesErrorMessage.from(e)); - } catch (NoServiceEndpointsAvailableException e) { - LOG.error("Could not find service endpoint for {} while fetching configuration", appId); - return serverError(StreamPipesErrorMessage.from(e)); - } catch (SpConfigurationException e) { - LOG.error("Tried to fetch a runtime configuration with insufficient settings"); - return badRequest(StreamPipesErrorMessage.from(e)); - } + return ok(result); + } catch (AdapterException e) { + LOG.error("Adapter exception occurred", e); + return serverError(StreamPipesErrorMessage.from(e)); + } catch (NoServiceEndpointsAvailableException e) { + LOG.error("Could not find service endpoint for {} while fetching configuration", appId); + return serverError(StreamPipesErrorMessage.from(e)); + } catch (SpConfigurationException e) { + LOG.error("Tried to fetch a runtime configuration with insufficient settings"); + return badRequest(StreamPipesErrorMessage.from(e)); } + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/SourcesResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/SourcesResource.java index 69542d7e72..463b10dda4 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/SourcesResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/SourcesResource.java @@ -23,52 +23,59 @@ import org.apache.streampipes.connect.container.master.management.SourcesManagement; import org.apache.streampipes.model.SpDataSet; import org.apache.streampipes.model.message.Notifications; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/v2/connect/master/sources") public class SourcesResource extends AbstractAdapterResource { - private static final Logger LOG = LoggerFactory.getLogger(SourcesResource.class); - - public SourcesResource() { - super(SourcesManagement::new); - } + private static final Logger LOG = LoggerFactory.getLogger(SourcesResource.class); - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response addSetAdapter(SpDataSet dataSet) { + public SourcesResource() { + super(SourcesManagement::new); + } - String responseMessage = "Instance of data set " + dataSet.getElementId() + " successfully started"; + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response addSetAdapter(SpDataSet dataSet) { - try { - managementService.addSetAdapter(dataSet); - } catch (AdapterException | NoServiceEndpointsAvailableException e) { - LOG.error("Could not set data set instance: " + dataSet.getElementId(), e); - return ok(Notifications.error("Could not set data set instance: " + dataSet.getElementId())); - } + String responseMessage = "Instance of data set " + dataSet.getElementId() + " successfully started"; - return ok(Notifications.success(responseMessage)); + try { + managementService.addSetAdapter(dataSet); + } catch (AdapterException | NoServiceEndpointsAvailableException e) { + LOG.error("Could not set data set instance: " + dataSet.getElementId(), e); + return ok(Notifications.error("Could not set data set instance: " + dataSet.getElementId())); } - @DELETE - @Path("{adapterId}/{runningInstanceId}") - @Produces(MediaType.APPLICATION_JSON) - public Response detach(@PathParam("adapterId") String elementId, @PathParam("runningInstanceId") String runningInstanceId) { - String responseMessage = "Instance id: "+ runningInstanceId + " successfully started"; + return ok(Notifications.success(responseMessage)); + } - try { - managementService.detachAdapter(elementId, runningInstanceId); - } catch (AdapterException | NoServiceEndpointsAvailableException e) { - LOG.error("Could not detach instance id: "+ runningInstanceId, e); - return fail(); - } + @DELETE + @Path("{adapterId}/{runningInstanceId}") + @Produces(MediaType.APPLICATION_JSON) + public Response detach(@PathParam("adapterId") String elementId, + @PathParam("runningInstanceId") String runningInstanceId) { + String responseMessage = "Instance id: " + runningInstanceId + " successfully started"; - return ok(Notifications.success(responseMessage)); + try { + managementService.detachAdapter(elementId, runningInstanceId); + } catch (AdapterException | NoServiceEndpointsAvailableException e) { + LOG.error("Could not detach instance id: " + runningInstanceId, e); + return fail(); } + + return ok(Notifications.success(responseMessage)); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/UnitResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/UnitResource.java index d89faa51f5..7c7d418707 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/UnitResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/UnitResource.java @@ -21,6 +21,7 @@ import org.apache.streampipes.connect.api.exception.AdapterException; import org.apache.streampipes.connect.container.master.management.UnitMasterManagement; import org.apache.streampipes.model.connect.unit.UnitDescription; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,23 +35,23 @@ @Path("/v2/connect/master/unit") public class UnitResource extends AbstractAdapterResource { - private static final Logger logger = LoggerFactory.getLogger(UnitResource.class); - - public UnitResource() { - super(UnitMasterManagement::new); - } - - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - public Response getFittingUnits(UnitDescription unitDescription) { - try { - String resultingJson = managementService.getFittingUnits(unitDescription); - return ok(resultingJson); - } catch (AdapterException e) { - logger.error("Error while getting all adapter descriptions", e); - return fail(); - } + private static final Logger logger = LoggerFactory.getLogger(UnitResource.class); + + public UnitResource() { + super(UnitMasterManagement::new); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response getFittingUnits(UnitDescription unitDescription) { + try { + String resultingJson = managementService.getFittingUnits(unitDescription); + return ok(resultingJson); + } catch (AdapterException e) { + logger.error("Error while getting all adapter descriptions", e); + return fail(); } + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/WelcomePageMaster.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/WelcomePageMaster.java index 5730300b9a..2504e9df05 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/WelcomePageMaster.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/WelcomePageMaster.java @@ -24,6 +24,7 @@ import org.apache.streampipes.connect.container.master.management.AdapterMasterManagement; import org.apache.streampipes.model.connect.adapter.AdapterDescription; import org.apache.streampipes.storage.couchdb.utils.CouchDbConfig; + import org.rendersnake.HtmlCanvas; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,58 +33,59 @@ import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; + import java.io.IOException; @Path("/v2/connect") public class WelcomePageMaster extends AbstractAdapterResource { - private Logger LOG = LoggerFactory.getLogger(WelcomePageMaster.class); - - public WelcomePageMaster() { - super(AdapterMasterManagement::new); - } - - @GET - @Produces(MediaType.TEXT_HTML) - public String getWelcomePageHtml() { - return buildHtml(); - } - - private String buildHtml() { - HtmlCanvas html = new HtmlCanvas(); - try { - HtmlCanvas tmp = html - .head() - .title() - .content("StreamPipes Connector Master Container") - ._head() - .body() - .h1().write("Connector Master Container")._h1() - .h2().write("All Running Adapters")._h2() - .ol(); - - getAllRunningAdapters(tmp); - - html = tmp._ol() - ._body(); - } catch (IOException e) { - LOG.error("Error in SP Connect Master Container: ", e); - } - - return html.toHtml(); - } - - private void getAllRunningAdapters(HtmlCanvas canvas) throws IOException { - - try { - for (AdapterDescription ad : managementService.getAllAdapterDescriptions()) { - canvas.li().write(ad.getElementId())._li(); - canvas.ul().li().write("Kafka Topic: " + GroundingService.extractTopic(ad))._li()._ul(); - } - } catch (AdapterException e) { - LOG.error("Could not connect to couchdb on URL: " + CouchDbConfig.INSTANCE.getHost(), e); - canvas.li().write("Error while connecting to CouchDB on Host: " + CouchDbConfig.INSTANCE.getHost())._li(); - } - } + private static final Logger LOG = LoggerFactory.getLogger(WelcomePageMaster.class); + + public WelcomePageMaster() { + super(AdapterMasterManagement::new); + } + + @GET + @Produces(MediaType.TEXT_HTML) + public String getWelcomePageHtml() { + return buildHtml(); + } + + private String buildHtml() { + HtmlCanvas html = new HtmlCanvas(); + try { + HtmlCanvas tmp = html + .head() + .title() + .content("StreamPipes Connector Master Container") + ._head() + .body() + .h1().write("Connector Master Container")._h1() + .h2().write("All Running Adapters")._h2() + .ol(); + + getAllRunningAdapters(tmp); + + html = tmp._ol() + ._body(); + } catch (IOException e) { + LOG.error("Error in SP Connect Master Container: ", e); + } + + return html.toHtml(); + } + + private void getAllRunningAdapters(HtmlCanvas canvas) throws IOException { + + try { + for (AdapterDescription ad : managementService.getAllAdapterDescriptions()) { + canvas.li().write(ad.getElementId())._li(); + canvas.ul().li().write("Kafka Topic: " + GroundingService.extractTopic(ad))._li()._ul(); + } + } catch (AdapterException e) { + LOG.error("Could not connect to couchdb on URL: " + CouchDbConfig.INSTANCE.getHost(), e); + canvas.li().write("Error while connecting to CouchDB on Host: " + CouchDbConfig.INSTANCE.getHost())._li(); + } + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/WorkerAdministrationResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/WorkerAdministrationResource.java index 48a6a481c7..ae5210eea8 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/WorkerAdministrationResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/connect/WorkerAdministrationResource.java @@ -29,25 +29,26 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.List; @Path("v2/connect/master/administration") public class WorkerAdministrationResource extends AbstractSharedRestInterface { - private WorkerAdministrationManagement workerAdministrationManagement; + private WorkerAdministrationManagement workerAdministrationManagement; - public WorkerAdministrationResource() { - this.workerAdministrationManagement = new WorkerAdministrationManagement(); - } + public WorkerAdministrationResource() { + this.workerAdministrationManagement = new WorkerAdministrationManagement(); + } - @POST - @JacksonSerialized - @Produces(MediaType.APPLICATION_JSON) - public Response addWorkerContainer(List availableAdapterDescription) { + @POST + @JacksonSerialized + @Produces(MediaType.APPLICATION_JSON) + public Response addWorkerContainer(List availableAdapterDescription) { - this.workerAdministrationManagement.register(availableAdapterDescription); + this.workerAdministrationManagement.register(availableAdapterDescription); - return ok(Notifications.success("Worker Container successfully added")); - } + return ok(Notifications.success("Worker Container successfully added")); + } } 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 3638e5d4a2..4cad2f9a54 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 @@ -22,12 +22,20 @@ import org.apache.streampipes.resource.management.AbstractDashboardResourceManager; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.List; public abstract class AbstractDashboardResource extends AbstractAuthGuardedRestResource { diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/AbstractPipelineExtractionResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/AbstractPipelineExtractionResource.java index 21ea0733cf..8d7eece977 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/AbstractPipelineExtractionResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/AbstractPipelineExtractionResource.java @@ -23,6 +23,7 @@ import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; import javax.ws.rs.core.Response; + import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -36,20 +37,20 @@ protected Response getPipelineByIdAndFieldValue(String appId, List pipelines = extract(new ArrayList<>(), appId); Optional matchedPipeline = - pipelines - .stream() - .filter(pipeline -> matches(pipeline, pipelineId, fieldValue)).findFirst(); + pipelines + .stream() + .filter(pipeline -> matches(pipeline, pipelineId, fieldValue)).findFirst(); return matchedPipeline.isPresent() ? ok(matchedPipeline.get()) : fail(); } protected List extract(List target, String appId) { getPipelineStorage() - .getAllPipelines() - .forEach(pipeline -> { - List sinks = extractSink(pipeline, appId); - sinks.forEach(sink -> target.add(convert(pipeline, sink))); - }); + .getAllPipelines() + .forEach(pipeline -> { + List sinks = extractSink(pipeline, appId); + sinks.forEach(sink -> target.add(convert(pipeline, sink))); + }); return target; } @@ -57,32 +58,32 @@ protected abstract T convert(Pipeline pipeline, DataSinkInvocation sink); protected abstract boolean matches(T resourceToExtract, - String pipelineId, - String fieldValue); + String pipelineId, + String fieldValue); protected List extractSink(Pipeline pipeline, String appId) { return pipeline - .getActions() - .stream() - .filter(sink -> sink.getAppId().equals(appId)) - .collect(Collectors.toList()); + .getActions() + .stream() + .filter(sink -> sink.getAppId().equals(appId)) + .collect(Collectors.toList()); } protected String extractFieldValue(DataSinkInvocation sink, String fieldName) { return sink.getStaticProperties() - .stream() - .filter(sp -> sp.getInternalName().equals(fieldName)) - .map(sp -> (FreeTextStaticProperty) sp) - .findFirst().get().getValue(); + .stream() + .filter(sp -> sp.getInternalName().equals(fieldName)) + .map(sp -> (FreeTextStaticProperty) sp) + .findFirst().get().getValue(); } protected String extractInputTopic(DataSinkInvocation sink) { return sink - .getInputStreams() - .get(0) - .getEventGrounding() - .getTransportProtocol() - .getTopicDefinition() - .getActualTopicName(); + .getInputStreams() + .get(0) + .getEventGrounding() + .getTransportProtocol() + .getTopicDefinition() + .getActualTopicName(); } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/Dashboard.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/Dashboard.java index 144c7d9a71..0357625cd3 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/Dashboard.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/Dashboard.java @@ -19,34 +19,33 @@ package org.apache.streampipes.rest.impl.dashboard; import org.apache.streampipes.model.client.user.Privilege; -import org.apache.streampipes.model.client.user.Role; import org.apache.streampipes.resource.management.AbstractDashboardResourceManager; + import org.springframework.stereotype.Component; import javax.ws.rs.Path; -import java.util.Arrays; @Path("/v2/dashboard/dashboards") @Component public class Dashboard extends AbstractDashboardResource { - @Override - protected AbstractDashboardResourceManager getResourceManager() { - return getSpResourceManager().manageDashboards(); - } - - @Override - public boolean hasReadAuthority() { - return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_READ_DASHBOARD_VALUE); - } - - @Override - public boolean hasWriteAuthority() { - return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_WRITE_DASHBOARD_VALUE); - } - - @Override - public boolean hasDeleteAuthority() { - return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_DELETE_DASHBOARD_VALUE); - } + @Override + protected AbstractDashboardResourceManager getResourceManager() { + return getSpResourceManager().manageDashboards(); + } + + @Override + public boolean hasReadAuthority() { + return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_READ_DASHBOARD_VALUE); + } + + @Override + public boolean hasWriteAuthority() { + return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_WRITE_DASHBOARD_VALUE); + } + + @Override + public boolean hasDeleteAuthority() { + return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_DELETE_DASHBOARD_VALUE); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/DashboardWidget.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/DashboardWidget.java index a3e00958b0..316f28c54a 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/DashboardWidget.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/DashboardWidget.java @@ -23,7 +23,14 @@ import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.storage.api.IDashboardWidgetStorage; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/VisualizablePipelineResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/VisualizablePipelineResource.java index 79ecdbd6fa..ab087cf29f 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/VisualizablePipelineResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/dashboard/VisualizablePipelineResource.java @@ -23,6 +23,7 @@ import org.apache.streampipes.model.pipeline.Pipeline; import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; @@ -33,6 +34,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.ArrayList; import java.util.List; @@ -57,7 +59,8 @@ public List getVisualizablePipelines() { @Produces(MediaType.APPLICATION_JSON) @Path("{pipelineId}/{visualizationName}") public Response getVisualizablePipelineByPipelineIdAndVisualizationName(@PathParam("pipelineId") String pipelineId, - @PathParam("visualizationName") String visualizationName) { + @PathParam("visualizationName") + String visualizationName) { return getPipelineByIdAndFieldValue(DashboardAppId, pipelineId, visualizationName); } @@ -70,7 +73,8 @@ private String normalize(String visualizationName) { } @Override - protected org.apache.streampipes.model.dashboard.VisualizablePipeline convert(Pipeline pipeline, DataSinkInvocation sink) { + protected org.apache.streampipes.model.dashboard.VisualizablePipeline convert(Pipeline pipeline, + DataSinkInvocation sink) { VisualizablePipeline visualizablePipeline = new org.apache.streampipes.model.dashboard.VisualizablePipeline(); visualizablePipeline.setPipelineId(pipeline.getPipelineId()); visualizablePipeline.setPipelineName(pipeline.getName()); @@ -85,6 +89,6 @@ protected boolean matches(VisualizablePipeline pipeline, String pipelineId, String visualizationName) { return pipeline.getPipelineId().equals(pipelineId) - && pipeline.getVisualizationName().equals(visualizationName); + && pipeline.getVisualizationName().equals(visualizationName); } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/DataLakeDashboardResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/DataLakeDashboardResource.java index 6aa6a5f79f..7b02a97fb8 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/DataLakeDashboardResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/DataLakeDashboardResource.java @@ -20,9 +20,9 @@ import org.apache.streampipes.model.client.user.Privilege; -import org.apache.streampipes.model.client.user.Role; import org.apache.streampipes.resource.management.AbstractDashboardResourceManager; import org.apache.streampipes.rest.impl.dashboard.AbstractDashboardResource; + import org.springframework.stereotype.Component; import javax.ws.rs.Path; @@ -31,23 +31,23 @@ @Component public class DataLakeDashboardResource extends AbstractDashboardResource { - @Override - protected AbstractDashboardResourceManager getResourceManager() { - return getSpResourceManager().manageDataExplorer(); - } - - @Override - public boolean hasReadAuthority() { - return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_READ_DATA_EXPLORER_VIEW_VALUE); - } - - @Override - public boolean hasWriteAuthority() { - return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_WRITE_DATA_EXPLORER_VIEW_VALUE); - } - - @Override - public boolean hasDeleteAuthority() { - return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_DELETE_DATA_EXPLORER_VIEW_VALUE); - } + @Override + protected AbstractDashboardResourceManager getResourceManager() { + return getSpResourceManager().manageDataExplorer(); + } + + @Override + public boolean hasReadAuthority() { + return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_READ_DATA_EXPLORER_VIEW_VALUE); + } + + @Override + public boolean hasWriteAuthority() { + return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_WRITE_DATA_EXPLORER_VIEW_VALUE); + } + + @Override + public boolean hasDeleteAuthority() { + return isAdminOrHasAnyAuthority(Privilege.Constants.PRIVILEGE_DELETE_DATA_EXPLORER_VIEW_VALUE); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/DataLakeWidgetResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/DataLakeWidgetResource.java index e2d7a796dd..c8003ff36d 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/DataLakeWidgetResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/DataLakeWidgetResource.java @@ -23,7 +23,14 @@ import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.storage.api.IDataExplorerWidgetStorage; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/PersistedDataStreamResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/PersistedDataStreamResource.java index 26479f3fdf..10e892c029 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/PersistedDataStreamResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/datalake/PersistedDataStreamResource.java @@ -23,6 +23,7 @@ import org.apache.streampipes.rest.impl.dashboard.AbstractPipelineExtractionResource; import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; @@ -33,6 +34,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.ArrayList; import java.util.List; @@ -57,7 +59,8 @@ public List getPersistedDataStreams() { @Produces(MediaType.APPLICATION_JSON) @Path("{pipelineId}/{measureName}") public Response getVisualizablePipelineByPipelineIdAndVisualizationName(@PathParam("pipelineId") String pipelineId, - @PathParam("measureName") String measureName) { + @PathParam("measureName") + String measureName) { return getPipelineByIdAndFieldValue(DataLakeAppId, pipelineId, measureName); } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/nouser/PipelineElementImportNoUser.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/nouser/PipelineElementImportNoUser.java index a405fd0317..6e9ad373fd 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/nouser/PipelineElementImportNoUser.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/nouser/PipelineElementImportNoUser.java @@ -25,10 +25,15 @@ import org.apache.streampipes.model.message.NotificationType; import org.apache.streampipes.rest.core.base.impl.AbstractRestResource; import org.apache.streampipes.storage.api.IPipelineElementDescriptionStorageCache; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.ws.rs.*; +import javax.ws.rs.FormParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -74,7 +79,8 @@ public Response deleteElement(@PathParam("username") String username, userService.deleteOwnSource(username, uri); requestor.refreshDataSourceCache(); } else { - return constructErrorMessage(new Notification(NotificationType.STORAGE_ERROR.title(), NotificationType.STORAGE_ERROR.description())); + return constructErrorMessage( + new Notification(NotificationType.STORAGE_ERROR.title(), NotificationType.STORAGE_ERROR.description())); } return constructSuccessMessage(NotificationType.STORAGE_SUCCESS.uiNotification()); } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataProcessorResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataProcessorResource.java index a04e4b4efd..316b6e7344 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataProcessorResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataProcessorResource.java @@ -25,60 +25,66 @@ import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; + import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.List; @Path("/v2/sepas") @Component public class DataProcessorResource extends AbstractAuthGuardedRestResource { - @GET - @Path("/available") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - @PreAuthorize(AuthConstants.HAS_READ_PIPELINE_ELEMENT_PRIVILEGE) - @PostFilter("hasPermission(filterObject.elementId, 'READ')") - public List getAvailable() { - return getDataProcessorResourceManager().findAll(); - } + @GET + @Path("/available") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + @PreAuthorize(AuthConstants.HAS_READ_PIPELINE_ELEMENT_PRIVILEGE) + @PostFilter("hasPermission(filterObject.elementId, 'READ')") + public List getAvailable() { + return getDataProcessorResourceManager().findAll(); + } + + @GET + @Path("/own") + @JacksonSerialized + @Produces({MediaType.APPLICATION_JSON}) + @PreAuthorize(AuthConstants.HAS_READ_PIPELINE_ELEMENT_PRIVILEGE) + @PostFilter("hasPermission(filterObject.belongsTo, 'READ')") + public List getOwn() { + return getDataProcessorResourceManager().findAllAsInvocation(); + } - @GET - @Path("/own") - @JacksonSerialized - @Produces({MediaType.APPLICATION_JSON}) - @PreAuthorize(AuthConstants.HAS_READ_PIPELINE_ELEMENT_PRIVILEGE) - @PostFilter("hasPermission(filterObject.belongsTo, 'READ')") - public List getOwn() { - return getDataProcessorResourceManager().findAllAsInvocation(); - } - - @DELETE - @Path("/own/{elementId}") - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - @PreAuthorize(AuthConstants.HAS_DELETE_PIPELINE_ELEMENT_PRIVILEGE) - public Response removeOwn(@PathParam("elementId") String elementId) { - getDataProcessorResourceManager().delete(elementId); - return constructSuccessMessage(NotificationType.STORAGE_SUCCESS.uiNotification()); - } + @DELETE + @Path("/own/{elementId}") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + @PreAuthorize(AuthConstants.HAS_DELETE_PIPELINE_ELEMENT_PRIVILEGE) + public Response removeOwn(@PathParam("elementId") String elementId) { + getDataProcessorResourceManager().delete(elementId); + return constructSuccessMessage(NotificationType.STORAGE_SUCCESS.uiNotification()); + } - @Path("/{elementId}") - @GET - @Produces(MediaType.APPLICATION_JSON) - @JacksonSerialized - @PreAuthorize(AuthConstants.HAS_READ_PIPELINE_ELEMENT_PRIVILEGE) - public DataProcessorInvocation getElement(@PathParam("elementId") String elementId) { - return getDataProcessorResourceManager().findAsInvocation(elementId); - } + @Path("/{elementId}") + @GET + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + @PreAuthorize(AuthConstants.HAS_READ_PIPELINE_ELEMENT_PRIVILEGE) + public DataProcessorInvocation getElement(@PathParam("elementId") String elementId) { + return getDataProcessorResourceManager().findAsInvocation(elementId); + } - private DataProcessorResourceManager getDataProcessorResourceManager() { - return getSpResourceManager().manageDataProcessors(); - } + private DataProcessorResourceManager getDataProcessorResourceManager() { + return getSpResourceManager().manageDataProcessors(); + } } diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataSinkResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataSinkResource.java index 9cc4daf6bd..d890ae1d80 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataSinkResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataSinkResource.java @@ -26,13 +26,19 @@ import org.apache.streampipes.rest.security.AuthConstants; import org.apache.streampipes.rest.shared.annotation.JacksonSerialized; import org.apache.streampipes.rest.shared.util.SpMediaType; + import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.util.List; @Path("/v2/actions") diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/security/AuthConstants.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/security/AuthConstants.java index 8bf2d81a85..325cb27529 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/security/AuthConstants.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/security/AuthConstants.java @@ -17,8 +17,29 @@ */ package org.apache.streampipes.rest.security; -import static org.apache.streampipes.model.client.user.Privilege.Constants.*; -import static org.apache.streampipes.model.client.user.Role.Constants.*; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_DELETE_ADAPTER_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_DELETE_PIPELINE_ELEMENT_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_DELETE_PIPELINE_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_READ_ADAPTER_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_READ_ASSETS_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_READ_DASHBOARD_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_READ_DATA_EXPLORER_VIEW_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_READ_FILES_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_READ_GENERIC_STORAGE_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_READ_PIPELINE_ELEMENT_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_READ_PIPELINE_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_WRITE_ADAPTER_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_WRITE_ASSETS_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_WRITE_DASHBOARD_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_WRITE_DATA_EXPLORER_VIEW_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_WRITE_GENERIC_STORAGE_VALUE; +import static org.apache.streampipes.model.client.user.Privilege.Constants.PRIVILEGE_WRITE_PIPELINE_VALUE; +import static org.apache.streampipes.model.client.user.Role.Constants.ROLE_ADMIN_VALUE; +import static org.apache.streampipes.model.client.user.Role.Constants.ROLE_DASHBOARD_ADMIN_VALUE; +import static org.apache.streampipes.model.client.user.Role.Constants.ROLE_DASHBOARD_USER_VALUE; +import static org.apache.streampipes.model.client.user.Role.Constants.ROLE_PIPELINE_ADMIN_VALUE; +import static org.apache.streampipes.model.client.user.Role.Constants.ROLE_PIPELINE_USER_VALUE; +import static org.apache.streampipes.model.client.user.Role.Constants.ROLE_SERVICE_ADMIN_VALUE; public class AuthConstants { @@ -30,7 +51,8 @@ public class AuthConstants { private static final String BE2 = "))"; private static final String OR = " or "; - public static final String IS_ADMIN_ROLE = HAS_ANY_AUTHORITY + ROLE_ADMIN_VALUE + Q + ", '" + ROLE_SERVICE_ADMIN_VALUE +Q + BE; + public static final String IS_ADMIN_ROLE = + HAS_ANY_AUTHORITY + ROLE_ADMIN_VALUE + Q + ", '" + ROLE_SERVICE_ADMIN_VALUE + Q + BE; public static final String IS_PIPELINE_ADMIN_ROLE = HAS_ANY_ROLE + ROLE_PIPELINE_ADMIN_VALUE + Q + BE; public static final String IS_PIPELINE_USER_ROLE = HAS_ANY_ROLE + ROLE_PIPELINE_USER_VALUE + Q + BE; @@ -38,30 +60,47 @@ public class AuthConstants { public static final String IS_DASHBOARD_ADMIN_ROLE = HAS_ANY_ROLE + ROLE_DASHBOARD_ADMIN_VALUE + Q + BE; public static final String IS_DASHBOARD_USER_ROLE = HAS_ANY_ROLE + ROLE_DASHBOARD_USER_VALUE + Q + BE; - public static final String HAS_READ_PIPELINE_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_PIPELINE_VALUE + Q + BE2; - public static final String HAS_WRITE_PIPELINE_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_PIPELINE_VALUE + Q + BE2; - public static final String HAS_DELETE_PIPELINE_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_DELETE_PIPELINE_VALUE + Q + BE2; - - public static final String HAS_READ_PIPELINE_ELEMENT_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_PIPELINE_ELEMENT_VALUE + Q + BE2; - public static final String HAS_DELETE_PIPELINE_ELEMENT_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_DELETE_PIPELINE_ELEMENT_VALUE + Q + BE2; - - public static final String HAS_WRITE_ADAPTER_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_ADAPTER_VALUE + Q + BE2; - public static final String HAS_READ_ADAPTER_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_ADAPTER_VALUE + Q + BE2; - public static final String HAS_DELETE_ADAPTER_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_DELETE_ADAPTER_VALUE + Q + BE2; - - public static final String HAS_WRITE_DATA_EXPLORER_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_DATA_EXPLORER_VIEW_VALUE + Q + BE2; - public static final String HAS_READ_DATA_EXPLORER_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_DATA_EXPLORER_VIEW_VALUE + Q + BE2; - - public static final String HAS_WRITE_DASHBOARD_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_DASHBOARD_VALUE + Q + BE2; - public static final String HAS_READ_DASHBOARD_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_DASHBOARD_VALUE + Q + BE2; - - public static final String HAS_READ_FILE_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_FILES_VALUE + Q + BE2; - - public static final String HAS_READ_ASSETS_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_ASSETS_VALUE + Q + BE2; - public static final String HAS_WRITE_ASSETS_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_ASSETS_VALUE + Q + BE2; - - public static final String HAS_READ_GENERIC_STORAGE_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_GENERIC_STORAGE_VALUE + Q + BE2; - public static final String HAS_WRITE_GENERIC_STORAGE_PRIVILEGE = BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_GENERIC_STORAGE_VALUE + Q + BE2; + public static final String HAS_READ_PIPELINE_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_PIPELINE_VALUE + Q + BE2; + public static final String HAS_WRITE_PIPELINE_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_PIPELINE_VALUE + Q + BE2; + public static final String HAS_DELETE_PIPELINE_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_DELETE_PIPELINE_VALUE + Q + BE2; + + public static final String HAS_READ_PIPELINE_ELEMENT_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_PIPELINE_ELEMENT_VALUE + Q + BE2; + public static final String HAS_DELETE_PIPELINE_ELEMENT_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_DELETE_PIPELINE_ELEMENT_VALUE + Q + BE2; + + public static final String HAS_WRITE_ADAPTER_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_ADAPTER_VALUE + Q + BE2; + public static final String HAS_READ_ADAPTER_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_ADAPTER_VALUE + Q + BE2; + public static final String HAS_DELETE_ADAPTER_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_DELETE_ADAPTER_VALUE + Q + BE2; + + public static final String HAS_WRITE_DATA_EXPLORER_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_DATA_EXPLORER_VIEW_VALUE + Q + BE2; + public static final String HAS_READ_DATA_EXPLORER_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_DATA_EXPLORER_VIEW_VALUE + Q + BE2; + + public static final String HAS_WRITE_DASHBOARD_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_DASHBOARD_VALUE + Q + BE2; + public static final String HAS_READ_DASHBOARD_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_DASHBOARD_VALUE + Q + BE2; + + public static final String HAS_READ_FILE_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_FILES_VALUE + Q + BE2; + + public static final String HAS_READ_ASSETS_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_ASSETS_VALUE + Q + BE2; + public static final String HAS_WRITE_ASSETS_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_ASSETS_VALUE + Q + BE2; + + public static final String HAS_READ_GENERIC_STORAGE_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_READ_GENERIC_STORAGE_VALUE + Q + BE2; + public static final String HAS_WRITE_GENERIC_STORAGE_PRIVILEGE = + BS + IS_ADMIN_ROLE + OR + HAS_ANY_AUTHORITY + PRIVILEGE_WRITE_GENERIC_STORAGE_VALUE + Q + BE2; public static final String IS_AUTHENTICATED = "isAuthenticated()"; diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/security/SpPermissionEvaluator.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/security/SpPermissionEvaluator.java index a39cf58dc5..62364a9846 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/security/SpPermissionEvaluator.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/security/SpPermissionEvaluator.java @@ -23,6 +23,7 @@ import org.apache.streampipes.model.pipeline.PipelineElementRecommendationMessage; import org.apache.streampipes.storage.management.StorageDispatcher; import org.apache.streampipes.user.management.model.PrincipalUserDetails; + import org.springframework.context.annotation.Configuration; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.core.Authentication; @@ -66,7 +67,8 @@ public boolean hasPermission(Authentication auth, Serializable serializable, Str } private boolean hasPermission(Authentication auth, String objectInstanceId) { - return isPublicElement(objectInstanceId) || getUserDetails(auth).getAllObjectPermissions().contains(objectInstanceId); + return isPublicElement(objectInstanceId) + || getUserDetails(auth).getAllObjectPermissions().contains(objectInstanceId); } private PrincipalUserDetails getUserDetails(Authentication authentication) { @@ -74,14 +76,15 @@ private PrincipalUserDetails getUserDetails(Authentication authentication) { } private boolean isPublicElement(String objectInstanceId) { - List permissions = StorageDispatcher.INSTANCE.getNoSqlStore().getPermissionStorage().getUserPermissionsForObject(objectInstanceId); + List permissions = + StorageDispatcher.INSTANCE.getNoSqlStore().getPermissionStorage().getUserPermissionsForObject(objectInstanceId); return permissions.size() > 0 && permissions.get(0).isPublicElement(); } private boolean isAdmin(PrincipalUserDetails userDetails) { return userDetails - .getAuthorities() - .stream() - .anyMatch(a -> a.getAuthority().equals(Role.Constants.ROLE_ADMIN_VALUE)); + .getAuthorities() + .stream() + .anyMatch(a -> a.getAuthority().equals(Role.Constants.ROLE_ADMIN_VALUE)); } } diff --git a/streampipes-rest/src/test/java/org/apache/streampipes/dataexplorer/v4/params/WhereStatementParamsTest.java b/streampipes-rest/src/test/java/org/apache/streampipes/dataexplorer/v4/params/WhereStatementParamsTest.java index c58f6f2049..694af53691 100644 --- a/streampipes-rest/src/test/java/org/apache/streampipes/dataexplorer/v4/params/WhereStatementParamsTest.java +++ b/streampipes-rest/src/test/java/org/apache/streampipes/dataexplorer/v4/params/WhereStatementParamsTest.java @@ -15,6 +15,7 @@ * limitations under the License. * */ + package org.apache.streampipes.dataexplorer.v4.params; import org.junit.Test; @@ -22,36 +23,37 @@ import static org.junit.Assert.assertEquals; public class WhereStatementParamsTest { - @Test - public void filterNumber() { - WhereStatementParams result = WhereStatementParams.from("", "[fieldName;=;6]"); - WhereCondition expected = new WhereCondition("fieldName", "=", "6"); - - assertWhereCondition(result, expected); - } - - @Test - public void filterBoolean() { - WhereStatementParams result = WhereStatementParams.from("", "[fieldName;=;true]"); - WhereCondition expected = new WhereCondition("fieldName", "=", "true"); - - assertWhereCondition(result, expected); - } - - @Test - public void filterString() { - WhereStatementParams result = WhereStatementParams.from("", "[fieldName;=;a]"); - WhereCondition expected = new WhereCondition("fieldName", "=", "'a'"); - - assertWhereCondition(result, expected); - } - private void assertWhereCondition(WhereStatementParams result, WhereCondition expected) { - assertEquals(1, result.getWhereConditions().size()); - WhereCondition resultingWhereCondition = result.getWhereConditions().get(0); - assertEquals(expected.getField(), resultingWhereCondition.getField()); - assertEquals(expected.getOperator(), resultingWhereCondition.getOperator()); - assertEquals(expected.getCondition(), resultingWhereCondition.getCondition()); - } - - -} \ No newline at end of file + @Test + public void filterNumber() { + WhereStatementParams result = WhereStatementParams.from("", "[fieldName;=;6]"); + WhereCondition expected = new WhereCondition("fieldName", "=", "6"); + + assertWhereCondition(result, expected); + } + + @Test + public void filterBoolean() { + WhereStatementParams result = WhereStatementParams.from("", "[fieldName;=;true]"); + WhereCondition expected = new WhereCondition("fieldName", "=", "true"); + + assertWhereCondition(result, expected); + } + + @Test + public void filterString() { + WhereStatementParams result = WhereStatementParams.from("", "[fieldName;=;a]"); + WhereCondition expected = new WhereCondition("fieldName", "=", "'a'"); + + assertWhereCondition(result, expected); + } + + private void assertWhereCondition(WhereStatementParams result, WhereCondition expected) { + assertEquals(1, result.getWhereConditions().size()); + WhereCondition resultingWhereCondition = result.getWhereConditions().get(0); + assertEquals(expected.getField(), resultingWhereCondition.getField()); + assertEquals(expected.getOperator(), resultingWhereCondition.getOperator()); + assertEquals(expected.getCondition(), resultingWhereCondition.getCondition()); + } + + +} From 6f72d49ae07c5686678994fe560629f6c2999e34 Mon Sep 17 00:00:00 2001 From: Philipp Zehnder Date: Thu, 1 Dec 2022 13:50:31 +0100 Subject: [PATCH 02/10] [hotfix] Remove old route that is no longer used --- .../backend/StreamPipesResourceConfig.java | 2 - .../nouser/PipelineElementImportNoUser.java | 88 ------------------- 2 files changed, 90 deletions(-) delete mode 100644 streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/nouser/PipelineElementImportNoUser.java diff --git a/streampipes-backend/src/main/java/org/apache/streampipes/backend/StreamPipesResourceConfig.java b/streampipes-backend/src/main/java/org/apache/streampipes/backend/StreamPipesResourceConfig.java index abab204fff..07a98cce44 100644 --- a/streampipes-backend/src/main/java/org/apache/streampipes/backend/StreamPipesResourceConfig.java +++ b/streampipes-backend/src/main/java/org/apache/streampipes/backend/StreamPipesResourceConfig.java @@ -29,7 +29,6 @@ import org.apache.streampipes.rest.impl.datalake.DataLakeDashboardResource; import org.apache.streampipes.rest.impl.datalake.DataLakeWidgetResource; import org.apache.streampipes.rest.impl.datalake.PersistedDataStreamResource; -import org.apache.streampipes.rest.impl.nouser.PipelineElementImportNoUser; import org.apache.streampipes.rest.impl.pe.DataProcessorResource; import org.apache.streampipes.rest.impl.pe.DataSinkResource; import org.apache.streampipes.rest.impl.pe.DataStreamResource; @@ -85,7 +84,6 @@ public StreamPipesResourceConfig() { register(PipelineElementAsset.class); register(PipelineElementCategory.class); register(PipelineElementFile.class); - register(PipelineElementImportNoUser.class); register(PipelineElementImport.class); register(PipelineElementPreview.class); register(PipelineElementRuntimeInfo.class); diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/nouser/PipelineElementImportNoUser.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/nouser/PipelineElementImportNoUser.java deleted file mode 100644 index 6e9ad373fd..0000000000 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/nouser/PipelineElementImportNoUser.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.apache.streampipes.rest.impl.nouser; - -import org.apache.streampipes.manager.endpoint.EndpointItemParser; -import org.apache.streampipes.manager.storage.UserService; -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.rest.core.base.impl.AbstractRestResource; -import org.apache.streampipes.storage.api.IPipelineElementDescriptionStorageCache; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.FormParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -@Path("/v2/noauth/users/{username}/element") -public class PipelineElementImportNoUser extends AbstractRestResource { - - private static final Logger logger = LoggerFactory.getLogger(PipelineElementImportNoUser.class); - - @Context - UriInfo uri; - - @POST - @Produces(MediaType.APPLICATION_JSON) - public Response addElement(@PathParam("username") String username, - @FormParam("uri") String uri, - @FormParam("publicElement") boolean publicElement) { - logger.info("User " + username + " adds element with URI: " + uri + " to triplestore"); - - return ok(verifyAndAddElement(uri, username, publicElement)); - } - - private Message verifyAndAddElement(String uri, - String username, - boolean publicElement) { - return new EndpointItemParser().parseAndAddEndpointItem(uri, username, publicElement); - } - - @Path("/delete") - @POST - @Produces(MediaType.APPLICATION_JSON) - public Response deleteElement(@PathParam("username") String username, - @FormParam("uri") String uri) { - - UserService userService = getUserService(); - IPipelineElementDescriptionStorageCache requestor = getPipelineElementRdfStorage(); - - logger.info("User " + username + " deletes element with URI: " + uri + " from triplestore"); - - if (requestor.getDataStreamById(uri) != null) { - requestor.deleteDataStream(requestor.getDataStreamById(uri)); - userService.deleteOwnSource(username, uri); - requestor.refreshDataSourceCache(); - } else { - return constructErrorMessage( - new Notification(NotificationType.STORAGE_ERROR.title(), NotificationType.STORAGE_ERROR.description())); - } - return constructSuccessMessage(NotificationType.STORAGE_SUCCESS.uiNotification()); - } - -} From b11227ed5b67895200b9de7d728fcf4a181118ac Mon Sep 17 00:00:00 2001 From: Dominik Riemer Date: Thu, 1 Dec 2022 19:55:25 +0100 Subject: [PATCH 03/10] Enable checkstyle for streampipes-messaging --- streampipes-messaging/pom.xml | 24 ++++++++++++++++++- .../streampipes/messaging/EventConsumer.java | 10 ++++---- .../streampipes/messaging/EventProducer.java | 10 ++++---- .../messaging/SpProtocolDefinition.java | 6 ++--- .../messaging/SpProtocolManager.java | 19 +++++++-------- 5 files changed, 45 insertions(+), 24 deletions(-) diff --git a/streampipes-messaging/pom.xml b/streampipes-messaging/pom.xml index bc9af0206a..1415a3beb9 100644 --- a/streampipes-messaging/pom.xml +++ b/streampipes-messaging/pom.xml @@ -35,4 +35,26 @@ 0.71.0-SNAPSHOT - \ No newline at end of file + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + validate + validate + + check + + + + + true + true + + + + + diff --git a/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/EventConsumer.java b/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/EventConsumer.java index 3e276df67a..dec6f0258f 100644 --- a/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/EventConsumer.java +++ b/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/EventConsumer.java @@ -21,12 +21,12 @@ import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.model.grounding.TransportProtocol; -public interface EventConsumer { +public interface EventConsumer { - void connect(TP protocolSettings, InternalEventProcessor eventProcessor) throws - SpRuntimeException; + void connect(T protocolSettings, InternalEventProcessor eventProcessor) throws + SpRuntimeException; - void disconnect() throws SpRuntimeException; + void disconnect() throws SpRuntimeException; - boolean isConnected(); + boolean isConnected(); } diff --git a/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/EventProducer.java b/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/EventProducer.java index 9d3998bc7f..20993d932d 100644 --- a/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/EventProducer.java +++ b/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/EventProducer.java @@ -23,13 +23,13 @@ import java.io.Serializable; -public interface EventProducer extends Serializable { +public interface EventProducer extends Serializable { - void connect(TP protocolSettings) throws SpRuntimeException; + void connect(T protocolSettings) throws SpRuntimeException; - void publish(byte[] event); + void publish(byte[] event); - void disconnect() throws SpRuntimeException; + void disconnect() throws SpRuntimeException; - boolean isConnected(); + boolean isConnected(); } diff --git a/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/SpProtocolDefinition.java b/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/SpProtocolDefinition.java index 2a1655c3bb..cd24baad59 100644 --- a/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/SpProtocolDefinition.java +++ b/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/SpProtocolDefinition.java @@ -20,9 +20,9 @@ import org.apache.streampipes.model.grounding.TransportProtocol; -public interface SpProtocolDefinition { +public interface SpProtocolDefinition { - EventConsumer getConsumer(); + EventConsumer getConsumer(); - EventProducer getProducer(); + EventProducer getProducer(); } diff --git a/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/SpProtocolManager.java b/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/SpProtocolManager.java index d15199f4e5..35e2d9b6e6 100644 --- a/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/SpProtocolManager.java +++ b/streampipes-messaging/src/main/java/org/apache/streampipes/messaging/SpProtocolManager.java @@ -28,7 +28,7 @@ public enum SpProtocolManager { INSTANCE; - private List> availableProtocols; + private final List> availableProtocols; SpProtocolManager() { this.availableProtocols = new ArrayList<>(); @@ -42,17 +42,16 @@ public List> getAvailab return availableProtocols; } - public Optional> findDefinition(T - transportProtocol) { + public Optional> findDefinition(T transportProtocol) { // TODO add RDF URI for protocol in model return this.availableProtocols - .stream() - .filter - (adf -> adf.getTransportProtocolClass().equals(transportProtocol.getClass() - .getCanonicalName())) - .map(s -> (SpProtocolDefinitionFactory) s) - .map(SpProtocolDefinitionFactory::createInstance) - .findFirst(); + .stream() + .filter + (adf -> adf.getTransportProtocolClass().equals(transportProtocol.getClass() + .getCanonicalName())) + .map(s -> (SpProtocolDefinitionFactory) s) + .map(SpProtocolDefinitionFactory::createInstance) + .findFirst(); } } From a08d295ef0f6d9fd457b89d8639e038a64973bca Mon Sep 17 00:00:00 2001 From: Philipp Zehnder Date: Thu, 1 Dec 2022 21:01:39 +0100 Subject: [PATCH 04/10] [hotfix] Resolve checkstyle issues due to merge conflicts --- .../streampipes/rest/impl/UserResource.java | 50 ++++++++++++------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/UserResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/UserResource.java index 9d82cd91c2..7978613514 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/UserResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/UserResource.java @@ -18,7 +18,13 @@ package org.apache.streampipes.rest.impl; import org.apache.streampipes.mail.MailSender; -import org.apache.streampipes.model.client.user.*; +import org.apache.streampipes.model.client.user.ChangePasswordRequest; +import org.apache.streampipes.model.client.user.Principal; +import org.apache.streampipes.model.client.user.PrincipalType; +import org.apache.streampipes.model.client.user.RawUserApiToken; +import org.apache.streampipes.model.client.user.Role; +import org.apache.streampipes.model.client.user.ServiceAccount; +import org.apache.streampipes.model.client.user.UserAccount; import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.rest.core.base.impl.AbstractAuthGuardedRestResource; import org.apache.streampipes.rest.security.AuthConstants; @@ -26,13 +32,23 @@ import org.apache.streampipes.user.management.encryption.SecretEncryptionManager; import org.apache.streampipes.user.management.service.TokenService; import org.apache.streampipes.user.management.util.PasswordUtil; + import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; + import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; @@ -183,7 +199,7 @@ public Response createNewApiToken(@PathParam("userId") String userId, @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateUserAccountDetails(@PathParam("principalId") String principalId, - UserAccount user) { + UserAccount user) { String authenticatedUserId = getAuthenticatedUsername(); if (user != null && (authenticatedUserId.equals(principalId) || isAdmin())) { UserAccount existingUser = (UserAccount) getPrincipalById(principalId); @@ -237,7 +253,7 @@ public Response updatePassword(@PathParam("principalId") String principalId, ChangePasswordRequest passwordRequest) { String authenticatedUserId = getAuthenticatedUsername(); UserAccount existingUser = (UserAccount) getPrincipalById(principalId); - if (principalId.equals(authenticatedUserId) || isAdmin()) { + if (principalId.equals(authenticatedUserId) || isAdmin()) { try { String existingPw = passwordRequest.getExistingPassword(); if (PasswordUtil.validatePassword(existingPw, existingUser.getPassword())) { @@ -262,7 +278,7 @@ public Response updatePassword(@PathParam("principalId") String principalId, @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response updateServiceAccountDetails(@PathParam("principalId") String principalId, - ServiceAccount user) { + ServiceAccount user) { String authenticatedUserId = getAuthenticatedUsername(); if (user != null && (authenticatedUserId.equals(principalId) || isAdmin())) { Principal existingUser = getPrincipalById(principalId); @@ -283,11 +299,11 @@ public Response updateServiceAccountDetails(@PathParam("principalId") String pri private boolean isAdmin() { return SecurityContextHolder - .getContext() - .getAuthentication() - .getAuthorities() - .stream() - .anyMatch(r -> r.getAuthority().equals(Role.ROLE_ADMIN.name())); + .getContext() + .getAuthentication() + .getAuthorities() + .stream() + .anyMatch(r -> r.getAuthority().equals(Role.ROLE_ADMIN.name())); } private void updateUser(UserAccount existingUser, @@ -299,14 +315,14 @@ private void updateUser(UserAccount existingUser, replacePermissions(user, existingUser); } user.setUserApiTokens(existingUser - .getUserApiTokens() + .getUserApiTokens() + .stream() + .filter(existingToken -> user.getUserApiTokens() .stream() - .filter(existingToken -> user.getUserApiTokens() - .stream() - .anyMatch(updatedToken -> existingToken - .getTokenId() - .equals(updatedToken.getTokenId()))) - .collect(Collectors.toList())); + .anyMatch(updatedToken -> existingToken + .getTokenId() + .equals(updatedToken.getTokenId()))) + .collect(Collectors.toList())); } private void encryptAndStore(UserAccount userAccount, From abcbe8a8fe0ba0a2c3ffae4c263bbcf64f6f6083 Mon Sep 17 00:00:00 2001 From: Dominik Riemer Date: Thu, 1 Dec 2022 22:27:08 +0100 Subject: [PATCH 05/10] Enable checkstyle for streampipes-messaging-jms (#820) --- .../jms/ActiveMQConnectionProvider.java | 20 +++++++++---------- .../messaging/jms/ActiveMQConsumer.java | 16 +++++++++------ .../messaging/jms/ActiveMQPublisher.java | 17 ++++++++-------- .../messaging/jms/ActiveMQUtils.java | 13 ++++++------ .../messaging/jms/SpJmsProtocol.java | 4 ++-- 5 files changed, 38 insertions(+), 32 deletions(-) diff --git a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQConnectionProvider.java b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQConnectionProvider.java index 835dd7df6a..4de17d1678 100644 --- a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQConnectionProvider.java +++ b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQConnectionProvider.java @@ -25,16 +25,16 @@ public abstract class ActiveMQConnectionProvider { - protected Connection startJmsConnection(String url) { - try { - ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); - connectionFactory.setAlwaysSyncSend(false); - Connection connect = connectionFactory.createConnection(); + protected Connection startJmsConnection(String url) { + try { + ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); + connectionFactory.setAlwaysSyncSend(false); + Connection connect = connectionFactory.createConnection(); - connect.start(); - return connect; - } catch (JMSException e) { - throw new AssertionError("Failed to establish the JMS-Connection!", e); - } + connect.start(); + return connect; + } catch (JMSException e) { + throw new AssertionError("Failed to establish the JMS-Connection!", e); } + } } diff --git a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQConsumer.java b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQConsumer.java index 4e85243295..f043f785b4 100644 --- a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQConsumer.java +++ b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQConsumer.java @@ -18,22 +18,24 @@ package org.apache.streampipes.messaging.jms; -import org.apache.activemq.command.ActiveMQBytesMessage; -import org.apache.activemq.util.ByteSequence; import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.messaging.EventConsumer; import org.apache.streampipes.messaging.InternalEventProcessor; import org.apache.streampipes.model.grounding.JmsTransportProtocol; +import org.apache.activemq.command.ActiveMQBytesMessage; +import org.apache.activemq.util.ByteSequence; + import javax.jms.BytesMessage; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.Session; + import java.io.Serializable; public class ActiveMQConsumer extends ActiveMQConnectionProvider implements - EventConsumer, - AutoCloseable, Serializable { + EventConsumer, + AutoCloseable, Serializable { private Session session; private MessageConsumer consumer; @@ -57,13 +59,15 @@ private void initListener() { @Override public void connect(JmsTransportProtocol protocolSettings, InternalEventProcessor - eventProcessor) throws SpRuntimeException { + eventProcessor) throws SpRuntimeException { String url = ActiveMQUtils.makeActiveMqUrl(protocolSettings); try { this.eventProcessor = eventProcessor; session = startJmsConnection(url).createSession(false, Session.AUTO_ACKNOWLEDGE); - consumer = session.createConsumer(session.createTopic(protocolSettings.getTopicDefinition().getActualTopicName())); + consumer = session.createConsumer(session.createTopic( + protocolSettings.getTopicDefinition().getActualTopicName()) + ); initListener(); this.connected = true; } catch (JMSException e) { diff --git a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQPublisher.java b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQPublisher.java index 40a11640d3..374f504b24 100644 --- a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQPublisher.java +++ b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQPublisher.java @@ -18,14 +18,15 @@ package org.apache.streampipes.messaging.jms; -import org.apache.activemq.ActiveMQConnectionFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.messaging.EventProducer; import org.apache.streampipes.model.grounding.JmsTransportProtocol; import org.apache.streampipes.model.grounding.SimpleTopicDefinition; +import org.apache.activemq.ActiveMQConnectionFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.ConnectionFactory; @@ -96,16 +97,16 @@ public void connect(JmsTransportProtocol protocolSettings) throws SpRuntimeExcep try { this.session = connection - .createSession(false, Session.AUTO_ACKNOWLEDGE); + .createSession(false, Session.AUTO_ACKNOWLEDGE); this.producer = session.createProducer(session.createTopic(protocolSettings - .getTopicDefinition() - .getActualTopicName())); + .getTopicDefinition() + .getActualTopicName())); this.producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); this.connection.start(); this.connected = true; } catch (JMSException e) { - throw new SpRuntimeException("could not connect to activemq broker. Broker: '" + - protocolSettings.getBrokerHostname() + "' Port: " + protocolSettings.getPort()); + throw new SpRuntimeException("could not connect to activemq broker. Broker: '" + + protocolSettings.getBrokerHostname() + "' Port: " + protocolSettings.getPort()); } } diff --git a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQUtils.java b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQUtils.java index 0a66af0786..5bda0e642f 100644 --- a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQUtils.java +++ b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/ActiveMQUtils.java @@ -1,4 +1,4 @@ -package org.apache.streampipes.messaging.jms;/* +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. @@ -15,15 +15,16 @@ * limitations under the License. * */ +package org.apache.streampipes.messaging.jms; import org.apache.streampipes.model.grounding.JmsTransportProtocol; public class ActiveMQUtils { - private static final String TCP_PROTOCOL = "tcp://"; - private static final String COLON = ":"; + private static final String TCP_PROTOCOL = "tcp://"; + private static final String COLON = ":"; - public static String makeActiveMqUrl(JmsTransportProtocol protocol) { - return TCP_PROTOCOL + protocol.getBrokerHostname() + COLON + protocol.getPort(); - } + public static String makeActiveMqUrl(JmsTransportProtocol protocol) { + return TCP_PROTOCOL + protocol.getBrokerHostname() + COLON + protocol.getPort(); + } } diff --git a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/SpJmsProtocol.java b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/SpJmsProtocol.java index 293f089966..dcdf03c6f4 100644 --- a/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/SpJmsProtocol.java +++ b/streampipes-messaging-jms/src/main/java/org/apache/streampipes/messaging/jms/SpJmsProtocol.java @@ -24,8 +24,8 @@ public class SpJmsProtocol implements SpProtocolDefinition { - private EventConsumer jmsConsumer; - private EventProducer jmsProducer; + private final EventConsumer jmsConsumer; + private final EventProducer jmsProducer; public SpJmsProtocol() { this.jmsConsumer = new ActiveMQConsumer(); From 855c5a6a101530e046f91c95734cad9c89fea46f Mon Sep 17 00:00:00 2001 From: Dominik Riemer Date: Thu, 1 Dec 2022 22:36:55 +0100 Subject: [PATCH 06/10] Enable checkstyle for streampipes-messaging-nats (#820) --- streampipes-messaging-nats/pom.xml | 22 +++++++++++ .../messaging/nats/AbstractNatsConnector.java | 30 ++++++++------- .../messaging/nats/NatsConsumer.java | 37 ++++++++++--------- .../messaging/nats/NatsPublisher.java | 28 +++++++------- .../streampipes/messaging/nats/NatsUtils.java | 29 ++++++++------- .../messaging/nats/SpNatsProtocol.java | 30 ++++++++------- .../messaging/nats/SpNatsProtocolFactory.java | 25 +++++++------ 7 files changed, 116 insertions(+), 85 deletions(-) diff --git a/streampipes-messaging-nats/pom.xml b/streampipes-messaging-nats/pom.xml index 5fdc5a690f..af42b43c2d 100644 --- a/streampipes-messaging-nats/pom.xml +++ b/streampipes-messaging-nats/pom.xml @@ -46,4 +46,26 @@ + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + validate + validate + + check + + + + + true + true + + + + + diff --git a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/AbstractNatsConnector.java b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/AbstractNatsConnector.java index f72f1e961d..5253cdf243 100644 --- a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/AbstractNatsConnector.java +++ b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/AbstractNatsConnector.java @@ -1,27 +1,29 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.nats; +import org.apache.streampipes.model.grounding.NatsTransportProtocol; +import org.apache.streampipes.model.nats.NatsConfig; + import io.nats.client.Connection; import io.nats.client.Nats; import io.nats.client.Options; -import org.apache.streampipes.model.grounding.NatsTransportProtocol; -import org.apache.streampipes.model.nats.NatsConfig; import java.io.IOException; import java.time.Duration; diff --git a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsConsumer.java b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsConsumer.java index b54fe0f672..ee02fab772 100644 --- a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsConsumer.java +++ b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsConsumer.java @@ -1,31 +1,33 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.nats; -import io.nats.client.Connection; -import io.nats.client.Dispatcher; -import io.nats.client.Subscription; import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.messaging.EventConsumer; import org.apache.streampipes.messaging.InternalEventProcessor; import org.apache.streampipes.model.grounding.NatsTransportProtocol; import org.apache.streampipes.model.nats.NatsConfig; +import io.nats.client.Connection; +import io.nats.client.Dispatcher; +import io.nats.client.Subscription; + import java.io.IOException; import java.util.concurrent.TimeoutException; @@ -69,8 +71,7 @@ public boolean isConnected() { private void createSubscription(InternalEventProcessor eventProcessor) { dispatcher = natsConnection.createDispatcher((message) -> {}); - this.subscription = dispatcher.subscribe(subject, (message) -> { - eventProcessor.onEvent(message.getData()); - }); + this.subscription = dispatcher.subscribe(subject, (message) -> + eventProcessor.onEvent(message.getData())); } } diff --git a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsPublisher.java b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsPublisher.java index f4b0c75f6d..06e7cc7325 100644 --- a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsPublisher.java +++ b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsPublisher.java @@ -1,27 +1,29 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.nats; -import io.nats.client.Connection; import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.messaging.EventProducer; import org.apache.streampipes.model.grounding.NatsTransportProtocol; +import io.nats.client.Connection; + import java.io.IOException; import java.util.concurrent.TimeoutException; diff --git a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsUtils.java b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsUtils.java index fb15db9351..7b49469621 100644 --- a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsUtils.java +++ b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/NatsUtils.java @@ -1,24 +1,25 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ - package org.apache.streampipes.messaging.nats; -import io.nats.client.Options; import org.apache.streampipes.model.nats.NatsConfig; + +import io.nats.client.Options; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/SpNatsProtocol.java b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/SpNatsProtocol.java index 847507ca04..bf3abb3de2 100644 --- a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/SpNatsProtocol.java +++ b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/SpNatsProtocol.java @@ -1,18 +1,19 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.nats; @@ -24,13 +25,14 @@ public class SpNatsProtocol implements SpProtocolDefinition { - private EventConsumer natsConsumer; - private EventProducer natsProducer; + private final EventConsumer natsConsumer; + private final EventProducer natsProducer; public SpNatsProtocol() { this.natsConsumer = new NatsConsumer(); this.natsProducer = new NatsPublisher(); } + @Override public EventConsumer getConsumer() { return this.natsConsumer; diff --git a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/SpNatsProtocolFactory.java b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/SpNatsProtocolFactory.java index 7d6812cfde..5d18e2b0b7 100644 --- a/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/SpNatsProtocolFactory.java +++ b/streampipes-messaging-nats/src/main/java/org/apache/streampipes/messaging/nats/SpNatsProtocolFactory.java @@ -1,18 +1,19 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.nats; From 877e2816aeb381f1a3f4955e328e51f46f8a7234 Mon Sep 17 00:00:00 2001 From: Dominik Riemer Date: Thu, 1 Dec 2022 22:37:14 +0100 Subject: [PATCH 07/10] Activate checkstyle in pom (#820) --- streampipes-messaging-jms/pom.xml | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/streampipes-messaging-jms/pom.xml b/streampipes-messaging-jms/pom.xml index 3edcc5c3db..2f6828361a 100644 --- a/streampipes-messaging-jms/pom.xml +++ b/streampipes-messaging-jms/pom.xml @@ -42,4 +42,26 @@ - \ No newline at end of file + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + validate + validate + + check + + + + + true + true + + + + + + From be6e9540b1caf2445fbd18d0716c5904cdf7bcb4 Mon Sep 17 00:00:00 2001 From: Dominik Riemer Date: Thu, 1 Dec 2022 22:37:41 +0100 Subject: [PATCH 08/10] Deactivate checkstyle line ending rule (#820) --- tools/maven/checkstyle.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tools/maven/checkstyle.xml b/tools/maven/checkstyle.xml index b81a4a9f9a..b817502d55 100644 --- a/tools/maven/checkstyle.xml +++ b/tools/maven/checkstyle.xml @@ -36,11 +36,6 @@ page at http://checkstyle.sourceforge.net/config.html --> - - - - - From 1fe4ac5f03f12a41e66f647528a4df1ceb74c4e0 Mon Sep 17 00:00:00 2001 From: Dominik Riemer Date: Thu, 1 Dec 2022 22:47:41 +0100 Subject: [PATCH 09/10] Enable checkstyle for streampipes-messaging-kafka (#820) --- streampipes-messaging-kafka/pom.xml | 24 +++++++++++++- .../messaging/kafka/SpKafkaConsumer.java | 27 +++++++++------- .../messaging/kafka/SpKafkaProducer.java | 31 +++++++++++++------ .../messaging/kafka/SpKafkaProtocol.java | 4 +-- .../kafka/config/ConsumerConfigFactory.java | 7 +++-- .../kafka/config/KafkaConfigAppender.java | 2 +- .../kafka/config/ProducerConfigFactory.java | 14 ++++----- .../KafkaSecuritySaslPlainConfig.java | 31 +++++++++++-------- .../security/KafkaSecuritySaslSSLConfig.java | 31 +++++++++++-------- ...fkaSecurityUnauthenticatedPlainConfig.java | 7 ++--- ...KafkaSecurityUnauthenticatedSSLConfig.java | 8 ++--- streampipes-messaging-nats/pom.xml | 1 - 12 files changed, 115 insertions(+), 72 deletions(-) diff --git a/streampipes-messaging-kafka/pom.xml b/streampipes-messaging-kafka/pom.xml index 29485016d6..b23939e3bd 100644 --- a/streampipes-messaging-kafka/pom.xml +++ b/streampipes-messaging-kafka/pom.xml @@ -46,4 +46,26 @@ kafka-clients - \ No newline at end of file + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + validate + validate + + check + + + + + true + true + + + + + diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaConsumer.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaConsumer.java index cf1657dc09..1411b9c03f 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaConsumer.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaConsumer.java @@ -18,10 +18,6 @@ package org.apache.streampipes.messaging.kafka; -import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; -import org.apache.kafka.clients.consumer.ConsumerRecords; -import org.apache.kafka.clients.consumer.KafkaConsumer; -import org.apache.kafka.common.TopicPartition; import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.messaging.EventConsumer; import org.apache.streampipes.messaging.InternalEventProcessor; @@ -29,17 +25,26 @@ import org.apache.streampipes.messaging.kafka.config.KafkaConfigAppender; import org.apache.streampipes.model.grounding.KafkaTransportProtocol; import org.apache.streampipes.model.grounding.WildcardTopicDefinition; + +import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.TopicPartition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.time.Duration; import java.time.temporal.ChronoUnit; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Properties; import java.util.regex.Pattern; public class SpKafkaConsumer implements EventConsumer, Runnable, - Serializable { + Serializable { private String topic; private InternalEventProcessor eventProcessor; @@ -97,9 +102,7 @@ public void onPartitionsAssigned(Collection partitions) { Duration duration = Duration.of(100, ChronoUnit.MILLIS); while (isRunning) { ConsumerRecords records = consumer.poll(duration); - records.forEach(record -> { - eventProcessor.onEvent(record.value()); - }); + records.forEach(record -> eventProcessor.onEvent(record.value())); } LOG.info("Closing Kafka Consumer."); consumer.close(); @@ -111,14 +114,14 @@ private String replaceWildcardWithPatternFormat(String topic) { } private Properties makeProperties(KafkaTransportProtocol protocol, - List appenders) { + List appenders) { return new ConsumerConfigFactory(protocol).buildProperties(appenders); } @Override public void connect(KafkaTransportProtocol protocol, InternalEventProcessor - eventProcessor) - throws SpRuntimeException { + eventProcessor) + throws SpRuntimeException { LOG.info("Kafka consumer: Connecting to " + protocol.getTopicDefinition().getActualTopicName()); if (protocol.getTopicDefinition() instanceof WildcardTopicDefinition) { this.patternTopic = true; diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaProducer.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaProducer.java index 7c46bb911c..afd3d44a77 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaProducer.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaProducer.java @@ -18,22 +18,31 @@ package org.apache.streampipes.messaging.kafka; -import org.apache.kafka.clients.admin.*; +import org.apache.streampipes.commons.constants.Envs; +import org.apache.streampipes.messaging.EventProducer; +import org.apache.streampipes.messaging.kafka.config.KafkaConfigAppender; +import org.apache.streampipes.messaging.kafka.config.ProducerConfigFactory; +import org.apache.streampipes.model.grounding.KafkaTransportProtocol; + +import org.apache.kafka.clients.admin.AdminClient; +import org.apache.kafka.clients.admin.CreateTopicsResult; +import org.apache.kafka.clients.admin.KafkaAdminClient; +import org.apache.kafka.clients.admin.ListTopicsResult; +import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.config.TopicConfig; -import org.apache.streampipes.commons.constants.Envs; -import org.apache.streampipes.messaging.kafka.config.KafkaConfigAppender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.apache.streampipes.messaging.EventProducer; -import org.apache.streampipes.messaging.kafka.config.ProducerConfigFactory; -import org.apache.streampipes.model.grounding.KafkaTransportProtocol; import java.io.Serializable; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; import java.util.concurrent.ExecutionException; public class SpKafkaProducer implements EventProducer, Serializable { @@ -50,7 +59,8 @@ public class SpKafkaProducer implements EventProducer, S private static final Logger LOG = LoggerFactory.getLogger(SpKafkaProducer.class); - public SpKafkaProducer() { } + public SpKafkaProducer() { + } // TODO backwards compatibility, remove later public SpKafkaProducer(String url, @@ -58,7 +68,7 @@ public SpKafkaProducer(String url, List appenders) { String[] urlParts = url.split(COLON); KafkaTransportProtocol protocol = new KafkaTransportProtocol(urlParts[0], - Integer.parseInt(urlParts[1]), topic); + Integer.parseInt(urlParts[1]), topic); this.brokerUrl = url; this.topic = topic; this.producer = new KafkaProducer<>(makeProperties(protocol, appenders)); @@ -115,7 +125,8 @@ private void createKafaTopic(KafkaTransportProtocol settings) throws ExecutionEx if (!topicExists(topics)) { Map topicConfig = new HashMap<>(); - String retentionTime = Envs.SP_KAFKA_RETENTION_MS.exists() ? Envs.SP_KAFKA_RETENTION_MS.getValue() : SP_KAFKA_RETENTION_MS_DEFAULT; + String retentionTime = Envs.SP_KAFKA_RETENTION_MS.exists() + ? Envs.SP_KAFKA_RETENTION_MS.getValue() : SP_KAFKA_RETENTION_MS_DEFAULT; topicConfig.put(TopicConfig.RETENTION_MS_CONFIG, retentionTime); final NewTopic newTopic = new NewTopic(topic, 1, (short) 1); diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaProtocol.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaProtocol.java index 305a0c12ab..0a921092d3 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaProtocol.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/SpKafkaProtocol.java @@ -25,8 +25,8 @@ public class SpKafkaProtocol implements SpProtocolDefinition { - private EventConsumer kafkaConsumer; - private EventProducer kafkaProducer; + private final EventConsumer kafkaConsumer; + private final EventProducer kafkaProducer; public SpKafkaProtocol() { this.kafkaConsumer = new SpKafkaConsumer(); diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/ConsumerConfigFactory.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/ConsumerConfigFactory.java index 2aa488aed5..461d96e04f 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/ConsumerConfigFactory.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/ConsumerConfigFactory.java @@ -17,9 +17,10 @@ */ package org.apache.streampipes.messaging.kafka.config; +import org.apache.streampipes.model.grounding.KafkaTransportProtocol; + import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.ByteArrayDeserializer; -import org.apache.streampipes.model.grounding.KafkaTransportProtocol; import java.util.Properties; import java.util.UUID; @@ -44,10 +45,10 @@ public Properties makeDefaultProperties() { props.put(ConsumerConfig.GROUP_ID_CONFIG, getConfigOrDefault(protocol::getGroupId, UUID.randomUUID().toString())); props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, ENABLE_AUTO_COMMIT_CONFIG_DEFAULT); props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, - AUTO_COMMIT_INTERVAL_MS_CONFIG_DEFAULT); + AUTO_COMMIT_INTERVAL_MS_CONFIG_DEFAULT); props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, SESSION_TIMEOUT_MS_CONFIG_DEFAULT); props.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, - getConfigOrDefault(protocol::getMessageMaxBytes, FETCH_MAX_BYTES_CONFIG_DEFAULT)); + getConfigOrDefault(protocol::getMessageMaxBytes, FETCH_MAX_BYTES_CONFIG_DEFAULT)); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, KEY_DESERIALIZER_CLASS_CONFIG_DEFAULT); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, VALUE_DESERIALIZER_CLASS_CONFIG_DEFAULT); diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/KafkaConfigAppender.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/KafkaConfigAppender.java index a8f945a756..1e53ebd225 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/KafkaConfigAppender.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/KafkaConfigAppender.java @@ -22,5 +22,5 @@ public interface KafkaConfigAppender { - void appendConfig(Properties props); + void appendConfig(Properties props); } diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/ProducerConfigFactory.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/ProducerConfigFactory.java index 23426d1248..197cdffcff 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/ProducerConfigFactory.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/config/ProducerConfigFactory.java @@ -17,10 +17,11 @@ */ package org.apache.streampipes.messaging.kafka.config; +import org.apache.streampipes.model.grounding.KafkaTransportProtocol; + import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.ByteArraySerializer; import org.apache.kafka.common.serialization.StringSerializer; -import org.apache.streampipes.model.grounding.KafkaTransportProtocol; import java.util.Properties; @@ -37,11 +38,8 @@ public class ProducerConfigFactory extends AbstractConfigFactory { private static final String VALUE_SERIALIZER_DEFAULT = ByteArraySerializer.class.getName(); - public ProducerConfigFactory(KafkaTransportProtocol protocol) { super(protocol); - - } @Override @@ -49,14 +47,14 @@ public Properties makeDefaultProperties() { Properties props = new Properties(); props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, getBrokerUrl()); props.put(ProducerConfig.ACKS_CONFIG, getConfigOrDefault(protocol::getAcks, - ACKS_CONFIG_DEFAULT)); + ACKS_CONFIG_DEFAULT)); props.put(ProducerConfig.RETRIES_CONFIG, RETRIES_CONFIG_DEFAULT); props.put(ProducerConfig.BATCH_SIZE_CONFIG, - getConfigOrDefault(protocol::getBatchSize, BATCH_SIZE_CONFIG_DEFAULT)); + getConfigOrDefault(protocol::getBatchSize, BATCH_SIZE_CONFIG_DEFAULT)); props.put(ProducerConfig.LINGER_MS_CONFIG, - getConfigOrDefault(protocol::getLingerMs, LINGER_MS_DEFAULT)); + getConfigOrDefault(protocol::getLingerMs, LINGER_MS_DEFAULT)); props.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, getConfigOrDefault(protocol::getMaxRequestSize, - MAX_REQUEST_SIZE_CONFIG_DEFAULT)); + MAX_REQUEST_SIZE_CONFIG_DEFAULT)); props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, BUFFER_MEMORY_CONFIG_DEFAULT); props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, KEY_SERIALIZER_DEFAULT); diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecuritySaslPlainConfig.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecuritySaslPlainConfig.java index eb40e57872..a7e5fa94fc 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecuritySaslPlainConfig.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecuritySaslPlainConfig.java @@ -26,21 +26,26 @@ public class KafkaSecuritySaslPlainConfig extends KafkaSecurityConfig { - private final String username; - private final String password; + private final String username; + private final String password; - public KafkaSecuritySaslPlainConfig(String username, String password) { - this.username = username; - this.password = password; - } + public KafkaSecuritySaslPlainConfig(String username, String password) { + this.username = username; + this.password = password; + } - @Override - public void appendConfig(Properties props) { + @Override + public void appendConfig(Properties props) { - props.put(SaslConfigs.SASL_MECHANISM, "PLAIN"); - props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SASL_PLAINTEXT.toString()); + props.put(SaslConfigs.SASL_MECHANISM, "PLAIN"); + props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SASL_PLAINTEXT.toString()); - String SASL_JAAS_CONFIG = "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"" + username + "\" password=\"" + password + "\";"; - props.put(SaslConfigs.SASL_JAAS_CONFIG, SASL_JAAS_CONFIG); - } + String saslJaasConfig = "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"" + + username + + "\" password=\"" + + password + + "\";"; + + props.put(SaslConfigs.SASL_JAAS_CONFIG, saslJaasConfig); + } } diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecuritySaslSSLConfig.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecuritySaslSSLConfig.java index 9b77841b1f..2c5ef691e3 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecuritySaslSSLConfig.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecuritySaslSSLConfig.java @@ -26,21 +26,26 @@ public class KafkaSecuritySaslSSLConfig extends KafkaSecurityConfig { - private final String username; - private final String password; + private final String username; + private final String password; - public KafkaSecuritySaslSSLConfig(String username, String password) { - this.username = username; - this.password = password; - } + public KafkaSecuritySaslSSLConfig(String username, String password) { + this.username = username; + this.password = password; + } - @Override - public void appendConfig(Properties props) { + @Override + public void appendConfig(Properties props) { - props.put(SaslConfigs.SASL_MECHANISM, "PLAIN"); - props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SASL_SSL.toString()); + props.put(SaslConfigs.SASL_MECHANISM, "PLAIN"); + props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SASL_SSL.toString()); - String SASL_JAAS_CONFIG = "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"" + username + "\" password=\"" + password + "\";"; - props.put(SaslConfigs.SASL_JAAS_CONFIG, SASL_JAAS_CONFIG); - } + String saslJaasConfig = "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"" + + username + + "\" password=\"" + + password + + "\";"; + + props.put(SaslConfigs.SASL_JAAS_CONFIG, saslJaasConfig); + } } diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecurityUnauthenticatedPlainConfig.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecurityUnauthenticatedPlainConfig.java index 52795e7fe8..235a6eda39 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecurityUnauthenticatedPlainConfig.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecurityUnauthenticatedPlainConfig.java @@ -22,9 +22,8 @@ public class KafkaSecurityUnauthenticatedPlainConfig extends KafkaSecurityConfig { + @Override + public void appendConfig(Properties props) { - @Override - public void appendConfig(Properties props) { - - } + } } diff --git a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecurityUnauthenticatedSSLConfig.java b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecurityUnauthenticatedSSLConfig.java index 84e20296a3..8fdd02fd12 100644 --- a/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecurityUnauthenticatedSSLConfig.java +++ b/streampipes-messaging-kafka/src/main/java/org/apache/streampipes/messaging/kafka/security/KafkaSecurityUnauthenticatedSSLConfig.java @@ -25,8 +25,8 @@ public class KafkaSecurityUnauthenticatedSSLConfig extends KafkaSecurityConfig { - @Override - public void appendConfig(Properties props) { - props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SSL.toString()); - } + @Override + public void appendConfig(Properties props) { + props.put(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, SecurityProtocol.SSL.toString()); + } } diff --git a/streampipes-messaging-nats/pom.xml b/streampipes-messaging-nats/pom.xml index af42b43c2d..cfb27a1bcd 100644 --- a/streampipes-messaging-nats/pom.xml +++ b/streampipes-messaging-nats/pom.xml @@ -67,5 +67,4 @@ - From c7bfc4b1ade2250f1297020e1dce256f8cbf20d2 Mon Sep 17 00:00:00 2001 From: Dominik Riemer Date: Thu, 1 Dec 2022 22:50:50 +0100 Subject: [PATCH 10/10] Enable checkstyle for streampipes-messaging-mqtt (#820) --- streampipes-messaging-mqtt/pom.xml | 23 ++++++++++++- .../messaging/mqtt/AbstractMqttConnector.java | 26 +++++++------- .../messaging/mqtt/MqttConsumer.java | 34 +++++++++++-------- .../messaging/mqtt/MqttPublisher.java | 26 +++++++------- .../messaging/mqtt/SpMqttProtocol.java | 29 ++++++++-------- .../messaging/mqtt/SpMqttProtocolFactory.java | 27 ++++++++------- 6 files changed, 98 insertions(+), 67 deletions(-) diff --git a/streampipes-messaging-mqtt/pom.xml b/streampipes-messaging-mqtt/pom.xml index d157488efc..540d57caea 100644 --- a/streampipes-messaging-mqtt/pom.xml +++ b/streampipes-messaging-mqtt/pom.xml @@ -45,4 +45,25 @@ - \ No newline at end of file + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + + validate + validate + + check + + + + + true + true + + + + + diff --git a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/AbstractMqttConnector.java b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/AbstractMqttConnector.java index 6ba637a9b4..c5cad2b6d8 100644 --- a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/AbstractMqttConnector.java +++ b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/AbstractMqttConnector.java @@ -1,22 +1,24 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.mqtt; import org.apache.streampipes.model.grounding.MqttTransportProtocol; + import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.MQTT; diff --git a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/MqttConsumer.java b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/MqttConsumer.java index 51659912d5..d19d4b575b 100644 --- a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/MqttConsumer.java +++ b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/MqttConsumer.java @@ -1,18 +1,19 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.mqtt; @@ -20,6 +21,7 @@ import org.apache.streampipes.messaging.EventConsumer; import org.apache.streampipes.messaging.InternalEventProcessor; import org.apache.streampipes.model.grounding.MqttTransportProtocol; + import org.fusesource.mqtt.client.Message; import org.fusesource.mqtt.client.QoS; import org.fusesource.mqtt.client.Topic; @@ -27,11 +29,13 @@ import java.io.Serializable; public class MqttConsumer extends AbstractMqttConnector implements - EventConsumer, - AutoCloseable, Serializable { + EventConsumer, + AutoCloseable, Serializable { @Override - public void connect(MqttTransportProtocol protocolSettings, InternalEventProcessor eventProcessor) throws SpRuntimeException { + public void connect(MqttTransportProtocol protocolSettings, InternalEventProcessor eventProcessor) + throws SpRuntimeException { + try { this.createBrokerConnection(protocolSettings); Topic[] topics = {new Topic(protocolSettings.getTopicDefinition().getActualTopicName(), QoS.AT_LEAST_ONCE)}; diff --git a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/MqttPublisher.java b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/MqttPublisher.java index 91dbd38213..cf4f8356ec 100644 --- a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/MqttPublisher.java +++ b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/MqttPublisher.java @@ -1,24 +1,26 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.mqtt; import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.messaging.EventProducer; import org.apache.streampipes.model.grounding.MqttTransportProtocol; + import org.fusesource.mqtt.client.QoS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/SpMqttProtocol.java b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/SpMqttProtocol.java index 9c259bf5f4..ccda09075f 100644 --- a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/SpMqttProtocol.java +++ b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/SpMqttProtocol.java @@ -1,18 +1,19 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.mqtt; @@ -23,8 +24,8 @@ public class SpMqttProtocol implements SpProtocolDefinition { - private EventConsumer mqttConsumer; - private EventProducer mqttProducer; + private final EventConsumer mqttConsumer; + private final EventProducer mqttProducer; public SpMqttProtocol() { this.mqttConsumer = new MqttConsumer(); diff --git a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/SpMqttProtocolFactory.java b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/SpMqttProtocolFactory.java index dea95abfde..7fad10f689 100644 --- a/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/SpMqttProtocolFactory.java +++ b/streampipes-messaging-mqtt/src/main/java/org/apache/streampipes/messaging/mqtt/SpMqttProtocolFactory.java @@ -1,18 +1,19 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package org.apache.streampipes.messaging.mqtt; @@ -22,7 +23,7 @@ import org.apache.streampipes.model.grounding.TransportProtocol; public class SpMqttProtocolFactory extends SpProtocolDefinitionFactory { - + @Override public TransportProtocol getTransportProtocol() { return new MqttTransportProtocol();