From 5e247c6e6b6cc6886fd2ff33278b52a724f44ca9 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Sat, 18 Dec 2021 12:30:56 +0530 Subject: [PATCH 01/13] Add identity server service provider app integration --- .../application/mgt/common/Base64File.java | 23 + .../mgt/common/FileDataHolder.java | 33 ++ .../mgt/common/IdentityServer.java | 77 +++ .../mgt/common/IdentityServerList.java | 15 + .../application/mgt/common/SPApplication.java | 81 +++ .../mgt/common/SPApplicationListResponse.java | 42 ++ .../common/services/ApplicationManager.java | 106 +++- .../common/services/SPApplicationManager.java | 33 ++ .../common/wrapper/ApplicationWrapper.java | 3 +- .../wrapper/CustomAppReleaseWrapper.java | 38 ++ .../mgt/common/wrapper/CustomAppWrapper.java | 3 +- .../common/wrapper/EntAppReleaseWrapper.java | 38 ++ .../wrapper/PublicAppReleaseWrapper.java | 26 + .../mgt/common/wrapper/PublicAppWrapper.java | 4 +- .../common/wrapper/WebAppReleaseWrapper.java | 26 + .../mgt/common/wrapper/WebAppWrapper.java | 3 +- .../mgt/core/config/Extension.java | 1 + .../mgt/core/dao/SPApplicationDAO.java | 53 ++ .../ApplicationManagementDAOFactory.java | 24 + .../GenericApplicationDAOImpl.java | 12 +- .../application/OracleApplicationDAOImpl.java | 6 +- .../SQLServerApplicationDAOImpl.java | 6 +- .../GenericSPApplicationDAOImpl.java | 290 ++++++++++ .../OracleSPApplicationDAOImpl.java | 289 ++++++++++ .../PostgreSQLSPApplicationDAOImpl.java | 289 ++++++++++ .../SQLServerSPApplicationDAOImpl.java | 289 ++++++++++ .../mgt/core/impl/ApplicationManagerImpl.java | 527 +++++++++++------- .../core/impl/SPApplicationManagerImpl.java | 347 ++++++++++++ ...ApplicationManagementServiceComponent.java | 5 + .../mgt/core/internal/DataHolder.java | 11 + .../application/mgt/core/util/APIUtil.java | 32 +- .../core/util/ApplicationManagementUtil.java | 118 +++- .../application/mgt/core/util/Constants.java | 11 + .../application/mgt/core/util/DAOUtil.java | 104 +++- .../util/SPApplicationManagementUtil.java | 40 ++ .../management/ApplicationManagementTest.java | 4 +- .../ApplicationManagementPublisherAPI.java | 222 ++++++++ .../api/services/SPApplicationService.java | 280 ++++++++++ ...ApplicationManagementPublisherAPIImpl.java | 159 +++++- .../impl/SPApplicationServiceImpl.java | 211 +++++++ .../util/SPAppRequestHandlerUtil.java | 137 +++++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 + .../device/mgt/core/common/Constants.java | 10 + .../device/mgt/core/common/util/FileUtil.java | 24 + .../device/mgt/core/common/util/HttpUtil.java | 141 +++++ .../main/resources/conf/application-mgt.xml | 3 + .../repository/conf/application-mgt.xml.j2 | 7 + .../dbscripts/cdm/application-mgt/mysql.sql | 37 +- .../src/main/resources/conf/mdm-ui-config.xml | 4 + .../repository/conf/mdm-ui-config.xml.j2 | 4 + 50 files changed, 3947 insertions(+), 303 deletions(-) create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/SPApplicationManagementUtil.java create mode 100644 components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java create mode 100644 components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java create mode 100644 components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java new file mode 100644 index 00000000000..51e9add3722 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java @@ -0,0 +1,23 @@ +package io.entgra.application.mgt.common; + +public class Base64File { + + private String name; + private String base64String; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getBase64String() { + return base64String; + } + + public void setBase64String(String base64String) { + this.base64String = base64String; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java new file mode 100644 index 00000000000..4bb36c6c640 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java @@ -0,0 +1,33 @@ +package io.entgra.application.mgt.common; + +import java.io.InputStream; + +public class FileDataHolder { + + private String name; + private InputStream file; + + public FileDataHolder(String name, InputStream file) { + this.name = name; + this.file = file; + } + public FileDataHolder() { + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public InputStream getFile() { + return file; + } + + public void setFile(InputStream file) { + this.file = file; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java new file mode 100644 index 00000000000..4bc0ddee020 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java @@ -0,0 +1,77 @@ +package io.entgra.application.mgt.common; + + +public class IdentityServer { + private int id; + private String name; + private String description; + private String url; + private String spAppsUri; + private String spAppsApi; + private String userName; + private String password; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getSpAppsUri() { + return spAppsUri; + } + + public void setSpAppsURI(String spAppsUri) { + this.spAppsUri = spAppsUri; + } + + public String getSpAppsApi() { + return spAppsApi; + } + + public void setSpAppsApi(String spAppsApi) { + this.spAppsApi = spAppsApi; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java new file mode 100644 index 00000000000..5f1deaacf18 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java @@ -0,0 +1,15 @@ +package io.entgra.application.mgt.common; + +import java.util.List; + +public class IdentityServerList { + private List identityServers; + + public List getIdentityServers() { + return identityServers; + } + + public void setIdentityServers(List identityServers) { + this.identityServers = identityServers; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java new file mode 100644 index 00000000000..118576cfbf1 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java @@ -0,0 +1,81 @@ +package io.entgra.application.mgt.common; + + +import io.entgra.application.mgt.common.response.Application; + +import java.util.List; + +public class SPApplication { + private String id; + private String name; + private String description; + private String image; + private String accessUrl; + private String access; + private String self; + private List existingApplications; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getImage() { + return image; + } + + public void setImage(String image) { + this.image = image; + } + + public String getAccessUrl() { + return accessUrl; + } + + public void setAccessUrl(String accessUrl) { + this.accessUrl = accessUrl; + } + + public String getAccess() { + return access; + } + + public void setAccess(String access) { + this.access = access; + } + + public String getSelf() { + return self; + } + + public void setSelf(String self) { + this.self = self; + } + + public List getExistingApplications() { + return existingApplications; + } + + public void setExistingApplications(List existingApplications) { + this.existingApplications = existingApplications; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java new file mode 100644 index 00000000000..e638364bbde --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java @@ -0,0 +1,42 @@ +package io.entgra.application.mgt.common; + +import java.util.List; + +public class SPApplicationListResponse { + private int totalResults; + private int startIndex; + private int count; + private List applications; + + public int getTotalResults() { + return totalResults; + } + + public void setTotalResults(int totalResults) { + this.totalResults = totalResults; + } + + public int getStartIndex() { + return startIndex; + } + + public void setStartIndex(int startIndex) { + this.startIndex = startIndex; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public List getApplications() { + return applications; + } + + public void setApplications(List applications) { + this.applications = applications; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java index 5e77584b9a2..75708c11058 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java @@ -16,6 +16,10 @@ */ package io.entgra.application.mgt.common.services; +import io.entgra.application.mgt.common.ApplicationType; +import io.entgra.application.mgt.common.Base64File; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.exception.ResourceManagementException; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import io.entgra.application.mgt.common.ApplicationArtifact; import io.entgra.application.mgt.common.LifecycleChanger; @@ -46,6 +50,10 @@ import java.util.List; */ public interface ApplicationManager { + + ApplicationReleaseDTO uploadEntAppReleaseArtifacts(EntAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, + String deviceType) throws ApplicationManagementException; + /*** * The method is responsible to add new application into entgra App Manager. * @@ -54,18 +62,42 @@ public interface ApplicationManager { * @return {@link Application} * @throws ApplicationManagementException Catch all other throwing exceptions and throw {@link ApplicationManagementException} */ - Application createEntApp(ApplicationWrapper applicationWrapper, ApplicationArtifact applicationArtifact) + ApplicationDTO uploadEntAppReleaseArtifacts(ApplicationWrapper applicationWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - Application createWebClip(WebAppWrapper webAppWrapper, ApplicationArtifact applicationArtifact) + ApplicationReleaseDTO uploadWebAppReleaseArtifacts(WebAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact) + throws ApplicationManagementException, ResourceManagementException; + + ApplicationDTO uploadWebAppReleaseArtifacts(WebAppWrapper webAppWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - Application createPublicApp(PublicAppWrapper publicAppWrapper, ApplicationArtifact applicationArtifact) + ApplicationReleaseDTO uploadPubAppReleaseArtifacts(PublicAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, + String deviceType) throws ResourceManagementException; + + ApplicationDTO uploadPublicAppReleaseArtifacts(PublicAppWrapper publicAppWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - Application createCustomApp(CustomAppWrapper customAppWrapper, ApplicationArtifact applicationArtifact) + ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(CustomAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, + String deviceType) throws ResourceManagementException, ApplicationManagementException; + + ApplicationDTO uploadCustomAppReleaseArtifactsAndConstructAppDTO(CustomAppWrapper customAppWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + /*** + * This method is responsible to add application data into APPM database. However, before call this method it is + * required to do the validation of request and check the existence of application releaseDTO. + * + * @param applicationDTO Application DTO object. + * @return {@link Application} + * @throws ApplicationManagementException which throws if error occurs while during application management. + */ + Application executeApplicationPersistenceTransaction(ApplicationDTO applicationDTO) throws + ApplicationManagementException; + + + Application persistApplication(ApplicationDTO applicationDTO) throws ApplicationManagementException; + + /** * Check the existence of an application for given application name and the device type. * @@ -77,6 +109,7 @@ public interface ApplicationManager { */ boolean isExistingAppName(String appName, String deviceTypeName) throws ApplicationManagementException; + /** * Updates an already existing application. * @@ -121,6 +154,12 @@ public interface ApplicationManager { */ ApplicationList getApplications(Filter filter) throws ApplicationManagementException; + boolean isHideableApp(List applicationReleaseDTOs) + throws ApplicationManagementException; + + boolean isDeletableApp(List applicationReleaseDTOs) + throws ApplicationManagementException; + /** * To get list of applications that application releases has given package names. * @@ -131,6 +170,21 @@ public interface ApplicationManager { */ List getApplications(List packageNames) throws ApplicationManagementException; + + /** + * To create an application release for an ApplicationDTO. + * + * @param applicationDTO ApplicationDTO of the release + * @param applicationReleaseDTO ApplicatonRelease that need to be be created. + * @param type {@link ApplicationType} + * @return the unique id of the application release, if the application release succeeded else -1 + */ + ApplicationRelease createRelease(ApplicationDTO applicationDTO, ApplicationReleaseDTO applicationReleaseDTO, + ApplicationType type) + throws ApplicationManagementException; + + ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException; + /** * To get the Application for given Id. * @@ -202,16 +256,6 @@ public interface ApplicationManager { void updateApplicationArtifact(String deviceType, String uuid, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - /** - * To create an application release for an ApplicationDTO. - * - * @param applicationId ID of the ApplicationDTO - * @param entAppReleaseWrapper ApplicatonRelease that need to be be created. - * @return the unique id of the application release, if the application release succeeded else -1 - */ - ApplicationRelease createEntAppRelease(int applicationId, EntAppReleaseWrapper entAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - /*** * * @param releaseUuid UUID of the application release. @@ -220,30 +264,34 @@ public interface ApplicationManager { * @return If the application release is updated correctly True returns, otherwise retuen False */ ApplicationRelease updateEntAppRelease(String releaseUuid, EntAppReleaseWrapper entAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + ApplicationArtifact applicationArtifact) throws ApplicationManagementException; ApplicationRelease updatePubAppRelease(String releaseUuid, PublicAppReleaseWrapper publicAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + ApplicationArtifact applicationArtifact) throws ApplicationManagementException; ApplicationRelease updateWebAppRelease(String releaseUuid, WebAppReleaseWrapper webAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + ApplicationArtifact applicationArtifact) throws ApplicationManagementException; ApplicationRelease updateCustomAppRelease(String releaseUuid, CustomAppReleaseWrapper customAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + ApplicationArtifact applicationArtifact) throws ApplicationManagementException; /*** * To validate the application creating request * */ - void validateAppCreatingRequest(T param) throws ApplicationManagementException; + void validateAppCreatingRequest(T param, boolean isReleaseRequired) throws ApplicationManagementException; /*** * * @throws ApplicationManagementException throws if payload does not satisfy requirements. */ - void validateReleaseCreatingRequest(T param, String deviceType) throws ApplicationManagementException; + void validateReleaseCreatingRequest(T releases, String deviceType) throws ApplicationManagementException; - /*** + void validateImageArtifacts(Base64File iconFile, List screenshots) throws RequestValidatingException; + + void validateBase64File(Base64File file) throws RequestValidatingException; + + /*** * * @param iconFile Icon file for the application. * @param bannerFile Banner file for the application. @@ -253,6 +301,8 @@ public interface ApplicationManager { void validateImageArtifacts(Attachment iconFile, Attachment bannerFile, List attachmentList) throws RequestValidatingException; + void validateBinaryArtifact(Base64File binaryFile) throws RequestValidatingException; + void validateBinaryArtifact(Attachment binaryFile) throws RequestValidatingException; void addApplicationCategories(List categories) throws ApplicationManagementException; @@ -294,13 +344,13 @@ public interface ApplicationManager { void updateSubsStatus (int deviceId, int operationId, String status) throws ApplicationManagementException; - /** - * Get plist content to download and install the application. - * - * @param uuid Release UUID of the application. - * @return plist string - * @throws ApplicationManagementException Application management exception - */ + /** + * Get plist content to download and install the application. + * + * @param uuid Release UUID of the application. + * @return plist string + * @throws ApplicationManagementException Application management exception + */ String getPlistArtifact(String uuid) throws ApplicationManagementException; List getReleaseByPackageNames(List packageIds) throws ApplicationManagementException; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java new file mode 100644 index 00000000000..ad96347ed66 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java @@ -0,0 +1,33 @@ +package io.entgra.application.mgt.common.services; + +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.IdentityServerList; +import io.entgra.application.mgt.common.SPApplication; +import io.entgra.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.application.mgt.common.exception.RequestValidatingException; +import io.entgra.application.mgt.common.response.Application; + +import java.util.List; + +public interface SPApplicationManager { + + + void addExistingApps(int identityServerId, List applications) throws ApplicationManagementException; + + void detachSPApplications(int identityServerId, String spUID, List appIds) throws ApplicationManagementException; + + void attachSPApplications(int identityServerId, String spUID, List appIds) throws ApplicationManagementException; + + IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException; + + IdentityServerList getIdentityServers() throws ApplicationManagementException; + + List getSPApplications(int identityServerId, String spUID) throws ApplicationManagementException; + + Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException, RequestValidatingException; + + void validateAttachAppsRequest(int identityServerId, List appIds) throws ApplicationManagementException; + + void validateDetachAppsRequest(int identityServerId, String spId, List appIds) throws ApplicationManagementException; + +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/ApplicationWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/ApplicationWrapper.java index f109b7b78dc..82e52cdebea 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/ApplicationWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/ApplicationWrapper.java @@ -20,6 +20,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.List; @ApiModel(value = "ApplicationWrapper", description = "ApplicationWrapper represents the an ApplicationDTO in ApplicationDTO Store") @@ -80,7 +81,7 @@ public class ApplicationWrapper { value = "List of application releases", required = true) @NotNull - private List entAppReleaseWrappers; + private List entAppReleaseWrappers = new ArrayList<>(); public String getName() { diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java index eb30c7e9120..adac0bf2f33 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java @@ -16,10 +16,12 @@ */ package io.entgra.application.mgt.common.wrapper; +import io.entgra.application.mgt.common.Base64File; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; +import java.util.List; @ApiModel(value = "CustomAppReleaseWrapper", description = "This class holds the details when releasing an Custom app release to application store") public class CustomAppReleaseWrapper { @@ -65,6 +67,18 @@ public class CustomAppReleaseWrapper { @NotNull private String packageName; + @ApiModelProperty(name = "screenshots", + value = "screenshots of the application") + private List screenshots; + + @ApiModelProperty(name = "icon", + value = "icon of the application") + private Base64File icon; + + @ApiModelProperty(name = "binaryFile", + value = "binary file of the application") + private Base64File binaryFile; + public String getReleaseType() { return releaseType; } @@ -122,4 +136,28 @@ public class CustomAppReleaseWrapper { public void setPackageName(String packageName) { this.packageName = packageName; } + + public List getScreenshots() { + return screenshots; + } + + public void setScreenshots(List screenshots) { + this.screenshots = screenshots; + } + + public Base64File getIcon() { + return icon; + } + + public void setIcon(Base64File icon) { + this.icon = icon; + } + + public Base64File getBinaryFile() { + return binaryFile; + } + + public void setBinaryFile(Base64File binaryFile) { + this.binaryFile = binaryFile; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppWrapper.java index 4c0a392d897..b874a836614 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppWrapper.java @@ -20,6 +20,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.List; @ApiModel(value = "CustomAppWrapper", description = "CustomAppWrapper represents an Application used to install in IoT devices") @@ -78,7 +79,7 @@ public class CustomAppWrapper { value = "List of custom app releases", required = true) @NotNull - private List customAppReleaseWrappers; + private List customAppReleaseWrappers = new ArrayList<>(); public String getName() { return name; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java index 4d39506e9b6..2aa952ac400 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java @@ -16,10 +16,12 @@ */ package io.entgra.application.mgt.common.wrapper; +import io.entgra.application.mgt.common.Base64File; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; +import java.util.List; @ApiModel(value = "ApplicationReleaseDTO", description = "This class holds the details when releasing an ApplicationDTO to application store") public class EntAppReleaseWrapper { @@ -68,6 +70,18 @@ public class EntAppReleaseWrapper { value = "PackageName of the application installer specifically for windows") private String packageName; + @ApiModelProperty(name = "screenshots", + value = "screenshots of the application") + private List screenshots; + + @ApiModelProperty(name = "icon", + value = "icon of the application") + private Base64File icon; + + @ApiModelProperty(name = "binaryFile", + value = "binary file of the application") + private Base64File binaryFile; + public String getReleaseType() { return releaseType; } @@ -123,4 +137,28 @@ public class EntAppReleaseWrapper { public void setPackageName(String packageName) { this.packageName = packageName; } + + public List getScreenshots() { + return screenshots; + } + + public void setScreenshots(List screenshots) { + this.screenshots = screenshots; + } + + public Base64File getIcon() { + return icon; + } + + public void setIcon(Base64File icon) { + this.icon = icon; + } + + public Base64File getBinaryFile() { + return binaryFile; + } + + public void setBinaryFile(Base64File binaryFile) { + this.binaryFile = binaryFile; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java index 4b60e529410..c9c5499bc27 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java @@ -16,10 +16,12 @@ */ package io.entgra.application.mgt.common.wrapper; +import io.entgra.application.mgt.common.Base64File; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; +import java.util.List; @ApiModel(value = "Public App Release Wrapper", description = "This class holds the details when releasing an Public App" + " Release to application store") @@ -72,6 +74,14 @@ public class PublicAppReleaseWrapper { @NotNull private String supportedOsVersions; + @ApiModelProperty(name = "screenshots", + value = "screenshots of the application") + private List screenshots; + + @ApiModelProperty(name = "icon", + value = "icon of the application") + private Base64File icon; + public String getReleaseType() { return releaseType; } @@ -123,4 +133,20 @@ public class PublicAppReleaseWrapper { public String getSupportedOsVersions() { return supportedOsVersions; } public void setSupportedOsVersions(String supportedOsVersions) { this.supportedOsVersions = supportedOsVersions; } + + public Base64File getIcon() { + return icon; + } + + public void setIcon(Base64File icon) { + this.icon = icon; + } + + public List getScreenshots() { + return screenshots; + } + + public void setScreenshots(List screenshots) { + this.screenshots = screenshots; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppWrapper.java index 5f653257cb8..1025aa47f99 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppWrapper.java @@ -20,6 +20,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.List; @ApiModel(value = "PublicAppWrapper", description = "PublicAppWrapper represents an Application in App Store") @@ -77,8 +78,7 @@ public class PublicAppWrapper { @ApiModelProperty(name = "applicationReleaseWrappers", value = "List of public app releases", required = true) - @NotNull - private List publicAppReleaseWrappers; + private List publicAppReleaseWrappers = new ArrayList<>(); public String getName() { return name; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java index 090307a32de..b2a8c2f3e46 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java @@ -16,10 +16,12 @@ */ package io.entgra.application.mgt.common.wrapper; +import io.entgra.application.mgt.common.Base64File; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; +import java.util.List; @ApiModel(value = "ApplicationReleaseDTO", description = "This class holds the details when releasing an ApplicationDTO to application store") public class WebAppReleaseWrapper { @@ -63,6 +65,14 @@ public class WebAppReleaseWrapper { @NotNull private String url; + @ApiModelProperty(name = "screenshots", + value = "screenshots of the application") + private List screenshots; + + @ApiModelProperty(name = "icon", + value = "icon of the application") + private Base64File icon; + public String getReleaseType() { return releaseType; } @@ -114,4 +124,20 @@ public class WebAppReleaseWrapper { public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } + + public List getScreenshots() { + return screenshots; + } + + public void setScreenshots(List screenshots) { + this.screenshots = screenshots; + } + + public Base64File getIcon() { + return icon; + } + + public void setIcon(Base64File icon) { + this.icon = icon; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppWrapper.java index 8455f0ce672..e6f02593adb 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppWrapper.java @@ -20,6 +20,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.List; @ApiModel(value = "WebAppWrapper", description = "WebAppWrapper represents an ApplicationDTO in ApplicationDTO Store") @@ -78,7 +79,7 @@ public class WebAppWrapper { value = "List of web clip releases", required = true) @NotNull - private List webAppReleaseWrappers; + private List webAppReleaseWrappers = new ArrayList<>(); public String getName() { return name; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/Extension.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/Extension.java index 282f051889d..98741a5efdc 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/Extension.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/Extension.java @@ -77,6 +77,7 @@ public class Extension { * ApplicationManagement Extensions. */ public enum Name { + SPApplicationManager, ApplicationManager, ApplicationReleaseManager, CategoryManager, diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java new file mode 100644 index 00000000000..878a032be09 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java @@ -0,0 +1,53 @@ +package io.entgra.application.mgt.core.dao; + +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException; + +import java.util.List; + +public interface SPApplicationDAO { + /** + * + * @param tenantId + * @return the application with the provided installer location + * @throws ApplicationManagementDAOException + */ + List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException; + + /** + * + * @param tenantId + * @return the application with the provided installer location + * @throws ApplicationManagementDAOException + */ + int attachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException; + + /** + * + * @param tenantId + * @return the application with the provided installer location + * @throws ApplicationManagementDAOException + */ + void detachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException; + + List getIdentityServers(int tenantId) throws ApplicationManagementDAOException; + + IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException; + + /** + * Verify whether application exist for given application name and device type. Because a name and device type is + * unique for an application. + * + * @param appId id of the application. + * @param spUID UID of the service provider. + * @param tenantId ID of the tenant. + * @return ID of the ApplicationDTO. + * @throws ApplicationManagementDAOException Application Management DAO Exception. + */ + boolean isSPApplicationExist(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException; + + void deleteApplicationFromServiceProviders(int applicationId, int tenantId) throws ApplicationManagementDAOException; + + +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java index 414ca0d0153..9352a12aeb1 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java @@ -17,6 +17,11 @@ */ package io.entgra.application.mgt.core.dao.common; +import io.entgra.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.application.mgt.core.dao.impl.application.spapplication.GenericSPApplicationDAOImpl; +import io.entgra.application.mgt.core.dao.impl.application.spapplication.OracleSPApplicationDAOImpl; +import io.entgra.application.mgt.core.dao.impl.application.spapplication.PostgreSQLSPApplicationDAOImpl; +import io.entgra.application.mgt.core.dao.impl.application.spapplication.SQLServerSPApplicationDAOImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.application.mgt.common.exception.UnsupportedDatabaseEngineException; @@ -101,6 +106,25 @@ public class ApplicationManagementDAOFactory { throw new IllegalStateException("Database engine has not initialized properly."); } + public static SPApplicationDAO getSPApplicationDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case Constants.DataBaseTypes.DB_TYPE_H2: + case Constants.DataBaseTypes.DB_TYPE_MYSQL: + return new GenericSPApplicationDAOImpl(); + case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLSPApplicationDAOImpl(); + case Constants.DataBaseTypes.DB_TYPE_MSSQL: + return new SQLServerSPApplicationDAOImpl(); + case Constants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleSPApplicationDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + public static LifecycleStateDAO getLifecycleStateDAO() { if (databaseEngine != null) { switch (databaseEngine) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 9fa9743590b..9972fb05cc4 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -17,6 +17,9 @@ */ package io.entgra.application.mgt.core.dao.impl.application; +import io.entgra.application.mgt.common.ApplicationType; +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.core.util.Constants; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -137,12 +140,12 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, " + "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE " + "FROM AP_APP " - + "INNER JOIN AP_APP_RELEASE ON " + + "LEFT JOIN AP_APP_RELEASE ON " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + "INNER JOIN (SELECT AP_APP.ID FROM AP_APP "; if (StringUtils.isNotEmpty(filter.getVersion()) || StringUtils.isNotEmpty(filter.getAppReleaseState()) || StringUtils.isNotEmpty(filter.getAppReleaseType())) { - sql += "INNER JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "; + sql += "LEFT JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "; } sql += "WHERE AP_APP.TENANT_ID = ? "; @@ -183,7 +186,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic sql += "LIMIT ? OFFSET ? "; } sql += ") AS app_data ON app_data.ID = AP_APP.ID " - + "INNER JOIN (" + + "LEFT JOIN (" + "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID " + "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) " @@ -351,6 +354,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } } + @Override public ApplicationDTO getApplication(String releaseUuid, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { @@ -609,7 +613,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + "FROM AP_APP " - + "INNER JOIN AP_APP_RELEASE ON " + + "LEFT JOIN AP_APP_RELEASE ON " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID AND " + "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + "WHERE " diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java index 60e49f2a270..afc6a8cf412 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/OracleApplicationDAOImpl.java @@ -83,12 +83,12 @@ public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl { + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, " + "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE " + "FROM AP_APP " - + "INNER JOIN AP_APP_RELEASE ON " + + "LEFT JOIN AP_APP_RELEASE ON " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + "INNER JOIN (SELECT AP_APP.ID FROM AP_APP ORDER BY ID "; if (StringUtils.isNotEmpty(filter.getVersion()) || StringUtils.isNotEmpty(filter.getAppReleaseState()) || StringUtils.isNotEmpty(filter.getAppReleaseType())) { - sql += "INNER JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "; + sql += "LEFT JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "; } if (StringUtils.isNotEmpty(filter.getAppType())) { sql += "AND AP_APP.TYPE = ? "; @@ -127,7 +127,7 @@ public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl { sql += "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; } sql += ") AS app_data ON app_data.ID = AP_APP.ID " - + "INNER JOIN (" + + "LEFT JOIN (" + "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID " + "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) " diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java index 7420b9a0574..0212de34290 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java @@ -82,12 +82,12 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl { + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, " + "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE " + "FROM AP_APP " - + "INNER JOIN AP_APP_RELEASE ON " + + "LEFT JOIN AP_APP_RELEASE ON " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + "INNER JOIN (SELECT AP_APP.ID FROM AP_APP "; if (StringUtils.isNotEmpty(filter.getVersion()) || StringUtils.isNotEmpty(filter.getAppReleaseState()) || StringUtils.isNotEmpty(filter.getAppReleaseType())) { - sql += "INNER JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "; + sql += "LEFT JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "; } if (StringUtils.isNotEmpty(filter.getAppType())) { sql += "AND AP_APP.TYPE = ? "; @@ -126,7 +126,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl { sql += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; } sql += ") AS app_data ON app_data.ID = AP_APP.ID " - + "INNER JOIN (" + + "LEFT JOIN (" + "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID " + "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID " + "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) " diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java new file mode 100644 index 00000000000..f7ab51eef05 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -0,0 +1,290 @@ +package io.entgra.application.mgt.core.dao.impl.application.spapplication; + +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.exception.DBConnectionException; +import io.entgra.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.application.mgt.core.dao.impl.AbstractDAOImpl; +import io.entgra.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl; +import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPApplicationDAO { + + private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class); + @Override + public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT * " + + "FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved available identity servers" ); + } + return DAOUtil.loadIdentityServers(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT * " + + "FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ? AND " + + "ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setInt(1, tenantId); + stmt.setInt(2, id); + try (ResultSet rs = stmt.executeQuery()){ + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved available identity servers" ); + } + return DAOUtil.loadIdentityServer(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one identity server for id: " + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Getting identity server applications from the database"); + } + String sql = "SELECT " + + "AP_APP.ID AS APP_ID, " + + "AP_APP.NAME AS APP_NAME, " + + "AP_APP.DESCRIPTION AS APP_DESCRIPTION, " + + "AP_APP.TYPE AS APP_TYPE, " + + "AP_APP.STATUS AS APP_STATUS, " + + "AP_APP.SUB_TYPE AS APP_SUB_TYPE, " + + "AP_APP.CURRENCY AS APP_CURRENCY, " + + "AP_APP.RATING AS APP_RATING, " + + "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, " + + "AP_APP_RELEASE.ID AS RELEASE_ID, " + + "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, " + + "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, " + + "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + + "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, " + + "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, " + + "AP_APP_RELEASE.ICON_LOCATION AS AP_RELEASE_ICON_LOC, " + + "AP_APP_RELEASE.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, " + + "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, " + + "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, " + + "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, " + + "AP_APP_RELEASE.APP_HASH_VALUE AS RELEASE_HASH_VALUE, " + + "AP_APP_RELEASE.APP_PRICE AS RELEASE_PRICE, " + + "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, " + + "AP_APP_RELEASE.PACKAGE_NAME AS PACKAGE_NAME, " + + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "FROM AP_APP " + + "LEFT JOIN AP_APP_RELEASE ON " + + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID AND " + + "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + + "INNER JOIN AP_IS_SP_APP_MAPPING as SP_APPS on SP_APPS.AP_APP_ID = AP_APP.ID " + + "WHERE " + + "SP_APPS.SP_UID = ? " + + "AND SP_APPS.IS_ID = ? " + + "AND AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, spUID); + stmt.setInt(2, identityServerId); + stmt.setInt(3, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved basic details of the identity server applications"); + } + return DAOUtil.loadApplications(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to get identity server applications for application release"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while getting identity server applications while executing query. Executed query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public boolean isSPApplicationExist(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP_ID AS ID " + + "FROM AP_IS_SP_APP_MAPPING SP_MAPPING " + + "WHERE " + + "SP_UID = ? AND AP_APP_ID = ? " + + "AND IS_ID = ? AND " + + "TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check whether the existence of " + + "sp application with id " + appId + " for service provider which has UID " + spUID; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check whether the existence of service provider application " + + "with id " + appId + " for service provider which has UID " + spUID + ". executed query " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void detachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to map an application wit identity server:service provider"); + log.debug("Application Details : "); + log.debug("App ID : " + appId + " SP UID : " + spUID + " IS ID : " + identityServerId); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING " + + "WHERE SP_UID = ? " + + "AND AP_APP_ID = ? " + + "AND IS_ID = ? " + + "AND TENANT_ID = ? "; + + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public int attachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to map an application wit identity server:service provider"); + log.debug("Application Details : "); + log.debug("App ID : " + appId + " SP UID : " + spUID + " IS ID : " + identityServerId); + } + String sql = "INSERT INTO AP_IS_SP_APP_MAPPING " + + "(SP_UID, " + + "AP_APP_ID, " + + "IS_ID, TENANT_ID) " + + "VALUES (?, ?, ?, ?)"; + int mappingId = -1; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + mappingId = rs.getInt(1); + } + return mappingId; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteApplicationFromServiceProviders(int applicationId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application with the id: " + applicationId + " from service providers"); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING WHERE AP_APP_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, applicationId); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + applicationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + applicationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java new file mode 100644 index 00000000000..553daa263c0 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -0,0 +1,289 @@ +package io.entgra.application.mgt.core.dao.impl.application.spapplication; + +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.exception.DBConnectionException; +import io.entgra.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.application.mgt.core.dao.impl.AbstractDAOImpl; +import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPApplicationDAO { + + private static final Log log = LogFactory.getLog(OracleSPApplicationDAOImpl.class); + + @Override + public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT * " + + "FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved available identity servers" ); + } + return DAOUtil.loadIdentityServers(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT * " + + "FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ? AND " + + "ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setInt(1, tenantId); + stmt.setInt(2, id); + try (ResultSet rs = stmt.executeQuery()){ + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved available identity servers" ); + } + return DAOUtil.loadIdentityServer(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one identity server for id: " + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Getting identity server applications from the database"); + } + String sql = "SELECT " + + "AP_APP.ID AS APP_ID, " + + "AP_APP.NAME AS APP_NAME, " + + "AP_APP.DESCRIPTION AS APP_DESCRIPTION, " + + "AP_APP.TYPE AS APP_TYPE, " + + "AP_APP.STATUS AS APP_STATUS, " + + "AP_APP.SUB_TYPE AS APP_SUB_TYPE, " + + "AP_APP.CURRENCY AS APP_CURRENCY, " + + "AP_APP.RATING AS APP_RATING, " + + "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, " + + "AP_APP_RELEASE.ID AS RELEASE_ID, " + + "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, " + + "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, " + + "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + + "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, " + + "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, " + + "AP_APP_RELEASE.ICON_LOCATION AS AP_RELEASE_ICON_LOC, " + + "AP_APP_RELEASE.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, " + + "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, " + + "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, " + + "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, " + + "AP_APP_RELEASE.APP_HASH_VALUE AS RELEASE_HASH_VALUE, " + + "AP_APP_RELEASE.APP_PRICE AS RELEASE_PRICE, " + + "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, " + + "AP_APP_RELEASE.PACKAGE_NAME AS PACKAGE_NAME, " + + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "FROM AP_APP " + + "LEFT JOIN AP_APP_RELEASE ON " + + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID AND " + + "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + + "INNER JOIN AP_IS_SP_APP_MAPPING as SP_APPS on SP_APPS.AP_APP_ID = AP_APP.ID " + + "WHERE " + + "SP_APPS.SP_UID = ? " + + "AND SP_APPS.IS_ID = ? " + + "AND AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, spUID); + stmt.setInt(2, identityServerId); + stmt.setInt(3, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved basic details of the identity server applications"); + } + return DAOUtil.loadApplications(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to get identity server applications for application release"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while getting identity server applications while executing query. Executed query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public boolean isSPApplicationExist(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP_ID AS ID " + + "FROM AP_IS_SP_APP_MAPPING SP_MAPPING " + + "WHERE " + + "SP_UID = ? AND AP_APP_ID = ? " + + "AND IS_ID = ? AND " + + "TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check whether the existence of " + + "sp application with id " + appId + " for service provider which has UID " + spUID; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check whether the existence of service provider application " + + "with id " + appId + " for service provider which has UID " + spUID + ". executed query " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void detachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to map an application wit identity server:service provider"); + log.debug("Application Details : "); + log.debug("App ID : " + appId + " SP UID : " + spUID + " IS ID : " + identityServerId); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING " + + "WHERE SP_UID = ? " + + "AND AP_APP_ID = ? " + + "AND IS_ID = ? " + + "AND TENANT_ID = ? "; + + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public int attachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to map an application wit identity server:service provider"); + log.debug("Application Details : "); + log.debug("App ID : " + appId + " SP UID : " + spUID + " IS ID : " + identityServerId); + } + String sql = "INSERT INTO AP_IS_SP_APP_MAPPING " + + "(SP_UID, " + + "AP_APP_ID, " + + "IS_ID, TENANT_ID) " + + "VALUES (?, ?, ?, ?)"; + int mappingId = -1; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + mappingId = rs.getInt(1); + } + return mappingId; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteApplicationFromServiceProviders(int applicationId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application with the id: " + applicationId + " from service providers"); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING WHERE AP_APP_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, applicationId); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + applicationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + applicationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java new file mode 100644 index 00000000000..309c77b1d86 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -0,0 +1,289 @@ +package io.entgra.application.mgt.core.dao.impl.application.spapplication; + +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.exception.DBConnectionException; +import io.entgra.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.application.mgt.core.dao.impl.AbstractDAOImpl; +import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements SPApplicationDAO { + + private static final Log log = LogFactory.getLog(PostgreSQLSPApplicationDAOImpl.class); + + @Override + public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT * " + + "FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved available identity servers" ); + } + return DAOUtil.loadIdentityServers(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT * " + + "FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ? AND " + + "ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setInt(1, tenantId); + stmt.setInt(2, id); + try (ResultSet rs = stmt.executeQuery()){ + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved available identity servers" ); + } + return DAOUtil.loadIdentityServer(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one identity server for id: " + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Getting identity server applications from the database"); + } + String sql = "SELECT " + + "AP_APP.ID AS APP_ID, " + + "AP_APP.NAME AS APP_NAME, " + + "AP_APP.DESCRIPTION AS APP_DESCRIPTION, " + + "AP_APP.TYPE AS APP_TYPE, " + + "AP_APP.STATUS AS APP_STATUS, " + + "AP_APP.SUB_TYPE AS APP_SUB_TYPE, " + + "AP_APP.CURRENCY AS APP_CURRENCY, " + + "AP_APP.RATING AS APP_RATING, " + + "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, " + + "AP_APP_RELEASE.ID AS RELEASE_ID, " + + "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, " + + "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, " + + "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + + "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, " + + "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, " + + "AP_APP_RELEASE.ICON_LOCATION AS AP_RELEASE_ICON_LOC, " + + "AP_APP_RELEASE.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, " + + "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, " + + "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, " + + "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, " + + "AP_APP_RELEASE.APP_HASH_VALUE AS RELEASE_HASH_VALUE, " + + "AP_APP_RELEASE.APP_PRICE AS RELEASE_PRICE, " + + "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, " + + "AP_APP_RELEASE.PACKAGE_NAME AS PACKAGE_NAME, " + + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "FROM AP_APP " + + "LEFT JOIN AP_APP_RELEASE ON " + + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID AND " + + "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + + "INNER JOIN AP_IS_SP_APP_MAPPING as SP_APPS on SP_APPS.AP_APP_ID = AP_APP.ID " + + "WHERE " + + "SP_APPS.SP_UID = ? " + + "AND SP_APPS.IS_ID = ? " + + "AND AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, spUID); + stmt.setInt(2, identityServerId); + stmt.setInt(3, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved basic details of the identity server applications"); + } + return DAOUtil.loadApplications(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to get identity server applications for application release"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while getting identity server applications while executing query. Executed query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public boolean isSPApplicationExist(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP_ID AS ID " + + "FROM AP_IS_SP_APP_MAPPING SP_MAPPING " + + "WHERE " + + "SP_UID = ? AND AP_APP_ID = ? " + + "AND IS_ID = ? AND " + + "TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check whether the existence of " + + "sp application with id " + appId + " for service provider which has UID " + spUID; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check whether the existence of service provider application " + + "with id " + appId + " for service provider which has UID " + spUID + ". executed query " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void detachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to map an application wit identity server:service provider"); + log.debug("Application Details : "); + log.debug("App ID : " + appId + " SP UID : " + spUID + " IS ID : " + identityServerId); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING " + + "WHERE SP_UID = ? " + + "AND AP_APP_ID = ? " + + "AND IS_ID = ? " + + "AND TENANT_ID = ? "; + + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public int attachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to map an application wit identity server:service provider"); + log.debug("Application Details : "); + log.debug("App ID : " + appId + " SP UID : " + spUID + " IS ID : " + identityServerId); + } + String sql = "INSERT INTO AP_IS_SP_APP_MAPPING " + + "(SP_UID, " + + "AP_APP_ID, " + + "IS_ID, TENANT_ID) " + + "VALUES (?, ?, ?, ?)"; + int mappingId = -1; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + mappingId = rs.getInt(1); + } + return mappingId; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteApplicationFromServiceProviders(int applicationId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application with the id: " + applicationId + " from service providers"); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING WHERE AP_APP_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, applicationId); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + applicationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + applicationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java new file mode 100644 index 00000000000..e31be220275 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -0,0 +1,289 @@ +package io.entgra.application.mgt.core.dao.impl.application.spapplication; + +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.exception.DBConnectionException; +import io.entgra.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.application.mgt.core.dao.impl.AbstractDAOImpl; +import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; +import io.entgra.application.mgt.core.util.DAOUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements SPApplicationDAO { + + private static final Log log = LogFactory.getLog(SQLServerSPApplicationDAOImpl.class); + + @Override + public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT * " + + "FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setInt(1, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved available identity servers" ); + } + return DAOUtil.loadIdentityServers(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT * " + + "FROM AP_IDENTITY_SERVER " + + "WHERE TENANT_ID = ? AND " + + "ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setInt(1, tenantId); + stmt.setInt(2, id); + try (ResultSet rs = stmt.executeQuery()){ + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved available identity servers" ); + } + return DAOUtil.loadIdentityServer(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to retrieve available identity servers"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (UnexpectedServerErrorException e) { + String msg = "Found more than one identity server for id: " + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Getting identity server applications from the database"); + } + String sql = "SELECT " + + "AP_APP.ID AS APP_ID, " + + "AP_APP.NAME AS APP_NAME, " + + "AP_APP.DESCRIPTION AS APP_DESCRIPTION, " + + "AP_APP.TYPE AS APP_TYPE, " + + "AP_APP.STATUS AS APP_STATUS, " + + "AP_APP.SUB_TYPE AS APP_SUB_TYPE, " + + "AP_APP.CURRENCY AS APP_CURRENCY, " + + "AP_APP.RATING AS APP_RATING, " + + "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, " + + "AP_APP_RELEASE.ID AS RELEASE_ID, " + + "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, " + + "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, " + + "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + + "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, " + + "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, " + + "AP_APP_RELEASE.ICON_LOCATION AS AP_RELEASE_ICON_LOC, " + + "AP_APP_RELEASE.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, " + + "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, " + + "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, " + + "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, " + + "AP_APP_RELEASE.APP_HASH_VALUE AS RELEASE_HASH_VALUE, " + + "AP_APP_RELEASE.APP_PRICE AS RELEASE_PRICE, " + + "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, " + + "AP_APP_RELEASE.PACKAGE_NAME AS PACKAGE_NAME, " + + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + + "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + + "FROM AP_APP " + + "LEFT JOIN AP_APP_RELEASE ON " + + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID AND " + + "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + + "INNER JOIN AP_IS_SP_APP_MAPPING as SP_APPS on SP_APPS.AP_APP_ID = AP_APP.ID " + + "WHERE " + + "SP_APPS.SP_UID = ? " + + "AND SP_APPS.IS_ID = ? " + + "AND AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, spUID); + stmt.setInt(2, identityServerId); + stmt.setInt(3, tenantId); + try (ResultSet rs = stmt.executeQuery()) { + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved basic details of the identity server applications"); + } + return DAOUtil.loadApplications(rs); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to get identity server applications for application release"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while getting identity server applications while executing query. Executed query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public boolean isSPApplicationExist(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP_ID AS ID " + + "FROM AP_IS_SP_APP_MAPPING SP_MAPPING " + + "WHERE " + + "SP_UID = ? AND AP_APP_ID = ? " + + "AND IS_ID = ? AND " + + "TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check whether the existence of " + + "sp application with id " + appId + " for service provider which has UID " + spUID; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check whether the existence of service provider application " + + "with id " + appId + " for service provider which has UID " + spUID + ". executed query " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + + } + + @Override + public void detachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to map an application wit identity server:service provider"); + log.debug("Application Details : "); + log.debug("App ID : " + appId + " SP UID : " + spUID + " IS ID : " + identityServerId); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING " + + "WHERE SP_UID = ? " + + "AND AP_APP_ID = ? " + + "AND IS_ID = ? " + + "AND TENANT_ID = ? "; + + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public int attachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to map an application wit identity server:service provider"); + log.debug("Application Details : "); + log.debug("App ID : " + appId + " SP UID : " + spUID + " IS ID : " + identityServerId); + } + String sql = "INSERT INTO AP_IS_SP_APP_MAPPING " + + "(SP_UID, " + + "AP_APP_ID, " + + "IS_ID, TENANT_ID) " + + "VALUES (?, ?, ?, ?)"; + int mappingId = -1; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, spUID); + stmt.setInt(2, appId); + stmt.setInt(3, identityServerId); + stmt.setInt(4, tenantId); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + mappingId = rs.getInt(1); + } + return mappingId; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + appId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void deleteApplicationFromServiceProviders(int applicationId, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete application with the id: " + applicationId + " from service providers"); + } + String sql = "DELETE FROM AP_IS_SP_APP_MAPPING WHERE AP_APP_ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, applicationId); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + + "application id " + applicationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an application which has application id " + + applicationId; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java index 82405ee2fe9..f413fee76ce 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java @@ -17,6 +17,8 @@ package io.entgra.application.mgt.core.impl; +import io.entgra.application.mgt.common.Base64File; +import io.entgra.application.mgt.core.dao.SPApplicationDAO; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; @@ -109,8 +111,7 @@ import java.util.stream.Stream; /** * Default Concrete implementation of Application Management related implementations. */ -public class -ApplicationManagerImpl implements ApplicationManager { +public class ApplicationManagerImpl implements ApplicationManager { private static final Log log = LogFactory.getLog(ApplicationManagerImpl.class); private VisibilityDAO visibilityDAO; @@ -119,6 +120,7 @@ ApplicationManagerImpl implements ApplicationManager { private LifecycleStateDAO lifecycleStateDAO; private SubscriptionDAO subscriptionDAO; private LifecycleStateManager lifecycleStateManager; + private SPApplicationDAO spApplicationDAO; public ApplicationManagerImpl() { initDataAccessObjects(); @@ -131,11 +133,21 @@ ApplicationManagerImpl implements ApplicationManager { this.lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO(); this.applicationReleaseDAO = ApplicationManagementDAOFactory.getApplicationReleaseDAO(); this.subscriptionDAO = ApplicationManagementDAOFactory.getSubscriptionDAO(); + this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO(); } @Override - public Application createEntApp(ApplicationWrapper applicationWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + public ApplicationReleaseDTO uploadEntAppReleaseArtifacts(EntAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, + String deviceType) throws ApplicationManagementException { + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + return uploadEntAppReleaseArtifacts(releaseDTO, artifact, deviceType, tenantId, true); + } + + @Override + public ApplicationDTO uploadEntAppReleaseArtifacts(ApplicationWrapper applicationWrapper, + ApplicationArtifact applicationArtifact) + throws ApplicationManagementException{ if (log.isDebugEnabled()) { log.debug("Ent. Application create request is received. Application name: " + applicationWrapper.getName() + " Device type: " + applicationWrapper.getDeviceType()); @@ -149,12 +161,21 @@ ApplicationManagerImpl implements ApplicationManager { applicationWrapper.getDeviceType(), tenantId, false); applicationDTO.getApplicationReleaseDTOs().clear(); applicationDTO.getApplicationReleaseDTOs().add(applicationReleaseDTO); - return addAppDataIntoDB(applicationDTO, tenantId); + return applicationDTO; } @Override - public Application createWebClip(WebAppWrapper webAppWrapper, ApplicationArtifact applicationArtifact) - throws ApplicationManagementException { + public ApplicationReleaseDTO uploadWebAppReleaseArtifacts(WebAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact) + throws ResourceManagementException { + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + return uploadWebAppReleaseArtifacts(releaseDTO, artifact, tenantId); + } + + @Override + public ApplicationDTO uploadWebAppReleaseArtifacts(WebAppWrapper webAppWrapper, + ApplicationArtifact applicationArtifact) + throws ApplicationManagementException{ if (log.isDebugEnabled()) { log.debug("Web clip create request is received. App name: " + webAppWrapper.getName() + " Device type: " + Constants.ANY); @@ -162,25 +183,38 @@ ApplicationManagerImpl implements ApplicationManager { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(webAppWrapper); ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); - applicationReleaseDTO.setUuid(UUID.randomUUID().toString()); - applicationReleaseDTO.setAppHashValue(DigestUtils.md5Hex(applicationReleaseDTO.getInstallerName())); - //uploading application artifacts try { applicationDTO.getApplicationReleaseDTOs().clear(); - applicationDTO.getApplicationReleaseDTOs() - .add(addImageArtifacts(applicationReleaseDTO, applicationArtifact, tenantId)); + applicationDTO.getApplicationReleaseDTOs().add(uploadWebAppReleaseArtifacts(applicationReleaseDTO, applicationArtifact, tenantId)); + return applicationDTO; } catch (ResourceManagementException e) { - String msg = "Error Occured when uploading artifacts of the web clip: " + webAppWrapper.getName(); + String msg = "Error Occurred when uploading artifacts of the web clip: " + webAppWrapper.getName(); log.error(msg); throw new ApplicationManagementException(msg, e); } - //insert application data into database - return addAppDataIntoDB(applicationDTO, tenantId); + } + + public ApplicationReleaseDTO uploadWebAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, + int tenantId) + throws ResourceManagementException { + releaseDTO.setUuid(UUID.randomUUID().toString()); + releaseDTO.setAppHashValue(DigestUtils.md5Hex(releaseDTO.getInstallerName())); + //uploading application artifacts + return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); } @Override - public Application createPublicApp(PublicAppWrapper publicAppWrapper, ApplicationArtifact applicationArtifact) - throws ApplicationManagementException { + public ApplicationReleaseDTO uploadPubAppReleaseArtifacts(PublicAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, + String deviceType) throws ResourceManagementException { + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + return uploadPubAppReleaseArtifacts(releaseDTO, artifact, deviceType, tenantId); + } + + @Override + public ApplicationDTO uploadPublicAppReleaseArtifacts(PublicAppWrapper publicAppWrapper, + ApplicationArtifact applicationArtifact) + throws ApplicationManagementException{ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); if (log.isDebugEnabled()) { @@ -188,114 +222,165 @@ ApplicationManagerImpl implements ApplicationManager { + " Device Type: " + publicAppWrapper.getDeviceType()); } - String publicAppStorePath = ""; - if (DeviceTypes.ANDROID.toString().equalsIgnoreCase(publicAppWrapper.getDeviceType())) { - publicAppStorePath = Constants.GOOGLE_PLAY_STORE_URL; - } else if (DeviceTypes.IOS.toString().equals(publicAppWrapper.getDeviceType())) { - publicAppStorePath = Constants.APPLE_STORE_URL; - } ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(publicAppWrapper); ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); - String appInstallerUrl = publicAppStorePath + applicationReleaseDTO.getPackageName(); - applicationReleaseDTO.setInstallerName(appInstallerUrl); - applicationReleaseDTO.setUuid(UUID.randomUUID().toString()); - applicationReleaseDTO.setAppHashValue(DigestUtils.md5Hex(appInstallerUrl)); + validatePublicAppReleasePackageName(applicationReleaseDTO.getPackageName()); + + try { + //uploading application artifacts + applicationReleaseDTO = uploadPubAppReleaseArtifacts(applicationReleaseDTO, applicationArtifact, + publicAppWrapper.getDeviceType(), tenantId); + applicationDTO.getApplicationReleaseDTOs().clear(); + applicationDTO.getApplicationReleaseDTOs().add(applicationReleaseDTO); + return applicationDTO; + } catch (ResourceManagementException e) { + String msg = "Error Occured when uploading artifacts of the public app: " + publicAppWrapper.getName(); + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + + public ApplicationReleaseDTO uploadPubAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, + String deviceType, int tenantId) + throws ResourceManagementException { + String appInstallerUrl = getPublicAppStorePath(deviceType) + releaseDTO.getPackageName(); + releaseDTO.setInstallerName(appInstallerUrl); + releaseDTO.setUuid(UUID.randomUUID().toString()); + releaseDTO.setAppHashValue(DigestUtils.md5Hex(appInstallerUrl)); + //uploading application artifacts + return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); + } + public void validatePublicAppReleasePackageName(String packageName) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { ConnectionManagerUtil.openDBConnection(); List exitingPubAppReleases = applicationReleaseDAO - .getReleaseByPackages(Collections.singletonList(applicationReleaseDTO.getPackageName()), tenantId); + .getReleaseByPackages(Collections.singletonList(packageName), tenantId); if (!exitingPubAppReleases.isEmpty()){ - String msg = "Public app release exists for package name " + applicationReleaseDTO.getPackageName() + String msg = "Public app release exists for package name " + packageName + ". Hence you can't add new public app for package name " - + applicationReleaseDTO.getPackageName(); + + packageName; log.error(msg); throw new BadRequestException(msg); } } catch (ApplicationManagementDAOException e) { - String msg = "Error Occured when fetching release: " + publicAppWrapper.getName(); + String msg = "Error Occurred when fetching release: " + packageName; log.error(msg); throw new ApplicationManagementException(msg, e); } finally { ConnectionManagerUtil.closeDBConnection(); } + } - try { - //uploading application artifacts - applicationReleaseDTO = addImageArtifacts(applicationReleaseDTO, applicationArtifact, tenantId); - applicationDTO.getApplicationReleaseDTOs().clear(); - applicationDTO.getApplicationReleaseDTOs().add(applicationReleaseDTO); - } catch (ResourceManagementException e) { - String msg = "Error Occured when uploading artifacts of the public app: " + publicAppWrapper.getName(); - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } - //insert application data into database - return addAppDataIntoDB(applicationDTO, tenantId); + @Override + public ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(CustomAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, + String deviceType) throws ResourceManagementException, ApplicationManagementException { + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + return uploadCustomAppReleaseArtifacts(releaseDTO, artifact, deviceType, tenantId); } @Override - public Application createCustomApp(CustomAppWrapper customAppWrapper, ApplicationArtifact applicationArtifact) + public ApplicationDTO uploadCustomAppReleaseArtifactsAndConstructAppDTO(CustomAppWrapper customAppWrapper, + ApplicationArtifact applicationArtifact) throws ApplicationManagementException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); - byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream()); - String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content)); - if (md5OfApp == null) { - String msg = - "Error occurred while getting md5sum value of custom app. Application name: " + customAppWrapper - .getName() + " Device type: " + customAppWrapper.getDeviceType(); - log.error(msg); - throw new ApplicationManagementException(msg); - } - try { - ConnectionManagerUtil.openDBConnection(); - if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(md5OfApp, tenantId)) { - String msg = "Application release exists for the uploaded binary file. Application name: " - + customAppWrapper.getName() + " Device type: " + customAppWrapper.getDeviceType(); - log.error(msg); - throw new BadRequestException(msg); - } - } catch (ApplicationManagementDAOException e) { - String msg = "Error occurred while adding application data into the database. Application name: " - + customAppWrapper.getName() + " Device type: " + customAppWrapper.getDeviceType(); - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(customAppWrapper); ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); - applicationReleaseDTO.setUuid(UUID.randomUUID().toString()); - applicationReleaseDTO.setAppHashValue(md5OfApp); - applicationReleaseDTO.setInstallerName(applicationArtifact.getInstallerName()); - try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) { - applicationStorageManager.uploadReleaseArtifact(applicationReleaseDTO, customAppWrapper.getDeviceType(), - binaryDuplicate, tenantId); - } catch (IOException e) { - String msg = "Error occurred when uploading release artifact into the server."; - log.error(msg); - throw new ApplicationManagementException(msg); - } - applicationReleaseDTO = addImageArtifacts(applicationReleaseDTO, applicationArtifact, tenantId); + applicationReleaseDTO = uploadCustomAppReleaseArtifacts(applicationReleaseDTO, applicationArtifact, + customAppWrapper.getDeviceType(), tenantId); applicationDTO.getApplicationReleaseDTOs().clear(); applicationDTO.getApplicationReleaseDTOs().add(applicationReleaseDTO); - return addAppDataIntoDB(applicationDTO, tenantId); + return applicationDTO; } catch (ResourceManagementException e) { String msg = "Error occurred while uploading application artifact into the server. Application name: " + customAppWrapper.getName() + " Device type: " + customAppWrapper.getDeviceType(); log.error(msg, e); throw new ApplicationManagementException(msg, e); + } + } + + public ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, + String deviceType, int tenantId) + throws ResourceManagementException, ApplicationManagementException { + ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); + byte[] content = getByteContentOfApp(applicationArtifact); + String md5OfApp = generateMD5OfApp(applicationArtifact, content); + validateReleaseBinaryFileHash(md5OfApp); + releaseDTO.setUuid(UUID.randomUUID().toString()); + releaseDTO.setAppHashValue(md5OfApp); + releaseDTO.setInstallerName(applicationArtifact.getInstallerName()); + + try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) { + applicationStorageManager.uploadReleaseArtifact(releaseDTO, deviceType, + binaryDuplicate, tenantId); } catch (IOException e) { - String msg = "Error occurred while getting bytes from application release artifact. Application name: " - + customAppWrapper.getName() + " Device type: " + customAppWrapper.getDeviceType(); + String msg = "Error occurred when uploading release artifact into the server"; + log.error(msg); + throw new ApplicationManagementException(msg); + } + return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); + } + + public void validateReleaseBinaryFileHash(String hash) + throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + if (this.applicationReleaseDAO.verifyReleaseExistenceByHash(hash, tenantId)) { + String msg = "Application release already exists"; + log.error(msg); + throw new BadRequestException(msg); + } + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while checking if release already exists"; log.error(msg, e); throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + public String getPublicAppStorePath(String deviceType) { + if (DeviceTypes.ANDROID.toString().equalsIgnoreCase(deviceType)) { + return Constants.GOOGLE_PLAY_STORE_URL; + } else if (DeviceTypes.IOS.toString().equalsIgnoreCase(deviceType)) { + return Constants.APPLE_STORE_URL; + } else { + throw new IllegalArgumentException("No such device with the name " + deviceType); } } + private byte[] getByteContentOfApp(ApplicationArtifact artifact) throws ApplicationManagementException{ + try { + return IOUtils.toByteArray(artifact.getInstallerStream()); + } catch (IOException e) { + String msg = "Error occurred while getting byte content of app binary artifact"; + log.error(msg); + throw new ApplicationManagementException(msg); + } + } + + private String generateMD5OfApp(ApplicationArtifact applicationArtifact, byte[] content) throws ApplicationManagementException { + try { + String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content)); + if (md5OfApp == null) { + String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + return md5OfApp; + } catch( ApplicationStorageManagementException e) { + String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName(); + log.error(msg); + throw new ApplicationManagementException(msg); + } + } + + + /** * Delete Application release artifacts * @@ -327,7 +412,7 @@ ApplicationManagerImpl implements ApplicationManager { * @throws ApplicationManagementException if error occurred while handling application release data. */ private ApplicationReleaseDTO addApplicationReleaseArtifacts(String deviceType, - ApplicationReleaseDTO applicationReleaseDTO, ApplicationArtifact applicationArtifact, boolean isNewRelease) + ApplicationReleaseDTO applicationReleaseDTO, ApplicationArtifact applicationArtifact, boolean isNewRelease) throws ResourceManagementException, ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); @@ -423,7 +508,7 @@ ApplicationManagerImpl implements ApplicationManager { * @throws ApplicationManagementException if error occurred while handling application release data. */ private ApplicationReleaseDTO updateEntAppReleaseArtifact(String deviceType, - ApplicationReleaseDTO applicationReleaseDTO, ApplicationArtifact applicationArtifact) + ApplicationReleaseDTO applicationReleaseDTO, ApplicationArtifact applicationArtifact) throws ResourceManagementException, ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); @@ -518,7 +603,7 @@ ApplicationManagerImpl implements ApplicationManager { * @throws ResourceManagementException if error occurred while uploading image artifacts into file system. */ private ApplicationReleaseDTO addImageArtifacts(ApplicationReleaseDTO applicationReleaseDTO, - ApplicationArtifact applicationArtifact, int tenantId) throws ResourceManagementException { + ApplicationArtifact applicationArtifact, int tenantId) throws ResourceManagementException { ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); applicationReleaseDTO.setIconName(applicationArtifact.getIconName()); @@ -555,7 +640,7 @@ ApplicationManagerImpl implements ApplicationManager { * @throws ResourceManagementException if error occurred while uploading application release artifacts into the file system. */ private ApplicationReleaseDTO updateImageArtifacts(ApplicationReleaseDTO applicationReleaseDTO, - ApplicationArtifact applicationArtifact, int tenantId) throws ResourceManagementException{ + ApplicationArtifact applicationArtifact, int tenantId) throws ResourceManagementException{ ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); if (!StringUtils.isEmpty(applicationArtifact.getIconName())) { @@ -608,6 +693,7 @@ ApplicationManagerImpl implements ApplicationManager { return applicationReleaseDTO; } + @Override public ApplicationList getApplications(Filter filter) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -665,7 +751,6 @@ ApplicationManagerImpl implements ApplicationManager { applications.add(application); } } - Pagination pagination = new Pagination(); pagination.setCount(applicationDAO.getApplicationCount(filter, deviceType.getId(), tenantId)); pagination.setSize(applications.size()); @@ -732,7 +817,6 @@ ApplicationManagerImpl implements ApplicationManager { } return true; } - /** * To check whether the application is whether hideable or not * @@ -740,7 +824,8 @@ ApplicationManagerImpl implements ApplicationManager { * @return true if application releases are in hideable state (i.e Retired), otherwise returns false * @throws ApplicationManagementException if error occurred while getting application release end state. */ - private boolean isHideableApp(List applicationReleaseDTOs) + @Override + public boolean isHideableApp(List applicationReleaseDTOs) throws ApplicationManagementException { try { for (ApplicationReleaseDTO applicationReleaseDTO : applicationReleaseDTOs) { @@ -764,7 +849,8 @@ ApplicationManagerImpl implements ApplicationManager { * @throws ApplicationManagementException if error occurred while checking whether the application release is in * deletable state or not. */ - private boolean isDeletableApp(List applicationReleaseDTOs) + @Override + public boolean isDeletableApp(List applicationReleaseDTOs) throws ApplicationManagementException { try { for (ApplicationReleaseDTO applicationReleaseDTO : applicationReleaseDTOs) { @@ -845,7 +931,7 @@ ApplicationManagerImpl implements ApplicationManager { * @throws UserStoreException if error occurred when checking whether user has assigned at least one filtering role. */ private boolean hasAppUnrestrictedRole(List appUnrestrictedRoles, List filteringUnrestrictedRoles, - String userName) throws BadRequestException, UserStoreException { + String userName) throws BadRequestException, UserStoreException { if (!hasUserRole(filteringUnrestrictedRoles, userName)) { String msg = "At least one filtering role is not assigned for the user: " + userName + ". Hence user " + userName @@ -863,44 +949,62 @@ ApplicationManagerImpl implements ApplicationManager { return false; } - /*** - * This method is responsible to add application data into APPM database. However, before call this method it is - * required to do the validation of request and check the existence of application releaseDTO. - * - * @param applicationDTO Application DTO object. - * @param tenantId Tenant Id - * @return {@link Application} - * @throws ApplicationManagementException which throws if error occurs while during application management. - */ - private Application addAppDataIntoDB(ApplicationDTO applicationDTO, int tenantId) throws ApplicationManagementException { - ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); - List unrestrictedRoles = applicationDTO.getUnrestrictedRoles(); - ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); - List categories = applicationDTO.getAppCategories(); - List tags = applicationDTO.getTags(); - List applicationReleaseEntities = new ArrayList<>(); + @Override + public Application persistApplication(ApplicationDTO applicationDTO) throws ApplicationManagementException { try { ConnectionManagerUtil.beginDBTransaction(); + Application application = executeApplicationPersistenceTransaction(applicationDTO); + ConnectionManagerUtil.commitDBTransaction(); + return application; + } catch (DBConnectionException e) { + String msg = "Error occurred while getting database connection."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while disabling AutoCommit."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while adding application with the name " + applicationDTO.getName() + " to database "; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public Application executeApplicationPersistenceTransaction(ApplicationDTO applicationDTO) throws + ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + ApplicationReleaseDTO applicationReleaseDTO = null; + if (applicationDTO.getApplicationReleaseDTOs().size() > 0) { + applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); + } + try { // Insert to application table int appId = this.applicationDAO.createApplication(applicationDTO, tenantId); if (appId == -1) { - log.error("Application data storing is Failed."); - ConnectionManagerUtil.rollbackDBTransaction(); - deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), - tenantId); - return null; + if (applicationReleaseDTO != null) { + deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), + tenantId); + } + String msg = "Application data storing is Failed."; + log.error(msg); + throw new ApplicationManagementDAOException(msg); } else { if (log.isDebugEnabled()) { log.debug("New ApplicationDTO entry added to AP_APP table. App Id:" + appId); } //add application categories - List categoryIds = applicationDAO.getCategoryIdsForCategoryNames(categories, tenantId); + List categoryIds = applicationDAO.getCategoryIdsForCategoryNames(applicationDTO.getAppCategories(), tenantId); this.applicationDAO.addCategoryMapping(categoryIds, appId, tenantId); //adding application unrestricted roles - if (unrestrictedRoles != null && !unrestrictedRoles.isEmpty()) { - this.visibilityDAO.addUnrestrictedRoles(unrestrictedRoles, appId, tenantId); + if (applicationDTO.getUnrestrictedRoles() != null && !applicationDTO.getUnrestrictedRoles().isEmpty()) { + this.visibilityDAO.addUnrestrictedRoles(applicationDTO.getUnrestrictedRoles(), appId, tenantId); if (log.isDebugEnabled()) { log.debug("New restricted roles to app ID mapping added to AP_UNRESTRICTED_ROLE table." + " App Id:" + appId); @@ -908,7 +1012,7 @@ ApplicationManagerImpl implements ApplicationManager { } //adding application tags - if (tags != null && !tags.isEmpty()) { + if (applicationDTO.getTags() != null && !applicationDTO.getTags().isEmpty()) { List registeredTags = applicationDAO.getAllTags(tenantId); List registeredTagNames = new ArrayList<>(); List tagIds = new ArrayList<>(); @@ -916,16 +1020,16 @@ ApplicationManagerImpl implements ApplicationManager { for (TagDTO tagDTO : registeredTags) { registeredTagNames.add(tagDTO.getTagName()); } - List newTags = getDifference(tags, registeredTagNames); + List newTags = getDifference(applicationDTO.getTags(), registeredTagNames); if (!newTags.isEmpty()) { this.applicationDAO.addTags(newTags, tenantId); if (log.isDebugEnabled()) { log.debug("New tags entry added to AP_APP_TAG table. App Id:" + appId); } - tagIds = this.applicationDAO.getTagIdsForTagNames(tags, tenantId); + tagIds = this.applicationDAO.getTagIdsForTagNames(applicationDTO.getTags(), tenantId); } else { for (TagDTO tagDTO : registeredTags) { - for (String tagName : tags) { + for (String tagName : applicationDTO.getTags()) { if (tagName.equals(tagDTO.getTagName())) { tagIds.add(tagDTO.getId()); break; @@ -939,25 +1043,26 @@ ApplicationManagerImpl implements ApplicationManager { if (log.isDebugEnabled()) { log.debug("Creating a new release. App Id:" + appId); } - String initialLifecycleState = lifecycleStateManager.getInitialState(); - applicationReleaseDTO.setCurrentState(initialLifecycleState); - applicationReleaseDTO = this.applicationReleaseDAO - .createRelease(applicationReleaseDTO, appId, tenantId); - LifecycleState lifecycleState = getLifecycleStateInstance(initialLifecycleState, initialLifecycleState); - this.lifecycleStateDAO.addLifecycleState(lifecycleState, applicationReleaseDTO.getId(), tenantId); - applicationReleaseEntities.add(applicationReleaseDTO); + List applicationReleaseEntities = new ArrayList<>(); + if (applicationReleaseDTO != null) { + String initialLifecycleState = lifecycleStateManager.getInitialState(); + applicationReleaseDTO.setCurrentState(initialLifecycleState); + applicationReleaseDTO = this.applicationReleaseDAO + .createRelease(applicationReleaseDTO, appId, tenantId); + LifecycleState lifecycleState = getLifecycleStateInstance(initialLifecycleState, initialLifecycleState); + this.lifecycleStateDAO.addLifecycleState(lifecycleState, applicationReleaseDTO.getId(), tenantId); + applicationReleaseEntities.add(applicationReleaseDTO); + } + applicationDTO.setId(appId); applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); - Application application = APIUtil.appDtoToAppResponse(applicationDTO); - ConnectionManagerUtil.commitDBTransaction(); - return application; + return APIUtil.appDtoToAppResponse(applicationDTO); } } catch (LifeCycleManagementDAOException e) { - ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred while adding lifecycle state. application name: " + applicationDTO.getName() + "."; log.error(msg, e); try { - applicationStorageManager.deleteAllApplicationReleaseArtifacts( + APIUtil.getApplicationStorageManager().deleteAllApplicationReleaseArtifacts( Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); } catch (ApplicationStorageManagementException ex) { String errorLog = @@ -968,73 +1073,59 @@ ApplicationManagerImpl implements ApplicationManager { } throw new ApplicationManagementException(msg, e); } catch (ApplicationManagementDAOException e) { - ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred while adding application or application release. application name: " + applicationDTO.getName() + "."; log.error(msg, e); deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); throw new ApplicationManagementException(msg, e); } catch (LifecycleManagementException e) { - ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred when getting initial lifecycle state. application name: " + applicationDTO.getName() + "."; log.error(msg, e); deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); throw new ApplicationManagementException(msg, e); - } catch (DBConnectionException e) { - String msg = "Error occurred while getting database connection."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); } catch (VisibilityManagementDAOException e) { - ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred while adding unrestricted roles. application name: " + applicationDTO.getName() + "."; log.error(msg, e); deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); throw new ApplicationManagementException(msg, e); - } catch (TransactionManagementException e) { - String msg = "Error occurred while disabling AutoCommit."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } finally { - ConnectionManagerUtil.closeDBConnection(); } } @Override - public ApplicationRelease createEntAppRelease(int applicationId, EntAppReleaseWrapper entAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + public ApplicationRelease createRelease(ApplicationDTO applicationDTO, ApplicationReleaseDTO applicationReleaseDTO, + ApplicationType type) + throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); if (log.isDebugEnabled()) { - log.debug("Application release creating request is received for the application id: " + applicationId); + log.debug("Application release creating request is received for the application id: " + applicationDTO.getId()); } - ApplicationDTO applicationDTO = getApplication(applicationId); - if (!ApplicationType.ENTERPRISE.toString().equals(applicationDTO.getType())) { - String msg = "It is possible to add new application release for " + ApplicationType.ENTERPRISE.toString() + if (!type.toString().equals(applicationDTO.getType())) { + String msg = "It is possible to add new application release for " + type + " app type. But you are requesting to add new application release for " + applicationDTO.getType() + " app type."; log.error(msg); throw new BadRequestException(msg); } - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - if (isInvalidOsVersionRange(entAppReleaseWrapper.getSupportedOsVersions(), deviceType.getName())) { - String msg = "You are trying to add application release which has invalid or unsupported OS versions in " - + "the supportedOsVersions section. Hence, please re-evaluate the request payload."; - log.error(msg); - throw new BadRequestException(msg); + + if (!type.equals(ApplicationType.ENTERPRISE)) { + int applicationReleaseCount = applicationDTO.getApplicationReleaseDTOs().size(); + if (applicationReleaseCount > 0) { + String msg = "Application type of " + applicationDTO.getType() + " can only have one release"; + log.error(msg); + throw new BadRequestException(msg); + } } - ApplicationReleaseDTO applicationReleaseDTO = uploadEntAppReleaseArtifacts( - APIUtil.releaseWrapperToReleaseDTO(entAppReleaseWrapper), applicationArtifact, deviceType.getName(), - tenantId, true); try { ConnectionManagerUtil.beginDBTransaction(); - String initialstate = lifecycleStateManager.getInitialState(); - applicationReleaseDTO.setCurrentState(initialstate); - LifecycleState lifecycleState = getLifecycleStateInstance(initialstate, initialstate); + String initialState = lifecycleStateManager.getInitialState(); + applicationReleaseDTO.setCurrentState(initialState); + LifecycleState lifecycleState = getLifecycleStateInstance(initialState, initialState); applicationReleaseDTO = this.applicationReleaseDAO .createRelease(applicationReleaseDTO, applicationDTO.getId(), tenantId); this.lifecycleStateDAO @@ -1044,23 +1135,23 @@ ApplicationManagerImpl implements ApplicationManager { return applicationRelease; } catch (TransactionManagementException e) { String msg = "Error occurred while staring application release creating transaction for application Id: " - + applicationId; + + applicationDTO.getId(); log.error(msg, e); throw new ApplicationManagementException(msg, e); } catch (DBConnectionException e) { String msg = "Error occurred while adding application release into IoTS app management ApplicationDTO id of" - + " the application release: " + applicationId; + + " the application release: " + applicationDTO.getId(); log.error(msg, e); throw new ApplicationManagementException(msg, e); } catch (LifeCycleManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred while adding new application release lifecycle state to the application" - + " release: " + applicationId; + + " release: " + applicationDTO.getId(); log.error(msg, e); throw new ApplicationManagementException(msg, e); } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Error occurred while adding new application release for application " + applicationId; + String msg = "Error occurred while adding new application release for application " + applicationDTO.getId(); log.error(msg, e); throw new ApplicationManagementException(msg, e); } finally { @@ -1075,7 +1166,8 @@ ApplicationManagerImpl implements ApplicationManager { * @return {@link ApplicationDTO} * @throws ApplicationManagementException if error occurred application data from the databse. */ - private ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException { + @Override + public ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { ConnectionManagerUtil.openDBConnection(); @@ -1112,7 +1204,7 @@ ApplicationManagerImpl implements ApplicationManager { * @throws ApplicationManagementException if error occurred while uploading artifacts into file system. */ private ApplicationReleaseDTO uploadEntAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, - ApplicationArtifact applicationArtifact, String deviceTypeName, int tenantId, boolean isNewRelease) + ApplicationArtifact applicationArtifact, String deviceTypeName, int tenantId, boolean isNewRelease) throws ApplicationManagementException { try { ApplicationReleaseDTO applicationReleaseDTO = addApplicationReleaseArtifacts(deviceTypeName, releaseDTO, @@ -1460,6 +1552,7 @@ ApplicationManagerImpl implements ApplicationManager { this.applicationDAO.deleteApplicationTags(applicationDTO.getId(), tenantId); this.applicationDAO.deleteAppCategories(applicationDTO.getId(), tenantId); this.visibilityDAO.deleteAppUnrestrictedRoles(applicationDTO.getId(), tenantId); + this.spApplicationDAO.deleteApplicationFromServiceProviders(applicationDTO.getId(), tenantId); this.applicationDAO.deleteApplication(applicationDTO.getId(), tenantId); APIUtil.getApplicationStorageManager().deleteAllApplicationReleaseArtifacts(deletingAppHashVals, tenantId); ConnectionManagerUtil.commitDBTransaction(); @@ -1683,7 +1776,7 @@ ApplicationManagerImpl implements ApplicationManager { @Override public void updateApplicationArtifact(String deviceType, String releaseUuid, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + ApplicationArtifact applicationArtifact) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); boolean isValidDeviceType = false; List deviceTypes; @@ -1749,7 +1842,7 @@ ApplicationManagerImpl implements ApplicationManager { throw new ApplicationManagementException(msg, e); } catch (TransactionManagementException e) { String msg = "Error occured while starting the transaction to update application release artifact which has " - + "application uuid " + releaseUuid + "."; + + "application uuid " + releaseUuid + "."; log.error(msg, e); throw new ApplicationManagementException(msg, e); } catch (DBConnectionException e) { @@ -1787,7 +1880,7 @@ ApplicationManagerImpl implements ApplicationManager { return this.lifecycleStateDAO.getLifecycleStates(applicationReleaseDTO.getId(), tenantId); } catch (DBConnectionException e) { String msg = "Error occurred while obtaining the database connection to get lifecycle state change flow for " - + "application release which has UUID: " + releaseUuid; + + "application release which has UUID: " + releaseUuid; log.error(msg, e); throw new ApplicationManagementException(msg, e); } catch (LifeCycleManagementDAOException e) { @@ -2068,8 +2161,8 @@ ApplicationManagerImpl implements ApplicationManager { if (!getDifference(updatingAppCategries, allCategoryName).isEmpty()){ String msg = "Application update request contains invalid category names. Hence please verify the " + "request payload"; - log.error(msg); - throw new BadRequestException(msg); + log.error(msg); + throw new BadRequestException(msg); } List addingAppCategories = getDifference(updatingAppCategries, appCategories); @@ -2672,7 +2765,7 @@ ApplicationManagerImpl implements ApplicationManager { @Override public ApplicationRelease updateEntAppRelease(String releaseUuid, EntAppReleaseWrapper entAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + ApplicationArtifact applicationArtifact) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { @@ -2749,7 +2842,7 @@ ApplicationManagerImpl implements ApplicationManager { @Override public ApplicationRelease updatePubAppRelease(String releaseUuid, PublicAppReleaseWrapper publicAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + ApplicationArtifact applicationArtifact) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { @@ -2818,7 +2911,7 @@ ApplicationManagerImpl implements ApplicationManager { @Override public ApplicationRelease updateWebAppRelease(String releaseUuid, WebAppReleaseWrapper webAppReleaseWrapper, - ApplicationArtifact applicationArtifact) throws ApplicationManagementException { + ApplicationArtifact applicationArtifact) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { @@ -2883,7 +2976,7 @@ ApplicationManagerImpl implements ApplicationManager { @Override public ApplicationRelease updateCustomAppRelease(String releaseUuid, - CustomAppReleaseWrapper customAppReleaseWrapper, ApplicationArtifact applicationArtifact) + CustomAppReleaseWrapper customAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); @@ -3017,7 +3110,7 @@ ApplicationManagerImpl implements ApplicationManager { * @throws ApplicationManagementException if invalid application release updating payload received. */ private void validateAppReleaseUpdating(T param, ApplicationDTO applicationDTO, - ApplicationArtifact applicationArtifact, String appType) + ApplicationArtifact applicationArtifact, String appType) throws ApplicationManagementException { if (applicationDTO == null) { String msg = "Couldn't found an application for requested UUID."; @@ -3094,8 +3187,9 @@ ApplicationManagerImpl implements ApplicationManager { } } + @Override - public void validateAppCreatingRequest(T param) throws ApplicationManagementException { + public void validateAppCreatingRequest(T param, boolean isReleaseRequired) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); int deviceTypeId = -1; @@ -3133,7 +3227,7 @@ ApplicationManagerImpl implements ApplicationManager { List entAppReleaseWrappers; entAppReleaseWrappers = applicationWrapper.getEntAppReleaseWrappers(); - if (entAppReleaseWrappers == null || entAppReleaseWrappers.size() != 1) { + if (isReleaseRequired && entAppReleaseWrappers.size() != 1) { String msg = "Invalid application creating request. Application creating request must have single " + "application release. Application name:" + applicationWrapper.getName() + "."; log.error(msg); @@ -3171,7 +3265,7 @@ ApplicationManagerImpl implements ApplicationManager { List webAppReleaseWrappers; webAppReleaseWrappers = webAppWrapper.getWebAppReleaseWrappers(); - if (webAppReleaseWrappers == null || webAppReleaseWrappers.size() != 1) { + if (isReleaseRequired && webAppReleaseWrappers.size() != 1) { String msg = "Invalid web clip creating request. Web clip creating request must have single " + "web clip release. Web clip name:" + webAppWrapper.getName() + "."; log.error(msg); @@ -3208,7 +3302,7 @@ ApplicationManagerImpl implements ApplicationManager { List publicAppReleaseWrappers; publicAppReleaseWrappers = publicAppWrapper.getPublicAppReleaseWrappers(); - if (publicAppReleaseWrappers == null || publicAppReleaseWrappers.size() != 1) { + if (isReleaseRequired && publicAppReleaseWrappers.size() != 1) { String msg = "Invalid public app creating request. Request must have single release. Application name:" + publicAppWrapper.getName() + "."; log.error(msg); @@ -3245,7 +3339,7 @@ ApplicationManagerImpl implements ApplicationManager { List customAppReleaseWrappers; customAppReleaseWrappers = customAppWrapper.getCustomAppReleaseWrappers(); - if (customAppReleaseWrappers == null || customAppReleaseWrappers.size() != 1) { + if (isReleaseRequired && customAppReleaseWrappers.size() != 1) { String msg = "Invalid custom app creating request. Application creating request must have single " + "application release. Application name:" + customAppWrapper.getName() + "."; log.error(msg); @@ -3424,9 +3518,34 @@ ApplicationManagerImpl implements ApplicationManager { } } + @Override + public void validateImageArtifacts(Base64File iconFile, List screenshots) + throws RequestValidatingException { + if (iconFile == null) { + String msg = "Icon file is not found with the application release creating request."; + log.error(msg); + throw new RequestValidatingException(msg); + } + if (screenshots == null || screenshots.isEmpty()) { + String msg = "Screenshots are not found with the application release creating request."; + log.error(msg); + throw new RequestValidatingException(msg); + } + } + + @Override + public void validateBase64File(Base64File file) throws RequestValidatingException { + if (StringUtils.isEmpty(file.getBase64String())) { + throw new RequestValidatingException("Base64File in the payload doesn't contain base64 string"); + } + if (StringUtils.isEmpty(file.getName())) { + throw new RequestValidatingException("Base64File in the payload doesn't contain file name"); + } + } + @Override public void validateImageArtifacts(Attachment iconFile, Attachment bannerFile, - List attachmentList) throws RequestValidatingException { + List attachmentList) throws RequestValidatingException { if (iconFile == null) { String msg = "Icon file is not found with the application release creating request."; log.error(msg); @@ -3439,6 +3558,16 @@ ApplicationManagerImpl implements ApplicationManager { } } + @Override + public void validateBinaryArtifact(Base64File binaryFile) throws RequestValidatingException { + if (binaryFile == null) { + String msg = "Binary file is not found with the application release creating request for ENTERPRISE app " + + "creating request."; + log.error(msg); + throw new RequestValidatingException(msg); + } + } + @Override public void validateBinaryArtifact(Attachment binaryFile) throws RequestValidatingException { if (binaryFile == null) { @@ -3515,18 +3644,18 @@ ApplicationManagerImpl implements ApplicationManager { String artifactDownloadURL = APIUtil.getArtifactDownloadBaseURL() + tenantId + Constants.FORWARD_SLASH + applicationReleaseDTO.getUuid() + Constants.FORWARD_SLASH + Constants.APP_ARTIFACT + Constants.FORWARD_SLASH + - applicationReleaseDTO.getInstallerName(); + applicationReleaseDTO.getInstallerName(); String plistContent = "<!DOCTYPE plist PUBLIC "-//Apple//DTDPLIST1.0//EN" "" + - "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="" + - "1.0"><dict><key>items</key><array><dict><" + - "key>assets</key><array><dict><key>kind</key><" + - "string>software-package</string><key>url</key><string>" + - "$downloadURL</string></dict></array><key>metadata<" + - "/key><dict><key>bundle-identifier</key><string>" + - "$packageName</string><key>bundle-version</key><string>" + - "$bundleVersion</string><key>kind</key><string>" + - "software</string><key>title</key><string>$appName<" + - "/string></dict></dict></array></dict></plist>"; + "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="" + + "1.0"><dict><key>items</key><array><dict><" + + "key>assets</key><array><dict><key>kind</key><" + + "string>software-package</string><key>url</key><string>" + + "$downloadURL</string></dict></array><key>metadata<" + + "/key><dict><key>bundle-identifier</key><string>" + + "$packageName</string><key>bundle-version</key><string>" + + "$bundleVersion</string><key>kind</key><string>" + + "software</string><key>title</key><string>$appName<" + + "/string></dict></dict></array></dict></plist>"; plistContent = plistContent.replace("$downloadURL", artifactDownloadURL) .replace("$packageName", applicationReleaseDTO.getPackageName()) .replace("$bundleVersion", applicationReleaseDTO.getVersion()) diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java new file mode 100644 index 00000000000..447487e0d47 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -0,0 +1,347 @@ +package io.entgra.application.mgt.core.impl; + +import io.entgra.application.mgt.common.ApplicationArtifact; +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.IdentityServerList; +import io.entgra.application.mgt.common.SPApplication; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.application.mgt.common.exception.DBConnectionException; +import io.entgra.application.mgt.common.exception.RequestValidatingException; +import io.entgra.application.mgt.common.exception.TransactionManagementException; +import io.entgra.application.mgt.common.response.Application; +import io.entgra.application.mgt.common.services.ApplicationManager; +import io.entgra.application.mgt.common.services.SPApplicationManager; +import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; +import io.entgra.application.mgt.common.wrapper.CustomAppReleaseWrapper; +import io.entgra.application.mgt.common.wrapper.CustomAppWrapper; +import io.entgra.application.mgt.common.wrapper.EntAppReleaseWrapper; +import io.entgra.application.mgt.common.wrapper.PublicAppReleaseWrapper; +import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; +import io.entgra.application.mgt.common.wrapper.WebAppReleaseWrapper; +import io.entgra.application.mgt.common.wrapper.WebAppWrapper; +import io.entgra.application.mgt.core.dao.ApplicationDAO; +import io.entgra.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.application.mgt.core.dao.VisibilityDAO; +import io.entgra.application.mgt.core.dao.common.ApplicationManagementDAOFactory; +import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException; +import io.entgra.application.mgt.core.exception.BadRequestException; +import io.entgra.application.mgt.core.internal.DataHolder; +import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager; +import io.entgra.application.mgt.core.util.APIUtil; +import io.entgra.application.mgt.core.util.ApplicationManagementUtil; +import io.entgra.application.mgt.core.util.ConnectionManagerUtil; +import io.entgra.application.mgt.core.util.Constants; +import io.entgra.application.mgt.core.util.SPApplicationManagementUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.util.ArrayList; +import java.util.List; + +public class SPApplicationManagerImpl implements SPApplicationManager { + + private static final Log log = LogFactory.getLog(SPApplicationManagerImpl.class); + private ApplicationDAO applicationDAO; + private SPApplicationDAO spApplicationDAO; + private VisibilityDAO visibilityDAO; + private final LifecycleStateManager lifecycleStateManager; + + public SPApplicationManagerImpl() { + initDataAccessObjects(); + lifecycleStateManager = DataHolder.getInstance().getLifecycleStateManager(); + } + + private void initDataAccessObjects() { + this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); + this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO(); + this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO(); + } + + public void addExistingApps(int identityServerId, List applications) throws ApplicationManagementException { + for (SPApplication application : applications) { + List existingApplications = getSPApplications(identityServerId, application.getId()); + application.setExistingApplications(existingApplications); + } + } + + @Override + public IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + ConnectionManagerUtil.openDBConnection(); + return spApplicationDAO.getIdentityServerById(identityServerId, tenantId); + } catch (DBConnectionException e) { + String msg = "Error occurred when getting database connection to get identity server with the id: " + identityServerId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = + "DAO exception while getting identity server with the id " + identityServerId ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public IdentityServerList getIdentityServers() throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + ConnectionManagerUtil.openDBConnection(); + IdentityServerList identityServerList = new IdentityServerList(); + identityServerList.setIdentityServers(spApplicationDAO.getIdentityServers(tenantId)); + return identityServerList; + } catch (DBConnectionException e) { + String msg = "Error occurred when getting database connection to get identity servers"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = + "DAO exception while getting identity servers"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public List getSPApplications(int identityServerId, String spUID) throws + ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + List applications = new ArrayList<>(); + + try { + ConnectionManagerUtil.openDBConnection(); + List appDTOs = spApplicationDAO.getSPApplications(identityServerId, spUID, tenantId); + for (ApplicationDTO applicationDTO : appDTOs) { + if (lifecycleStateManager.getEndState().equals(applicationDTO.getStatus())) { + continue; + } + boolean isHideableApp = applicationManager.isHideableApp(applicationDTO.getApplicationReleaseDTOs()); + boolean isDeletableApp = applicationManager.isDeletableApp(applicationDTO.getApplicationReleaseDTOs()); + + //Set application categories, tags and unrestricted roles to the application DTO. + applicationDTO + .setUnrestrictedRoles(visibilityDAO.getUnrestrictedRoles(applicationDTO.getId(), tenantId)); + applicationDTO.setAppCategories(applicationDAO.getAppCategories(applicationDTO.getId(), tenantId)); + applicationDTO.setTags(applicationDAO.getAppTags(applicationDTO.getId(), tenantId)); + + applicationDTO.setApplicationReleaseDTOs(applicationDTO.getApplicationReleaseDTOs()); + Application application = APIUtil.appDtoToAppResponse(applicationDTO); + application.setDeletableApp(isDeletableApp); + application.setHideableApp(isHideableApp); + applications.add(application); + } + + return applications; + } catch (DBConnectionException e) { + String msg = "Error occurred when getting database connection to get applications by filtering from " + + "requested filter."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + String msg = + "DAO exception while getting applications of tenant " + tenantId ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + public void validateAttachAppsRequest(int identityServerId, List appIds) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + for (int appId : appIds) { + try { + ApplicationDTO appDTO = applicationDAO.getApplication(appId, tenantId); + if (appDTO == null) { + String msg = "Payload contains invalid an app id. " + "No app exist with the appId: " + appId + "."; + throw new BadRequestException(msg); + } + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while trying to retrieve application with the id:" + appId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + public void validateDetachAppsRequest(int identityServerId, String spId, List appIds) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + try { + ConnectionManagerUtil.openDBConnection(); + for (int id : appIds) { + try { + boolean isSPAppExist = spApplicationDAO.isSPApplicationExist(identityServerId, spId, id, tenantId); + if (!isSPAppExist) { + String msg = "No service provider app exist with the appId: " + id + " for service provider with the " + + "UID " + spId; + throw new ApplicationManagementException(msg); + } + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while checking if application exists with the id:" + id; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + public void attachSPApplications(int identityServerId, String spUID, List appIds) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + ConnectionManagerUtil.beginDBTransaction(); + for (int appId : appIds) { + spApplicationDAO.attachSPApplication(identityServerId, spUID, appId, tenantId); + } + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e){ + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = + "DAO exception while getting applications of tenant " + tenantId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + + public void detachSPApplications(int identityServerId, String spUID, List appIds) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + ConnectionManagerUtil.beginDBTransaction(); + for (int id : appIds) { + spApplicationDAO.detachSPApplication(identityServerId, spUID, id, tenantId); + } + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e){ + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = + "DAO exception while getting applications of tenant " + tenantId; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException, + RequestValidatingException { + ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); + applicationManager.validateAppCreatingRequest(app, false); + ApplicationDTO applicationDTO = constructApplicationDTO(app); + try { + ConnectionManagerUtil.beginDBTransaction(); + Application createdApp = createSPApplication(applicationDTO); + attachCreatedSPApplication(createdApp, identityServerId, spId); + ConnectionManagerUtil.commitDBTransaction(); + return createdApp; + } catch (DBConnectionException e) { + String msg = "Error occurred while getting database connection."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while disabling AutoCommit."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while creating and attaching application with the name " + applicationDTO.getName() ; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + private ApplicationDTO constructApplicationDTO(T app) throws ApplicationManagementException, + RequestValidatingException { + if (ApplicationManagementUtil.isReleaseAvailable(app)) { + return uploadReleaseArtifactAndConstructApplicationDTO(app); + } + return APIUtil.convertToAppDTO(app); + } + + public Application createSPApplication(ApplicationDTO applicationDTO) throws ApplicationManagementException { + if (log.isDebugEnabled()) { + log.debug("Application release create request is received. Application name: " + applicationDTO.getName() + + " Device type ID: " + applicationDTO.getDeviceTypeId()); + } + ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); + return applicationManager.executeApplicationPersistenceTransaction(applicationDTO); + } + + + + public void attachCreatedSPApplication(Application createdApp, int identityServerId, String spUID) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + spApplicationDAO.attachSPApplication(identityServerId, spUID, createdApp.getId(), tenantId); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while attaching application with the id " + createdApp.getId(); + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + + public ApplicationDTO uploadReleaseArtifactAndConstructApplicationDTO(T app) throws ApplicationManagementException, + RequestValidatingException { + ApplicationArtifact artifact; + ApplicationDTO applicationDTO; + ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); + if (app instanceof ApplicationWrapper) { + ApplicationWrapper wrapper = (ApplicationWrapper) app; + EntAppReleaseWrapper releaseWrapper = wrapper.getEntAppReleaseWrappers().get(0); + applicationManager.validateReleaseCreatingRequest(releaseWrapper, wrapper.getDeviceType()); + applicationManager.validateBinaryArtifact(releaseWrapper.getBinaryFile()); + applicationManager.validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), null); + applicationDTO = applicationManager.uploadEntAppReleaseArtifacts(wrapper, artifact); + } else if (app instanceof PublicAppWrapper) { + PublicAppWrapper wrapper = (PublicAppWrapper) app; + PublicAppReleaseWrapper releaseWrapper = wrapper.getPublicAppReleaseWrappers().get(0); + applicationManager.validateReleaseCreatingRequest(releaseWrapper, wrapper.getDeviceType()); + applicationManager.validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), null, null); + applicationDTO = applicationManager.uploadPublicAppReleaseArtifacts(wrapper, artifact); + } else if (app instanceof WebAppWrapper) { + WebAppWrapper wrapper = (WebAppWrapper) app; + WebAppReleaseWrapper releaseWrapper = wrapper.getWebAppReleaseWrappers().get(0); + applicationManager.validateReleaseCreatingRequest(releaseWrapper, Constants.ANY); + applicationManager.validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), null, null); + applicationDTO = applicationManager.uploadWebAppReleaseArtifacts(wrapper, artifact); + } else if (app instanceof CustomAppWrapper) { + CustomAppWrapper wrapper = (CustomAppWrapper) app; + CustomAppReleaseWrapper releaseWrapper = wrapper.getCustomAppReleaseWrappers().get(0); + applicationManager.validateReleaseCreatingRequest(releaseWrapper, wrapper.getDeviceType()); + applicationManager.validateBinaryArtifact(releaseWrapper.getBinaryFile()); + applicationManager.validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), null); + applicationDTO = applicationManager.uploadCustomAppReleaseArtifactsAndConstructAppDTO(wrapper, artifact); + } else { + String msg = "Invalid payload found with the request. Hence verify the request payload object."; + log.error(msg); + throw new ApplicationManagementException(msg); + } + return applicationDTO; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/internal/ApplicationManagementServiceComponent.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/internal/ApplicationManagementServiceComponent.java index e56f73e1cb8..be8cd12d460 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/internal/ApplicationManagementServiceComponent.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/internal/ApplicationManagementServiceComponent.java @@ -17,6 +17,7 @@ */ package io.entgra.application.mgt.core.internal; +import io.entgra.application.mgt.common.services.SPApplicationManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; @@ -88,6 +89,10 @@ public class ApplicationManagementServiceComponent { DataHolder.getInstance().setLifecycleStateManger(lifecycleStateManager); bundleContext.registerService(LifecycleStateManager.class.getName(), lifecycleStateManager, null); + SPApplicationManager SPApplicationManager = ApplicationManagementUtil.getSPApplicationManagerInstance(); + DataHolder.getInstance().setISApplicationManager(SPApplicationManager); + bundleContext.registerService(SPApplicationManager.class.getName(), SPApplicationManager, null); + ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); applicationManager .addApplicationCategories(ConfigurationManager.getInstance().getConfiguration().getAppCategories()); diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/internal/DataHolder.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/internal/DataHolder.java index 3c675db85a7..f7bc6e1d8c1 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/internal/DataHolder.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/internal/DataHolder.java @@ -20,6 +20,7 @@ package io.entgra.application.mgt.core.internal; import io.entgra.application.mgt.common.services.ApplicationManager; import io.entgra.application.mgt.common.services.ApplicationStorageManager; import io.entgra.application.mgt.common.services.AppmDataHandler; +import io.entgra.application.mgt.common.services.SPApplicationManager; import io.entgra.application.mgt.common.services.ReviewManager; import io.entgra.application.mgt.common.services.SubscriptionManager; import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager; @@ -36,6 +37,8 @@ public class DataHolder { private RealmService realmService; + private SPApplicationManager SPApplicationManager; + private ApplicationManager applicationManager; private ReviewManager reviewManager; @@ -131,4 +134,12 @@ public class DataHolder { public void setTaskService(TaskService taskService) { this.taskService = taskService; } + + public SPApplicationManager getISApplicationManager() { + return SPApplicationManager; + } + + public void setISApplicationManager(SPApplicationManager SPApplicationManager) { + this.SPApplicationManager = SPApplicationManager; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java index 0afcc85ab50..cb4eb7edffc 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java @@ -59,12 +59,31 @@ public class APIUtil { private static Log log = LogFactory.getLog(APIUtil.class); + private static volatile SPApplicationManager SPApplicationManager; private static volatile ApplicationManager applicationManager; private static volatile ApplicationStorageManager applicationStorageManager; private static volatile SubscriptionManager subscriptionManager; private static volatile ReviewManager reviewManager; private static volatile AppmDataHandler appmDataHandler; + public static SPApplicationManager getSPApplicationManager() { + if (SPApplicationManager == null) { + synchronized (APIUtil.class) { + if (SPApplicationManager == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + SPApplicationManager = + (SPApplicationManager) ctx.getOSGiService(SPApplicationManager.class, null); + if (SPApplicationManager == null) { + String msg = "ApplicationDTO Manager service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + } + } + return SPApplicationManager; + } + public static ApplicationManager getApplicationManager() { if (applicationManager == null) { synchronized (APIUtil.class) { @@ -231,6 +250,7 @@ public class APIUtil { public static ApplicationDTO convertToAppDTO(T param) throws BadRequestException, UnexpectedServerErrorException { ApplicationDTO applicationDTO = new ApplicationDTO(); + List applicationReleaseEntities; if (param instanceof ApplicationWrapper){ ApplicationWrapper applicationWrapper = (ApplicationWrapper) param; @@ -244,7 +264,7 @@ public class APIUtil { applicationDTO.setTags(applicationWrapper.getTags()); applicationDTO.setUnrestrictedRoles(applicationWrapper.getUnrestrictedRoles()); applicationDTO.setDeviceTypeId(deviceType.getId()); - List applicationReleaseEntities = applicationWrapper.getEntAppReleaseWrappers() + applicationReleaseEntities = applicationWrapper.getEntAppReleaseWrappers() .stream().map(APIUtil::releaseWrapperToReleaseDTO).collect(Collectors.toList()); applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); } else if (param instanceof WebAppWrapper){ @@ -257,7 +277,7 @@ public class APIUtil { applicationDTO.setType(webAppWrapper.getType()); applicationDTO.setTags(webAppWrapper.getTags()); applicationDTO.setUnrestrictedRoles(webAppWrapper.getUnrestrictedRoles()); - List applicationReleaseEntities = webAppWrapper.getWebAppReleaseWrappers() + applicationReleaseEntities = webAppWrapper.getWebAppReleaseWrappers() .stream().map(APIUtil::releaseWrapperToReleaseDTO).collect(Collectors.toList()); applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); } else if (param instanceof PublicAppWrapper) { @@ -272,7 +292,7 @@ public class APIUtil { applicationDTO.setTags(publicAppWrapper.getTags()); applicationDTO.setUnrestrictedRoles(publicAppWrapper.getUnrestrictedRoles()); applicationDTO.setDeviceTypeId(deviceType.getId()); - List applicationReleaseEntities = publicAppWrapper.getPublicAppReleaseWrappers() + applicationReleaseEntities = publicAppWrapper.getPublicAppReleaseWrappers() .stream().map(APIUtil::releaseWrapperToReleaseDTO).collect(Collectors.toList()); applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); } else if (param instanceof CustomAppWrapper){ @@ -287,7 +307,7 @@ public class APIUtil { applicationDTO.setTags(customAppWrapper.getTags()); applicationDTO.setUnrestrictedRoles(customAppWrapper.getUnrestrictedRoles()); applicationDTO.setDeviceTypeId(deviceType.getId()); - List applicationReleaseEntities = customAppWrapper.getCustomAppReleaseWrappers() + applicationReleaseEntities = customAppWrapper.getCustomAppReleaseWrappers() .stream().map(APIUtil::releaseWrapperToReleaseDTO).collect(Collectors.toList()); applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); } @@ -362,7 +382,9 @@ public class APIUtil { application.setTags(applicationDTO.getTags()); application.setUnrestrictedRoles(applicationDTO.getUnrestrictedRoles()); application.setRating(applicationDTO.getAppRating()); - application.setInstallerName(applicationDTO.getApplicationReleaseDTOs().get(0).getInstallerName()); + if (applicationDTO.getApplicationReleaseDTOs() != null && !applicationDTO.getApplicationReleaseDTOs().isEmpty()) { + application.setInstallerName(applicationDTO.getApplicationReleaseDTOs().get(0).getInstallerName()); + } List applicationReleases = new ArrayList<>(); if (ApplicationType.PUBLIC.toString().equals(applicationDTO.getType()) && application.getCategories() .contains("GooglePlaySyncedApp")) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java index 11d8adb2ce4..ad5cabf8a40 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java @@ -17,6 +17,23 @@ */ package io.entgra.application.mgt.core.util; +import io.entgra.application.mgt.common.ApplicationArtifact; +import io.entgra.application.mgt.common.ApplicationSubscriptionType; +import io.entgra.application.mgt.common.ApplicationType; +import io.entgra.application.mgt.common.Base64File; +import io.entgra.application.mgt.common.FileDataHolder; +import io.entgra.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.application.mgt.common.exception.RequestValidatingException; +import io.entgra.application.mgt.common.services.SPApplicationManager; +import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; +import io.entgra.application.mgt.common.wrapper.CustomAppReleaseWrapper; +import io.entgra.application.mgt.common.wrapper.CustomAppWrapper; +import io.entgra.application.mgt.common.wrapper.EntAppReleaseWrapper; +import io.entgra.application.mgt.common.wrapper.PublicAppReleaseWrapper; +import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; +import io.entgra.application.mgt.common.wrapper.WebAppReleaseWrapper; +import io.entgra.application.mgt.common.wrapper.WebAppWrapper; +import io.entgra.application.mgt.core.exception.BadRequestException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.application.mgt.common.exception.InvalidConfigurationException; @@ -27,8 +44,16 @@ import io.entgra.application.mgt.common.services.SubscriptionManager; import io.entgra.application.mgt.core.config.ConfigurationManager; import io.entgra.application.mgt.core.config.Extension; import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager; +import org.wso2.carbon.device.mgt.core.common.util.FileUtil; +import java.io.ByteArrayInputStream; +import java.io.InputStream; import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; /** * This DAOUtil class is responsible for making sure single instance of each Extension Manager is used throughout for @@ -38,6 +63,77 @@ public class ApplicationManagementUtil { private static Log log = LogFactory.getLog(ApplicationManagementUtil.class); + public static ApplicationArtifact constructApplicationArtifact(Base64File iconBase64, List screenshotsBase64, + Base64File binaryFileBase64, Base64File bannerFileBase64) + throws BadRequestException { + ApplicationArtifact applicationArtifact = new ApplicationArtifact(); + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + if (binaryFileBase64 != null) { + try { + applicationManager.validateBase64File(binaryFileBase64); + } catch (RequestValidatingException e) { + String msg = "Invalid base64 binary file payload found"; + log.error(msg, e); + throw new BadRequestException(msg, e); + } + FileDataHolder binaryFile = base64FileToFileDataHolder(binaryFileBase64); + applicationArtifact.setInstallerName(binaryFile.getName()); + applicationArtifact.setInstallerStream(binaryFile.getFile()); + } + if (iconBase64 != null) { + try { + applicationManager.validateBase64File(iconBase64); + } catch (RequestValidatingException e) { + String msg = "Invalid base64 icon file payload found"; + log.error(msg, e); + throw new BadRequestException(msg, e); + } + FileDataHolder iconFile = base64FileToFileDataHolder(iconBase64); + applicationArtifact.setIconName(iconFile.getName()); + applicationArtifact.setIconStream(iconFile.getFile()); + } + if (bannerFileBase64 != null) { + try { + applicationManager.validateBase64File(bannerFileBase64); + } catch (RequestValidatingException e) { + String msg = "Invalid base64 banner file payload found"; + log.error(msg, e); + throw new BadRequestException(msg, e); + } + FileDataHolder bannerFile = base64FileToFileDataHolder(bannerFileBase64); + applicationArtifact.setBannerName(bannerFile.getName()); + applicationArtifact.setBannerStream(bannerFile.getFile()); + } + + if (screenshotsBase64 != null) { + Map screenshotData = new TreeMap<>(); + for (Base64File screenshot : screenshotsBase64) { + try { + applicationManager.validateBase64File(screenshot); + } catch (RequestValidatingException e) { + String msg = "Invalid base64 screenshot file payload found"; + log.error(msg, e); + throw new BadRequestException(msg, e); + } + FileDataHolder screenshotFile = base64FileToFileDataHolder(screenshot); + screenshotData.put(screenshotFile.getName(), screenshotFile.getFile()); + } + applicationArtifact.setScreenshots(screenshotData); + } + return applicationArtifact; + } + + public static FileDataHolder base64FileToFileDataHolder(Base64File base64File) { + InputStream stream = FileUtil.base64ToInputStream(base64File.getBase64String()); + return new FileDataHolder(base64File.getName(), stream); + } + + public static SPApplicationManager getSPApplicationManagerInstance() throws InvalidConfigurationException { + ConfigurationManager configurationManager = ConfigurationManager.getInstance(); + Extension extension = configurationManager.getExtension(Extension.Name.SPApplicationManager); + return getInstance(extension, SPApplicationManager.class); + } + public static ApplicationManager getApplicationManagerInstance() throws InvalidConfigurationException { ConfigurationManager configurationManager = ConfigurationManager.getInstance(); Extension extension = configurationManager.getExtension(Extension.Name.ApplicationManager); @@ -69,7 +165,27 @@ public class ApplicationManagementUtil { return getInstance(extension, LifecycleStateManager.class); } - private static T getInstance(Extension extension, Class cls) throws InvalidConfigurationException { + public static boolean isReleaseAvailable(T appWrapper) { + if (appWrapper instanceof ApplicationWrapper) { + List entAppReleaseWrappers = ((ApplicationWrapper) appWrapper).getEntAppReleaseWrappers(); + return entAppReleaseWrappers != null && !entAppReleaseWrappers.isEmpty(); + } + if (appWrapper instanceof PublicAppWrapper) { + List publicAppReleaseWrappers = ((PublicAppWrapper) appWrapper).getPublicAppReleaseWrappers(); + return publicAppReleaseWrappers != null && !publicAppReleaseWrappers.isEmpty(); + } + if (appWrapper instanceof WebAppWrapper) { + List webAppReleaseWrappers = ((WebAppWrapper) appWrapper).getWebAppReleaseWrappers(); + return webAppReleaseWrappers != null && !webAppReleaseWrappers.isEmpty(); + } + if (appWrapper instanceof CustomAppWrapper) { + List customAppReleaseWrappers = ((CustomAppWrapper) appWrapper).getCustomAppReleaseWrappers(); + return customAppReleaseWrappers != null && !((CustomAppWrapper) appWrapper).getCustomAppReleaseWrappers().isEmpty(); + } + throw new IllegalArgumentException("Provided bean does not belong to an Application Wrapper"); + } + + public static T getInstance(Extension extension, Class cls) throws InvalidConfigurationException { try { Class theClass = Class.forName(extension.getClassName()); if (extension.getParameters() != null && extension.getParameters().size() > 0) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java index 3302ddd25d8..03f94ef1d0f 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java @@ -35,6 +35,8 @@ public class Constants { public static final String DEFAULT_CONFIG_FILE_LOCATION = CarbonUtils.getCarbonConfigDirPath() + File.separator + Constants.APPLICATION_CONFIG_XML_FILE; public static final String DEFAULT_VERSION = "1.0.0"; + public static final String SCREENSHOT_NAME = "screenshot"; + public static final String ICON_NAME = "icon"; public static final String PAYLOAD = "Payload"; public static final String PLIST_NAME = "Info.plist"; public static final String CF_BUNDLE_VERSION = "CFBundleVersion"; @@ -45,6 +47,15 @@ public class Constants { public static final String HTTPS_PROTOCOL = "https"; public static final String HTTP_PROTOCOL = "http"; + public static final String LIMIT_QUERY_PARAM = "limit"; + public static final String OFFSET_QUERY_PARAM = "offset"; + public static final String IS_APPS_API_CONTEXT_PATH = "identity-server-applications"; + public static final String IS_APPS_API_BASE_PATH = "identity-server-applications"; + public static final Double IS_APP_DEFAULT_PRICE = 0.0; + public static final String SP_APP_CATEGORY = "SPApp"; + public static final String IS_APP_RELEASE_TYPE = "stable"; + public static final String IS_APP_DEFAULT_PAYMENT_CURRENCY = "$"; + public static final String IS_APP_DEFAULT_VERSION = "1.0"; public static final String FORWARD_SLASH = "/"; public static final String ANY = "ANY"; public static final String DEFAULT_PCK_NAME = "default.app.com"; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java index 6acfa182a1d..dc276ddf257 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java @@ -19,6 +19,7 @@ package io.entgra.application.mgt.core.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; +import io.entgra.application.mgt.common.IdentityServer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; @@ -38,10 +39,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; import java.util.ArrayList; -import java.util.Date; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -86,10 +84,16 @@ public class DAOUtil { application.setAppRating(rs.getDouble("APP_RATING")); application.setDeviceTypeId(rs.getInt("APP_DEVICE_TYPE_ID")); application.setPackageName(rs.getString("PACKAGE_NAME")); - application.getApplicationReleaseDTOs().add(constructAppReleaseDTO(rs)); + ApplicationReleaseDTO releaseDTO = constructAppReleaseDTO(rs); + if (releaseDTO != null) { + application.getApplicationReleaseDTOs().add(constructAppReleaseDTO(rs)); + } } else { if (application != null && application.getApplicationReleaseDTOs() != null) { - application.getApplicationReleaseDTOs().add(constructAppReleaseDTO(rs)); + ApplicationReleaseDTO releaseDTO = constructAppReleaseDTO(rs); + if (releaseDTO != null) { + application.getApplicationReleaseDTOs().add(constructAppReleaseDTO(rs)); + } } } hasNext = rs.next(); @@ -139,26 +143,76 @@ public class DAOUtil { */ public static ApplicationReleaseDTO constructAppReleaseDTO(ResultSet rs) throws SQLException { ApplicationReleaseDTO appRelease = new ApplicationReleaseDTO(); - appRelease.setId(rs.getInt("RELEASE_ID")); - appRelease.setDescription(rs.getString("RELEASE_DESCRIPTION")); - appRelease.setUuid(rs.getString("RELEASE_UUID")); - appRelease.setReleaseType(rs.getString("RELEASE_TYPE")); - appRelease.setVersion(rs.getString("RELEASE_VERSION")); - appRelease.setInstallerName(rs.getString("AP_RELEASE_STORED_LOC")); - appRelease.setIconName(rs.getString("AP_RELEASE_ICON_LOC")); - appRelease.setBannerName(rs.getString("AP_RELEASE_BANNER_LOC")); - appRelease.setScreenshotName1(rs.getString("AP_RELEASE_SC1")); - appRelease.setScreenshotName2(rs.getString("AP_RELEASE_SC2")); - appRelease.setScreenshotName3(rs.getString("AP_RELEASE_SC3")); - appRelease.setAppHashValue(rs.getString("RELEASE_HASH_VALUE")); - appRelease.setPrice(rs.getDouble("RELEASE_PRICE")); - appRelease.setMetaData(rs.getString("RELEASE_META_INFO")); - appRelease.setPackageName(rs.getString("PACKAGE_NAME")); - appRelease.setSupportedOsVersions(rs.getString("RELEASE_SUP_OS_VERSIONS")); - appRelease.setRating(rs.getDouble("RELEASE_RATING")); - appRelease.setCurrentState(rs.getString("RELEASE_CURRENT_STATE")); - appRelease.setRatedUsers(rs.getInt("RATED_USER_COUNT")); - return appRelease; + if (rs.getString("RELEASE_UUID") != null) { + appRelease.setId(rs.getInt("RELEASE_ID")); + appRelease.setDescription(rs.getString("RELEASE_DESCRIPTION")); + appRelease.setUuid(rs.getString("RELEASE_UUID")); + appRelease.setReleaseType(rs.getString("RELEASE_TYPE")); + appRelease.setVersion(rs.getString("RELEASE_VERSION")); + appRelease.setInstallerName(rs.getString("AP_RELEASE_STORED_LOC")); + appRelease.setIconName(rs.getString("AP_RELEASE_ICON_LOC")); + appRelease.setBannerName(rs.getString("AP_RELEASE_BANNER_LOC")); + appRelease.setScreenshotName1(rs.getString("AP_RELEASE_SC1")); + appRelease.setScreenshotName2(rs.getString("AP_RELEASE_SC2")); + appRelease.setScreenshotName3(rs.getString("AP_RELEASE_SC3")); + appRelease.setAppHashValue(rs.getString("RELEASE_HASH_VALUE")); + appRelease.setPrice(rs.getDouble("RELEASE_PRICE")); + appRelease.setMetaData(rs.getString("RELEASE_META_INFO")); + appRelease.setPackageName(rs.getString("PACKAGE_NAME")); + appRelease.setSupportedOsVersions(rs.getString("RELEASE_SUP_OS_VERSIONS")); + appRelease.setRating(rs.getDouble("RELEASE_RATING")); + appRelease.setCurrentState(rs.getString("RELEASE_CURRENT_STATE")); + appRelease.setRatedUsers(rs.getInt("RATED_USER_COUNT")); + return appRelease; + } + return null; + } + + /** + * To create application object from the result set retrieved from the Database. + * + * @param rs ResultSet + * @return IdentityServer that is retrieved from the Database. + * @throws SQLException SQL Exception + * @throws JSONException JSONException. + */ + public static IdentityServer loadIdentityServer(ResultSet rs) + throws SQLException, JSONException, UnexpectedServerErrorException { + List identityServers = loadIdentityServers(rs); + if (identityServers.isEmpty()) { + return null; + } + if (identityServers.size() > 1) { + String msg = "Internal server error. Found more than one identity server for requested ID"; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return identityServers.get(0); + } + + /** + * To create application object from the result set retrieved from the Database. + * + * @param rs ResultSet + * @return List of Applications that is retrieved from the Database. + * @throws SQLException SQL Exception + * @throws JSONException JSONException. + */ + public static List loadIdentityServers(ResultSet rs) throws SQLException, JSONException { + List identityServers = new ArrayList<>(); + while (rs.next()) { + IdentityServer identityServer = new IdentityServer(); + identityServer.setId(rs.getInt("ID")); + identityServer.setName(rs.getString("NAME")); + identityServer.setDescription(rs.getString("DESCRIPTION")); + identityServer.setUrl(rs.getString("URL")); + identityServer.setSpAppsURI(rs.getString("SP_APPS_URI")); + identityServer.setSpAppsApi(rs.getString("SP_APPS_API")); + identityServer.setUserName(rs.getString("USERNAME")); + identityServer.setPassword(rs.getString("PASSWORD")); + identityServers.add(identityServer); + } + return identityServers; } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/SPApplicationManagementUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/SPApplicationManagementUtil.java new file mode 100644 index 00000000000..53c11fd6f31 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/SPApplicationManagementUtil.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. 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 io.entgra.application.mgt.core.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import java.util.ArrayList; +import java.util.List; + +/** + * This DAOUtil class is responsible for making sure single instance of each Extension Manager is used throughout for + * all the tasks. + */ +public class SPApplicationManagementUtil { + + private static Log log = LogFactory.getLog(SPApplicationManagementUtil.class); + + private static List getDefaultSPAppCategories() { + List categories = new ArrayList<>(); + categories.add(Constants.SP_APP_CATEGORY); + return categories; + } + + +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java index 998e10e5b13..c781b674df9 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java @@ -41,7 +41,6 @@ import io.entgra.application.mgt.core.dto.ApplicationsDTO; import io.entgra.application.mgt.core.impl.ApplicationManagerImpl; import io.entgra.application.mgt.core.internal.DataHolder; import io.entgra.application.mgt.core.util.ConnectionManagerUtil; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; @@ -123,7 +122,8 @@ public class ApplicationManagementTest extends BaseTestCase { applicationArtifact.setScreenshots(screenshots); ApplicationManager manager = new ApplicationManagerImpl(); - manager.createEntApp(applicationWrapper, applicationArtifact); + ApplicationDTO applicationDTO = manager.uploadEntAppReleaseArtifacts(applicationWrapper, applicationArtifact); + manager.persistApplication(applicationDTO); } @DataProvider(name = "applicationIdDataProvider") diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java index 1cd1411da34..905f140de75 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java @@ -624,6 +624,228 @@ public interface ApplicationManagementPublisherAPI { @Multipart(value = "screenshot3") Attachment screenshot3 ); + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Path("/{deviceType}/public-app/{appId}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Create an application", + notes = "This will create a new public application release", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "OK. \n Successfully created an application.", + response = ApplicationRelease.class), + @ApiResponse( + code = 400, + message = "Bad Request. \n " + + "ApplicationDTO creating payload contains unacceptable or vulnerable data"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while creating the application.", + response = ErrorResponse.class) + }) + Response createPubAppRelease( + @ApiParam( + name = "deviceType", + value = "Device type that application is compatible with.", + required = true) + @PathParam("deviceType") String deviceType, + @ApiParam( + name = "appId", + value = "Id of the application.", + required = true) + @PathParam("appId") int appId, + @ApiParam( + name = "applicationRelease", + value = "The application release that need to be created.", + required = true) + @Multipart("applicationRelease") PublicAppReleaseWrapper publicAppReleaseWrapper, + @ApiParam( + name = "icon", + value = "Icon of the uploading application", + required = true) + @Multipart(value = "icon") Attachment iconFile, + @ApiParam( + name = "banner", + value = "Banner of the uploading application") + @Multipart(value = "banner") Attachment bannerFile, + @ApiParam( + name = "screenshot1", + value = "Screen Shots of the uploading application", + required = true) + @Multipart(value = "screenshot1") Attachment screenshot1, + @ApiParam( + name = "screenshot2", + value = "Screen Shots of the uploading application", + required = false) + @Multipart(value = "screenshot2") Attachment screenshot2, + @ApiParam( + name = "screenshot3", + value = "Screen Shots of the uploading application", + required = false) + @Multipart(value = "screenshot3") Attachment screenshot3 + ); + + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Path("/web-app/{appId}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Create an application", + notes = "This will create a new web application release", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "OK. \n Successfully created an application.", + response = ApplicationRelease.class), + @ApiResponse( + code = 400, + message = "Bad Request. \n " + + "ApplicationDTO creating payload contains unacceptable or vulnerable data"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while creating the application.", + response = ErrorResponse.class) + }) + Response createWebAppRelease( + @ApiParam( + name = "appId", + value = "Id of the application.", + required = true) + @PathParam("appId") int appId, + @ApiParam( + name = "applicationRelease", + value = "The application release that need to be created.", + required = true) + @Multipart("applicationRelease") WebAppReleaseWrapper webAppReleaseWrapper, + @ApiParam( + name = "icon", + value = "Icon of the uploading application", + required = true) + @Multipart(value = "icon") Attachment iconFile, + @ApiParam( + name = "banner", + value = "Banner of the uploading application") + @Multipart(value = "banner") Attachment bannerFile, + @ApiParam( + name = "screenshot1", + value = "Screen Shots of the uploading application", + required = true) + @Multipart(value = "screenshot1") Attachment screenshot1, + @ApiParam( + name = "screenshot2", + value = "Screen Shots of the uploading application", + required = false) + @Multipart(value = "screenshot2") Attachment screenshot2, + @ApiParam( + name = "screenshot3", + value = "Screen Shots of the uploading application", + required = false) + @Multipart(value = "screenshot3") Attachment screenshot3 + ); + + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Path("/{deviceType}/custom-app/{appId}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Create an application", + notes = "This will create a new custom application release", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "OK. \n Successfully created an application.", + response = ApplicationRelease.class), + @ApiResponse( + code = 400, + message = "Bad Request. \n " + + "ApplicationDTO creating payload contains unacceptable or vulnerable data"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while creating the application.", + response = ErrorResponse.class) + }) + Response createCustomAppRelease( + @ApiParam( + name = "deviceType", + value = "Device type that application is compatible with.", + required = true) + @PathParam("deviceType") String deviceType, + @ApiParam( + name = "appId", + value = "Id of the application.", + required = true) + @PathParam("appId") int appId, + @ApiParam( + name = "applicationRelease", + value = "The application release that need to be created.", + required = true) + @Multipart("applicationRelease") CustomAppReleaseWrapper customAppReleaseWrapper, + @ApiParam( + name = "binaryFile", + value = "Binary file of uploading application", + required = true) + @Multipart(value = "binaryFile") Attachment binaryFile, + @ApiParam( + name = "icon", + value = "Icon of the uploading application", + required = true) + @Multipart(value = "icon") Attachment iconFile, + @ApiParam( + name = "banner", + value = "Banner of the uploading application") + @Multipart(value = "banner") Attachment bannerFile, + @ApiParam( + name = "screenshot1", + value = "Screen Shots of the uploading application", + required = true) + @Multipart(value = "screenshot1") Attachment screenshot1, + @ApiParam( + name = "screenshot2", + value = "Screen Shots of the uploading application", + required = false) + @Multipart(value = "screenshot2") Attachment screenshot2, + @ApiParam( + name = "screenshot3", + value = "Screen Shots of the uploading application", + required = false) + @Multipart(value = "screenshot3") Attachment screenshot3 + ); + @PUT @Path("/image-artifacts/{uuid}") @Produces(MediaType.APPLICATION_JSON) diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java new file mode 100644 index 00000000000..c39c9b8ea79 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java @@ -0,0 +1,280 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.publisher.api.services; + +import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; +import io.entgra.application.mgt.common.wrapper.CustomAppWrapper; +import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; +import io.entgra.application.mgt.common.wrapper.WebAppWrapper; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.Info; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; +import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.Scopes; + +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.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * This is the application registration service that exposed for apimApplicationRegistration + */ + +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "Service Provider Application Management Publisher Service", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "SPApplicationService"), + @ExtensionProperty(name = "context", value = "/api/application-mgt-publisher/v1.0/identity-server-applications"), + }) + } + ), + tags = { + @Tag(name = "application_management, device_management", description = "App publisher related APIs") + } +) +@Scopes( + scopes = { + @Scope( + name = "view a service provider applications", + description = "Get application details", + key = "perm:app:publisher:service-provider:view", + roles = {"Internal/devicemgt-user"}, + permissions = {"/app-mgt/publisher/service-provider/application/view"} + ), + @Scope( + name = "Create a service provider application", + description = "Update an application", + key = "perm:app:publisher:service-provider:create", + roles = {"Internal/devicemgt-user"}, + permissions = {"/app-mgt/publisher/service-provider/application/create"} + ), + @Scope( + name = "Attach a service provider application", + description = "Update an application", + key = "perm:app:publisher:service-provider:attach", + roles = {"Internal/devicemgt-user"}, + permissions = {"/app-mgt/publisher/service-provider/application/attach"} + ), + @Scope( + name = "Detach a service provider application", + description = "Update an application", + key = "perm:app:publisher:service-provider:detach", + roles = {"Internal/devicemgt-user"}, + permissions = {"/app-mgt/publisher/service-provider/application/detach"} + ) + } +) +@Path("/identity-server-applications") +@Api(value = "SPApplication Management") +@Produces(MediaType.APPLICATION_JSON) +public interface SPApplicationService { + + String SCOPE = "scope"; + + /** + * This method is used to register an APIM application for tenant domain. + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/identity-servers") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") + }) + } + ) + Response getIdentityServers(); + + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/identity-servers/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") + }) + } + ) + Response getIdentityServer(@PathParam("id") int id); + + /** + * This method is used to register an APIM application for tenant domain. + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("{identity-server-id}/service-providers") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") + }) + } + ) + Response getServiceProviders(@QueryParam("limit") Integer limit, @QueryParam("offset") Integer offset, + @PathParam("identity-server-id") int identityServerId); + + @Path("/{identity-server-id}/{service-provider-id}/attach") + @POST + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:attach") + }) + } + ) + Response attachApps(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, List appIds); + + /** + * This method is used to register an APIM application for tenant domain. + */ + @Path("/{identity-server-id}/{service-provider-id}/detach") + @POST + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:detach") + }) + } + ) + Response detachApps(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, List appIds); + + /** + * This method is used to register an APIM application for tenant domain. + */ + @Path("/{identity-server-id}/{service-provider-id}/create/ent-app") + @POST + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:create") + }) + } + ) + Response createEntApp(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, ApplicationWrapper app); + + + /** + * This method is used to register an APIM application for tenant domain. + */ + @Path("/{identity-server-id}/{service-provider-id}/create/public-app") + @POST + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:create") + }) + } + ) + Response createPubApp(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, PublicAppWrapper app); + + @Path("/{identity-server-id}/{service-provider-id}/create/web-app") + @POST + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:create") + }) + } + ) + Response createWebApp(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, WebAppWrapper app); + + @Path("/{identity-server-id}/{service-provider-id}/create/custom-app") + @POST + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "get the application of requesting application id and state", + notes = "This will get the application identified by the application id and state, if exists", + tags = "ApplicationDTO Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:create") + }) + } + ) + Response createCustomApp(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, CustomAppWrapper app); +} diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java index 8b156bbf9d0..9aaeeb1d5a7 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java @@ -16,6 +16,9 @@ */ package io.entgra.application.mgt.publisher.api.services.impl; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.dto.ApplicationReleaseDTO; +import io.entgra.application.mgt.common.exception.ResourceManagementException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.cxf.jaxrs.ext.multipart.Attachment; @@ -47,6 +50,7 @@ import io.entgra.application.mgt.publisher.api.services.ApplicationManagementPub import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.services.ApplicationManager; import io.entgra.application.mgt.core.exception.NotFoundException; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import java.io.IOException; import java.io.InputStream; @@ -182,15 +186,16 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem ApplicationManager applicationManager = APIUtil.getApplicationManager(); List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { - applicationManager.validateAppCreatingRequest(applicationWrapper); + applicationManager.validateAppCreatingRequest(applicationWrapper, true); applicationManager.validateReleaseCreatingRequest(applicationWrapper.getEntAppReleaseWrappers().get(0), applicationWrapper.getDeviceType()); applicationManager.validateBinaryArtifact(binaryFile); applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); // Created new Ent App - Application application = applicationManager.createEntApp(applicationWrapper, + ApplicationDTO applicationDTO = applicationManager.uploadEntAppReleaseArtifacts(applicationWrapper, constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList)); + Application application = applicationManager.persistApplication(applicationDTO); if (application != null) { return Response.status(Response.Status.CREATED).entity(application).build(); } else { @@ -226,14 +231,15 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem ApplicationManager applicationManager = APIUtil.getApplicationManager(); List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { - applicationManager.validateAppCreatingRequest(webAppWrapper); + applicationManager.validateAppCreatingRequest(webAppWrapper, true); applicationManager .validateReleaseCreatingRequest(webAppWrapper.getWebAppReleaseWrappers().get(0), Constants.ANY); applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); // Created new Web App - Application application = applicationManager.createWebClip(webAppWrapper, + ApplicationDTO applicationDTO = applicationManager.uploadWebAppReleaseArtifacts(webAppWrapper, constructApplicationArtifact(null, iconFile, bannerFile, attachmentList)); + Application application = applicationManager.persistApplication(applicationDTO); if (application != null) { return Response.status(Response.Status.CREATED).entity(application).build(); } else { @@ -269,14 +275,15 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem ApplicationManager applicationManager = APIUtil.getApplicationManager(); List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { - applicationManager.validateAppCreatingRequest(publicAppWrapper); + applicationManager.validateAppCreatingRequest(publicAppWrapper, true); applicationManager.validateReleaseCreatingRequest(publicAppWrapper.getPublicAppReleaseWrappers().get(0), publicAppWrapper.getDeviceType()); applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); // Created new Public App - Application application = applicationManager.createPublicApp(publicAppWrapper, + ApplicationDTO applicationDTO = applicationManager.uploadPublicAppReleaseArtifacts(publicAppWrapper, constructApplicationArtifact(null, iconFile, bannerFile, attachmentList)); + Application application = applicationManager.persistApplication(applicationDTO); if (application != null) { return Response.status(Response.Status.CREATED).entity(application).build(); } else { @@ -313,15 +320,16 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem ApplicationManager applicationManager = APIUtil.getApplicationManager(); List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { - applicationManager.validateAppCreatingRequest(customAppWrapper); + applicationManager.validateAppCreatingRequest(customAppWrapper, true); applicationManager.validateReleaseCreatingRequest(customAppWrapper.getCustomAppReleaseWrappers().get(0), customAppWrapper.getDeviceType()); applicationManager.validateBinaryArtifact(binaryFile); applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); // Created new Custom App - Application application = applicationManager.createCustomApp(customAppWrapper, + ApplicationDTO applicationDTO = applicationManager.uploadCustomAppReleaseArtifactsAndConstructAppDTO(customAppWrapper, constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList)); + Application application = applicationManager.persistApplication(applicationDTO); if (application != null) { return Response.status(Response.Status.CREATED).entity(application).build(); } else { @@ -348,7 +356,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) @Path("/{deviceType}/ent-app/{appId}") public Response createEntAppRelease( - @PathParam("deviceType") String deviceType, + @PathParam("deviceType") String deviceTypeName, @PathParam("appId") int appId, @Multipart("applicationRelease") EntAppReleaseWrapper entAppReleaseWrapper, @Multipart("binaryFile") Attachment binaryFile, @@ -357,34 +365,131 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Multipart("screenshot1") Attachment screenshot1, @Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot3") Attachment screenshot3) { - ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { - applicationManager.validateReleaseCreatingRequest(entAppReleaseWrapper, deviceType); + ApplicationManager applicationManager = APIUtil.getApplicationManager(); applicationManager.validateBinaryArtifact(binaryFile); - applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); - - // Created new Ent App release - ApplicationRelease release = applicationManager.createEntAppRelease(appId, entAppReleaseWrapper, - constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList)); - if (release != null) { - return Response.status(Response.Status.CREATED).entity(release).build(); - } else { - log.error("ApplicationDTO Creation Failed"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - } catch (BadRequestException e) { - String msg = "Found incompatible payload with enterprise app release creating request."; + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); + ApplicationArtifact artifact = constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList); + ApplicationReleaseDTO applicationReleaseDTO = applicationManager.uploadEntAppReleaseArtifacts( + entAppReleaseWrapper, artifact, deviceType.getName()); + ApplicationRelease release = applicationManager.createRelease(applicationDTO, applicationReleaseDTO, ApplicationType.ENTERPRISE); + return Response.status(Response.Status.CREATED).entity(release).build(); + } catch (RequestValidatingException e) { + String msg = "Error occurred while validating binaryArtifact"; log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { - String msg = "Error occurred while creating the application"; + String msg = "Error occurred while creating application release for the application with the id " + appId; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @POST + @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Path("/{deviceType}/public-app/{appId}") + @Override + public Response createPubAppRelease( + @PathParam("deviceType") String deviceTypeName, + @PathParam("appId") int appId, + @Multipart("applicationRelease") PublicAppReleaseWrapper publicAppReleaseWrapper, + @Multipart("icon") Attachment iconFile, + @Multipart(value = "banner", required = false) Attachment bannerFile, + @Multipart("screenshot1") Attachment screenshot1, + @Multipart("screenshot2") Attachment screenshot2, + @Multipart("screenshot3") Attachment screenshot3) { + + try { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); + ApplicationArtifact artifact = constructApplicationArtifact(null, iconFile, bannerFile, attachmentList); + ApplicationReleaseDTO applicationReleaseDTO = applicationManager.uploadPubAppReleaseArtifacts( + publicAppReleaseWrapper, artifact, deviceType.getName()); + ApplicationRelease release = applicationManager.createRelease(applicationDTO, applicationReleaseDTO, ApplicationType.PUBLIC); + return Response.status(Response.Status.CREATED).entity(release).build(); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating application release for the application with the id " + appId; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (ResourceManagementException e) { + String msg = "Error occurred while uploading application release artifacts"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @POST + @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Path("/web-app/{appId}") + @Override + public Response createWebAppRelease( + @PathParam("appId") int appId, + @Multipart("applicationRelease") WebAppReleaseWrapper webAppReleaseWrapper, + @Multipart("icon") Attachment iconFile, + @Multipart(value = "banner", required = false) Attachment bannerFile, + @Multipart("screenshot1") Attachment screenshot1, + @Multipart("screenshot2") Attachment screenshot2, + @Multipart("screenshot3") Attachment screenshot3) { + try { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); + ApplicationArtifact artifact = constructApplicationArtifact(null, iconFile, bannerFile, attachmentList); + ApplicationReleaseDTO applicationReleaseDTO = applicationManager.uploadWebAppReleaseArtifacts(webAppReleaseWrapper, artifact); + ApplicationRelease release = applicationManager.createRelease(applicationDTO, applicationReleaseDTO, ApplicationType.WEB_CLIP); + return Response.status(Response.Status.CREATED).entity(release).build(); + } catch (ResourceManagementException e) { + String msg = "Error occurred while uploading application release artifacts"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating application release for the application with the id " + appId; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + @POST + @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Path("/{deviceType}/custom-app/{appId}") + @Override + public Response createCustomAppRelease( + @PathParam("deviceType") String deviceTypeName, + @PathParam("appId") int appId, + @Multipart("applicationRelease") CustomAppReleaseWrapper customAppReleaseWrapper, + @Multipart("binaryFile") Attachment binaryFile, + @Multipart("icon") Attachment iconFile, + @Multipart(value = "banner", required = false) Attachment bannerFile, + @Multipart("screenshot1") Attachment screenshot1, + @Multipart("screenshot2") Attachment screenshot2, + @Multipart("screenshot3") Attachment screenshot3) { + try { + APIUtil.getApplicationManager().validateBinaryArtifact(binaryFile); + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); + ApplicationArtifact artifact = constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList); + ApplicationReleaseDTO applicationReleaseDTO = applicationManager.uploadCustomAppReleaseArtifacts( + customAppReleaseWrapper, artifact, deviceType.getName()); + ApplicationRelease release = applicationManager.createRelease(applicationDTO, applicationReleaseDTO, ApplicationType.CUSTOM); + return Response.status(Response.Status.CREATED).entity(release).build(); } catch (RequestValidatingException e) { - String msg = "Error occurred while handling the application creating request"; + String msg = "Error occurred while validating binaryArtifact"; log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (ResourceManagementException e) { + String msg = "Error occurred while uploading application release artifacts"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating application release for the application with the id " + appId; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java new file mode 100644 index 00000000000..79a86655218 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.publisher.api.services.impl; + +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.IdentityServerList; +import io.entgra.application.mgt.common.SPApplicationListResponse; +import io.entgra.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.application.mgt.common.exception.RequestValidatingException; +import io.entgra.application.mgt.common.response.Application; +import io.entgra.application.mgt.common.services.SPApplicationManager; +import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; +import io.entgra.application.mgt.common.wrapper.CustomAppWrapper; +import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; +import io.entgra.application.mgt.common.wrapper.WebAppWrapper; +import io.entgra.application.mgt.core.exception.BadRequestException; +import io.entgra.application.mgt.core.util.APIUtil; +import io.entgra.application.mgt.publisher.api.services.SPApplicationService; +import io.entgra.application.mgt.publisher.api.services.util.SPAppRequestHandlerUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +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.util.List; + + +@Produces(MediaType.APPLICATION_JSON) +@Path("/identity-server-applications") +public class SPApplicationServiceImpl implements SPApplicationService { + private static final Log log = LogFactory.getLog(SPApplicationServiceImpl.class); + + @Path("/identity-servers") + @GET + @Override + public Response getIdentityServers() { + try { + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + IdentityServerList identityServers = spAppManager.getIdentityServers(); + return Response.status(Response.Status.OK).entity(identityServers).build(); + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; + log.error(errMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build(); + } + } + + @Path("/identity-servers/{id}") + @GET + @Override + public Response getIdentityServer(@PathParam("id") int id) { + try { + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + IdentityServer identityServer = spAppManager.getIdentityServer(id); + return Response.status(Response.Status.OK).entity(identityServer).build(); + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; + log.error(errMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build(); + } + } + + @Path("/{identity-server-id}/service-providers") + @GET + @Override + public Response getServiceProviders(@QueryParam("limit") Integer limit, @QueryParam("offset") Integer offset, + @PathParam("identity-server-id") int identityServerId) { + try { + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + SPApplicationListResponse applications = SPAppRequestHandlerUtil. + getServiceProvidersFromIdentityServer(identityServerId, limit, offset); + spAppManager.addExistingApps(identityServerId, applications.getApplications()); + return Response.status(Response.Status.OK).entity(applications).build(); + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; + log.error(errMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build(); + } + } + + @Path("/{identity-server-id}/{service-provider-id}/attach") + @POST + @Override + public Response attachApps(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, List appIds) { + SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); + try { + validateServiceProviderUID(identityServerId, serviceProviderId); + spApplicationManager.validateAttachAppsRequest(identityServerId, appIds); + spApplicationManager.attachSPApplications(identityServerId, serviceProviderId, appIds); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while attaching apps to service provider with the id" + serviceProviderId; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).build(); + } + + @Path("/{identity-server-id}/{service-provider-id}/detach") + @POST + @Override + public Response detachApps(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, List appIds) { + SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); + try { + validateServiceProviderUID(identityServerId, serviceProviderId); + spApplicationManager.validateDetachAppsRequest(identityServerId, serviceProviderId, appIds); + spApplicationManager.detachSPApplications(identityServerId, serviceProviderId, appIds); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while attaching apps to service provider with the id" + serviceProviderId; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return Response.status(Response.Status.OK).build(); + } + + @Path("/{identity-server-id}/{service-provider-id}/create/ent-app") + @POST + @Override + public Response createEntApp(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, ApplicationWrapper app) { + return createSPApplication(identityServerId, serviceProviderId, app); + } + + @Path("/{identity-server-id}/{service-provider-id}/create/public-app") + @POST + @Override + public Response createPubApp(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, PublicAppWrapper app) { + return createSPApplication(identityServerId, serviceProviderId, app); + } + + @Path("/{identity-server-id}/{service-provider-id}/create/web-app") + @POST + @Override + public Response createWebApp(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, WebAppWrapper app) { + return createSPApplication(identityServerId, serviceProviderId, app); + } + + @Path("/{identity-server-id}/{service-provider-id}/create/custom-app") + @POST + @Override + public Response createCustomApp(@PathParam("identity-server-id") int identityServerId, + @PathParam("service-provider-id") String serviceProviderId, CustomAppWrapper app) { + return createSPApplication(identityServerId, serviceProviderId, app); + } + + private Response createSPApplication(int identityServerId, String serviceProviderId, T appWrapper) { + try { + validateServiceProviderUID(identityServerId, serviceProviderId); + SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); + Application createdApp = spApplicationManager.createSPApplication(appWrapper, identityServerId, serviceProviderId); + return Response.status(Response.Status.CREATED).entity(createdApp).build(); + } catch (BadRequestException e) { + String msg = "Found incompatible payload with create service provider app request."; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (RequestValidatingException e) { + String msg = "Found invalid release payload with create service provider app request."; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + catch (ApplicationManagementException e) { + String msg = "Error occurred while creating service provider app"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + + private void validateServiceProviderUID(int identityServerId, String spUID) throws + ApplicationManagementException { + try { + boolean isSPAppExists = SPAppRequestHandlerUtil. + isSPApplicationExist(identityServerId, spUID); + if (!isSPAppExists) { + String errMsg = "Service provider with the uid " + spUID + " does not exist."; + log.error(errMsg); + throw new BadRequestException(errMsg); + } + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to validate service provider uid"; + log.error(errMsg, e); + throw new ApplicationManagementException(errMsg, e); + } + } + + +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java new file mode 100644 index 00000000000..307cb91342f --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java @@ -0,0 +1,137 @@ +package io.entgra.application.mgt.publisher.api.services.util; + +import com.google.gson.Gson; +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.SPApplication; +import io.entgra.application.mgt.common.SPApplicationListResponse; +import io.entgra.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.application.mgt.common.services.SPApplicationManager; +import io.entgra.application.mgt.core.util.APIUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.wso2.carbon.device.mgt.core.common.util.HttpUtil; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.UriBuilder; +import java.io.IOException; +import java.net.URI; + +public class SPAppRequestHandlerUtil { + + private static final Log log = LogFactory.getLog(SPAppRequestHandlerUtil.class); + + public static boolean isSPApplicationExist(int identityServerId, String spAppId) throws ApplicationManagementException { + SPApplication application = retrieveSPApplication(identityServerId, spAppId); + if (application == null) { + return false; + } + return true; + } + + public static SPApplicationListResponse getServiceProvidersFromIdentityServer(int identityServerId, Integer limit, Integer offSet) + throws ApplicationManagementException { + return retrieveSPApplications(identityServerId, limit, offSet); + } + + public static SPApplication retrieveSPApplication(int identityServerId, String spAppId) + throws ApplicationManagementException { + IdentityServer identityServer = getIdentityServer(identityServerId); + HttpGet req = new HttpGet(); + URI uri = HttpUtil.createURI(getSPApplicationsAPI(identityServer)); + uri = UriBuilder.fromUri(uri).path(spAppId).build(); + req.setURI(uri); + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpResponse response = invokeISAPI(identityServer, client, req); + String responseBody = HttpUtil.getResponseString(response); + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + return new Gson().fromJson(responseBody, + SPApplication.class); + } + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { + return null; + } + String msg = "Error occurred while calling SP Applications API"; + log.error(msg); + throw new ApplicationManagementException(msg); + } catch (IOException e) { + String msg = "Error occurred while calling SP Applications API"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + try { + client.close(); + } catch (IOException e) { + log.error("Error occurred while closing http connection"); + } + } + } + + + public static SPApplicationListResponse retrieveSPApplications(int identityServerId, Integer limit, Integer offset) + throws ApplicationManagementException { + IdentityServer identityServer = getIdentityServer(identityServerId); + HttpGet req = new HttpGet(); + URI uri = HttpUtil.createURI(getSPApplicationsAPI(identityServer)); + UriBuilder uriBuilder = UriBuilder.fromUri(uri); + if (limit != null) { + uriBuilder = uriBuilder.queryParam(io.entgra.application.mgt.core.util.Constants.LIMIT_QUERY_PARAM, limit); + } + if (offset != null) { + uriBuilder = uriBuilder.queryParam(io.entgra.application.mgt.core.util.Constants.OFFSET_QUERY_PARAM, offset); + } + uri = uriBuilder.build(); + req.setURI(uri); + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpResponse response = invokeISAPI(identityServer, client, req); + String responseBody = HttpUtil.getResponseString(response); + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + return new Gson().fromJson(responseBody, + SPApplicationListResponse.class); + } + String msg = "Error occurred while calling SP Applications API"; + log.error(msg); + throw new ApplicationManagementException(msg); + } catch (IOException e) { + String msg = "Error occurred while calling SP Applications API"; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + try { + client.close(); + } catch (IOException e) { + log.error("Error occurred while closing http connection"); + } + } + } + + public static IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException { + SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); + return spApplicationManager.getIdentityServer(identityServerId); + } + + public static HttpResponse invokeISAPI(IdentityServer identityServer, HttpClient client, HttpRequestBase request) throws IOException { + setBasicAuthHeader(identityServer, request); + return client.execute(request); + } + + public static void setBasicAuthHeader(IdentityServer identityServer, HttpRequestBase request) { + String basicAuthHeader = HttpUtil.getBasicAuthBase64Header(identityServer.getUserName(), + identityServer.getPassword()); + request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader); + } + + private static String getSPApplicationsAPI(IdentityServer identityServer) { + String api = identityServer.getSpAppsApi(); + return api; + } + +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 47dcef91e1b..da39cd93a8b 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -25,6 +25,7 @@ + @@ -54,6 +55,7 @@ + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java new file mode 100644 index 00000000000..2f9a7207b89 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java @@ -0,0 +1,10 @@ +package org.wso2.carbon.device.mgt.core.common; + +public class Constants { + public static final String SCHEME_SEPARATOR = "://"; + public static final String COLON = ":"; + public static final String URI_QUERY_SEPARATOR = "?"; + public static final String URI_SEPARATOR = "/"; + public static final String BASIC_AUTH_HEADER_PREFIX = "Basic "; + public static final String BEARER = "Bearer "; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java new file mode 100644 index 00000000000..28a5084003b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java @@ -0,0 +1,24 @@ +package org.wso2.carbon.device.mgt.core.common.util; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Base64; + +public class FileUtil { + + public static String removePathSeparatorFromBase64String(String base64String) { + String partSeparator = ","; + if (base64String.contains(partSeparator)) { + return base64String.split(partSeparator)[1]; + } + return base64String; + } + + public static InputStream base64ToInputStream(String base64) { + base64 = FileUtil.removePathSeparatorFromBase64String(base64); + byte[] base64Bytes = Base64.getDecoder().decode(base64); + return new ByteArrayInputStream(base64Bytes); + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java new file mode 100644 index 00000000000..130cd07c490 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. 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.wso2.carbon.device.mgt.core.common.util; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.entity.ContentType; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.device.mgt.core.common.Constants; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HttpUtil { + + public static URI createURI(String uriString) { + uriString = uriString.replace(" ", "%20"); + return URI.create(uriString); + } + + public static String getBasicAuthBase64Header(String userName, String password) { + return Constants.BASIC_AUTH_HEADER_PREFIX + getBase64Encode(userName, password); + } + + public static String getBase64Encode(String key, String value) { + return new String(Base64.encodeBase64((key + ":" + value).getBytes())); + } + + public static String getRequestSubPathFromEnd(URI requestUri, int position) { + if (requestUri.getPath() != null) { + String[] pathList = requestUri.getPath().split("/"); + if (pathList.length - 1 >= position) { + return pathList[pathList.length - 1 - position]; + } + } + return null; + } + + public static String getRequestSubPath(String fullPath, int position) { + String[] pathList = fullPath.split("/"); + if (pathList.length - 1 > position) { + String path = pathList[position + 1]; + if(path.contains(Constants.URI_QUERY_SEPARATOR)) { + path = path.substring(0, path.indexOf(Constants.URI_QUERY_SEPARATOR)); + } + return path; + } + return null; + } + + public static String getResponseString(HttpResponse response) throws IOException { + return EntityUtils.toString(response.getEntity()); + } + + public static boolean isQueryParamExist(String param, URI request) { + Map> queryMap = getQueryMap(request); + return queryMap.containsKey(param); + } + public static String getFirstQueryValue(String param, Map> queryMap) { + List valueList = queryMap.get(param); + String firstValue = null; + if(valueList != null) { + firstValue = valueList.get(0); + } + return firstValue; + } + public static Map> getQueryMap(String uri) { + String query = getQueryFromURIPath(uri); + Map> map = new HashMap<>(); + if (query != null) { + String[] params = query.split("&"); + for (String param : params) { + String[] paramArr = param.split("="); + if (paramArr.length == 2) { + String name = paramArr[0]; + String value = paramArr[1]; + if (!map.containsKey(name)) { + List valueList = new ArrayList<>(); + map.put(name, valueList); + } + map.get(name).add(value); + } + } + } + return map; + } + public static Map> getQueryMap(URI request) { + String query = request.getQuery(); + Map> map = new HashMap<>(); + if (query != null) { + String[] params = query.split("&"); + for (String param : params) { + String[] paramArr = param.split("="); + if (paramArr.length == 2) { + String name = paramArr[0]; + String value = paramArr[1]; + if (!map.containsKey(name)) { + List valueList = new ArrayList<>(); + map.put(name, valueList); + } + map.get(name).add(value); + } + } + } + return map; + } + public static String getQueryFromURIPath(String uri) { + String query = null; + if (uri.length() > "?".length() && uri.contains("?")) { + query = uri.substring(uri.lastIndexOf("?") + "?".length()); + } + if (StringUtils.isEmpty(query)) { + query = null; + } + return query; + } + + public static String getContentType(HttpResponse response) { + ContentType contentType = ContentType.getOrDefault(response.getEntity()); + return contentType.getMimeType(); + } +} diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml index fa4ce1eb53c..428fc0e1346 100644 --- a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf/application-mgt.xml @@ -22,6 +22,9 @@ jdbc/APPM_DS + + io.entgra.application.mgt.core.impl.SPApplicationManagerImpl + io.entgra.application.mgt.core.impl.ApplicationManagerImpl diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 index 21ce676f3f5..bd2cc9141cb 100644 --- a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/application-mgt.xml.j2 @@ -22,6 +22,13 @@ jdbc/APPM_DS + + {% if application_mgt_conf.extension.isapplication_manager is defined %} + {{application_mgt_conf.extension.isapplication_manager}} + {% else %} + io.entgra.application.mgt.core.impl.SPApplicationManagerImpl + {% endif %} + {% if application_mgt_conf.extension.application_manager is defined %} {{application_mgt_conf.extension.application_manager}} diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql index 110ccdc606d..8985d3637bf 100644 --- a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql @@ -274,4 +274,39 @@ CREATE TABLE IF NOT EXISTS AP_SCHEDULED_SUBSCRIPTION( SCHEDULED_TIMESTAMP TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, DELETED BOOLEAN, PRIMARY KEY (ID) -); \ No newline at end of file +); + +-- ----------------------------------------------------- +-- Table AP_IDENTITY_SERVER +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS AP_IDENTITY_SERVER +( + ID INT AUTO_INCREMENT + PRIMARY KEY, + NAME VARCHAR(255) NOT NULL, + DESCRIPTION VARCHAR(255) NOT NULL, + URL VARCHAR(255) NOT NULL, + SP_APPS_URI VARCHAR(255) NOT NULL, + SP_APPS_API VARCHAR(255) NULL, + TENANT_ID INT NOT NULL, + USERNAME VARCHAR(255) NOT NULL, + PASSWORD VARCHAR(255) NOT NULL +) + +-- ----------------------------------------------------- +-- Table AP_IS_SP_APP_MAPPING +-- -----------------------------------------------------; + CREATE TABLE IF NOT EXISTS AP_IS_SP_APP_MAPPING + ( + ID INT AUTO_INCREMENT + PRIMARY KEY, + SP_UID VARCHAR(255) NOT NULL, + AP_APP_ID INT NOT NULL, + IS_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + CONSTRAINT AP_IS_SP_APP_MAPPING_AP_APP_ID_fk + FOREIGN KEY (AP_APP_ID) REFERENCES AP_APP (ID), + CONSTRAINT AP_IS_SP_APP_MAPPING_AP_IDENTITY_SERVER_ID_fk + FOREIGN KEY (IS_ID) REFERENCES AP_IDENTITY_SERVER (ID) + ); + diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index 88d9b47d294..bc6be595996 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -36,6 +36,10 @@ perm:app:review:view perm:app:review:update + perm:app:publisher:service-provider:view + perm:app:publisher:service-provider:create + perm:app:publisher:service-provider:attach + perm:app:publisher:service-provider:detach perm:app:publisher:view perm:app:publisher:update perm:app:store:view diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/mdm-ui-config.xml.j2 b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/mdm-ui-config.xml.j2 index 077e55c9ed3..244e90ce97c 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/mdm-ui-config.xml.j2 +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf_templates/templates/repository/conf/mdm-ui-config.xml.j2 @@ -57,6 +57,10 @@ perm:app:review:view perm:app:review:update + perm:app:publisher:service-provider:view + perm:app:publisher:service-provider:create + perm:app:publisher:service-provider:attach + perm:app:publisher:service-provider:detach perm:app:publisher:view perm:app:publisher:update perm:app:store:view From 9cdc4389700c973bfd0b01f8e844809075f1d009 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Sat, 26 Feb 2022 22:18:09 +0530 Subject: [PATCH 02/13] Change to base64 string for file uploads instead of using multipart form data Make release optional when creating new application Fix screenshots not getting saved if duplicate screenshot file name found Delete artifacts if errors while adding release to db Improve service provider application related apis Refactor code --- .../application/mgt/common/Base64File.java | 18 + .../mgt/common/FileDataHolder.java | 18 + .../mgt/common/IdentityServer.java | 19 +- .../mgt/common/IdentityServerList.java | 18 + .../application/mgt/common/SPApplication.java | 18 + .../mgt/common/SPApplicationListResponse.java | 18 + .../common/services/ApplicationManager.java | 158 +++-- .../common/services/SPApplicationManager.java | 87 ++- .../wrapper/CustomAppReleaseWrapper.java | 12 + .../common/wrapper/EntAppReleaseWrapper.java | 12 + .../wrapper/PublicAppReleaseWrapper.java | 12 + .../common/wrapper/WebAppReleaseWrapper.java | 12 + .../mgt/core/dao/SPApplicationDAO.java | 71 ++- .../GenericApplicationDAOImpl.java | 3 - .../GenericSPApplicationDAOImpl.java | 30 +- .../OracleSPApplicationDAOImpl.java | 27 +- .../PostgreSQLSPApplicationDAOImpl.java | 27 +- .../SQLServerSPApplicationDAOImpl.java | 27 +- .../mgt/core/impl/ApplicationManagerImpl.java | 572 +++++++++--------- .../core/impl/SPApplicationManagerImpl.java | 112 +--- .../core/util/ApplicationManagementUtil.java | 53 +- .../application/mgt/core/util/DAOUtil.java | 3 +- .../util/SPApplicationManagementUtil.java | 40 -- .../management/ApplicationManagementTest.java | 3 +- .../ApplicationManagementPublisherAPI.java | 383 +----------- .../api/services/SPApplicationService.java | 86 ++- ...ApplicationManagementPublisherAPIImpl.java | 435 +++---------- .../impl/SPApplicationServiceImpl.java | 41 +- .../util/SPAppRequestHandlerUtil.java | 61 +- .../device/mgt/core/common/Constants.java | 18 + .../device/mgt/core/common/util/FileUtil.java | 60 ++ .../device/mgt/core/common/util/HttpUtil.java | 2 +- 32 files changed, 1182 insertions(+), 1274 deletions(-) delete mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/SPApplicationManagementUtil.java diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java index 51e9add3722..67ca3429f54 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.common; public class Base64File { diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java index 4bb36c6c640..ec59999afd1 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.common; import java.io.InputStream; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java index 4bc0ddee020..24a3cd7cf72 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java @@ -1,5 +1,22 @@ -package io.entgra.application.mgt.common; +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.common; public class IdentityServer { private int id; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java index 5f1deaacf18..a3944580000 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.common; import java.util.List; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java index 118576cfbf1..50d19aca631 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.common; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java index e638364bbde..576093944de 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.common; import java.util.List; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java index 75708c11058..e59021d1e4b 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java @@ -34,15 +34,10 @@ import io.entgra.application.mgt.common.response.ApplicationRelease; import io.entgra.application.mgt.common.response.Category; import io.entgra.application.mgt.common.response.Tag; import io.entgra.application.mgt.common.wrapper.CustomAppReleaseWrapper; -import io.entgra.application.mgt.common.wrapper.CustomAppWrapper; import io.entgra.application.mgt.common.wrapper.EntAppReleaseWrapper; import io.entgra.application.mgt.common.wrapper.ApplicationUpdateWrapper; -import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; import io.entgra.application.mgt.common.wrapper.PublicAppReleaseWrapper; -import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; import io.entgra.application.mgt.common.wrapper.WebAppReleaseWrapper; -import io.entgra.application.mgt.common.wrapper.WebAppWrapper; - import java.util.List; /** @@ -50,40 +45,64 @@ import java.util.List; */ public interface ApplicationManager { - - ApplicationReleaseDTO uploadEntAppReleaseArtifacts(EntAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, - String deviceType) throws ApplicationManagementException; - - /*** - * The method is responsible to add new application into entgra App Manager. + /** + * This method is responsible for handling application creation * - * @param applicationWrapper Application that need to be created. - * @param applicationArtifact contains artifact data. i.e image name and stream, icon name and stream etc. - * @return {@link Application} - * @throws ApplicationManagementException Catch all other throwing exceptions and throw {@link ApplicationManagementException} + * @param appId application id of the application to which the release should be created + * @param releaseWrapper {@link EntAppReleaseWrapper} of the release to be created + * @return Created application release bean + * @throws ApplicationManagementException if any error occurred while creating the application */ - ApplicationDTO uploadEntAppReleaseArtifacts(ApplicationWrapper applicationWrapper, ApplicationArtifact applicationArtifact) + ApplicationRelease createEntAppRelease(int appId, EntAppReleaseWrapper releaseWrapper) throws ApplicationManagementException; - ApplicationReleaseDTO uploadWebAppReleaseArtifacts(WebAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact) + /** + * This method is responsible for handling application creation + * + * @param appId application id of the application to which the release should be created + * @param releaseWrapper {@link WebAppReleaseWrapper} of the release to be created + * @return Created application release bean + * @throws ApplicationManagementException if any error occurred while creating the application + */ + ApplicationRelease createWebAppRelease(int appId, WebAppReleaseWrapper releaseWrapper) throws ApplicationManagementException, ResourceManagementException; - ApplicationDTO uploadWebAppReleaseArtifacts(WebAppWrapper webAppWrapper, ApplicationArtifact applicationArtifact) - throws ApplicationManagementException; - - ApplicationReleaseDTO uploadPubAppReleaseArtifacts(PublicAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, - String deviceType) throws ResourceManagementException; + /** + * This method is responsible for handling application creation + * + * @param appId application id of the application to which the release should be created + * @param releaseWrapper {@link PublicAppReleaseWrapper} of the release to be created + * @return Created application release bean + * @throws ApplicationManagementException if any error occurred while creating the application + */ + ApplicationRelease createPubAppRelease(int appId, PublicAppReleaseWrapper releaseWrapper) + throws ApplicationManagementException, ResourceManagementException; - ApplicationDTO uploadPublicAppReleaseArtifacts(PublicAppWrapper publicAppWrapper, ApplicationArtifact applicationArtifact) - throws ApplicationManagementException; + /** + * This method is responsible for handling application creation + * + * @param appId application id of the application to which the release should be created + * @param releaseWrapper {@link CustomAppReleaseWrapper} of the release to be created + * @return Created application release bean + * @throws ApplicationManagementException if any error occurred while creating the application + */ + ApplicationRelease createCustomAppRelease(int appId, CustomAppReleaseWrapper releaseWrapper) + throws ResourceManagementException, ApplicationManagementException; - ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(CustomAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, - String deviceType) throws ResourceManagementException, ApplicationManagementException; + /** + * Checks if release is available for a given application wrapper, and if exists it uploads + * the artifacts of the release + * + * @param app Application wrapper bean of the application + * @param Application Wrapper class + * @return constructed ApplicationDTO after uploading the release artifacts if exist + * @throws ApplicationManagementException if any error occurred while uploading release artifacts + */ + ApplicationDTO uploadReleaseArtifactIfExist(T app) throws ApplicationManagementException; - ApplicationDTO uploadCustomAppReleaseArtifactsAndConstructAppDTO(CustomAppWrapper customAppWrapper, ApplicationArtifact applicationArtifact) - throws ApplicationManagementException; + void validatePublicAppReleasePackageName(String packageName) throws ApplicationManagementException; - /*** + /** * This method is responsible to add application data into APPM database. However, before call this method it is * required to do the validation of request and check the existence of application releaseDTO. * @@ -91,12 +110,18 @@ public interface ApplicationManager { * @return {@link Application} * @throws ApplicationManagementException which throws if error occurs while during application management. */ - Application executeApplicationPersistenceTransaction(ApplicationDTO applicationDTO) throws + Application addAppDataIntoDB(ApplicationDTO applicationDTO) throws ApplicationManagementException; - - Application persistApplication(ApplicationDTO applicationDTO) throws ApplicationManagementException; - + /** + * This method is responsible for handling application creation + * + * @param app Application wrapper object which depends on the application type + * @param Application wrapper class which depends on the application type + * @return Created application bean + * @throws ApplicationManagementException if any error occurred while creating the application + */ + Application createApplication(T app) throws ApplicationManagementException; /** * Check the existence of an application for given application name and the device type. @@ -109,7 +134,6 @@ public interface ApplicationManager { */ boolean isExistingAppName(String appName, String deviceTypeName) throws ApplicationManagementException; - /** * Updates an already existing application. * @@ -145,6 +169,8 @@ public interface ApplicationManager { */ void deleteApplicationRelease(String releaseUuid) throws ApplicationManagementException; + void deleteApplicationArtifacts(List directoryPaths) throws ApplicationManagementException; + /** * To get the applications based on the search filter. * @@ -154,9 +180,21 @@ public interface ApplicationManager { */ ApplicationList getApplications(Filter filter) throws ApplicationManagementException; + /** + * + * @param applicationReleaseDTOs application releases of the application + * @return if application is hide-able + * @throws ApplicationManagementException if any error occurred while checking if hide-able + */ boolean isHideableApp(List applicationReleaseDTOs) throws ApplicationManagementException; + /** + * + * @param applicationReleaseDTOs application releases of the application + * @return if application is deletable + * @throws ApplicationManagementException if any error occurred while checking if deletable + */ boolean isDeletableApp(List applicationReleaseDTOs) throws ApplicationManagementException; @@ -170,7 +208,6 @@ public interface ApplicationManager { */ List getApplications(List packageNames) throws ApplicationManagementException; - /** * To create an application release for an ApplicationDTO. * @@ -244,7 +281,6 @@ public interface ApplicationManager { void updateApplicationImageArtifact(String uuid, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - /** * To update release images. * @@ -279,7 +315,7 @@ public interface ApplicationManager { * To validate the application creating request * */ - void validateAppCreatingRequest(T param, boolean isReleaseRequired) throws ApplicationManagementException; + void validateAppCreatingRequest(T param) throws ApplicationManagementException, RequestValidatingException; /*** * @@ -287,8 +323,49 @@ public interface ApplicationManager { */ void validateReleaseCreatingRequest(T releases, String deviceType) throws ApplicationManagementException; + /** + * Validate enterprise application release + * + */ + void validateEntAppReleaseCreatingRequest(EntAppReleaseWrapper releaseWrapper, String deviceType) + throws RequestValidatingException, ApplicationManagementException; + + /** + * Validate custom application release + * + */ + void validateCustomAppReleaseCreatingRequest(CustomAppReleaseWrapper releaseWrapper, String deviceType) + throws RequestValidatingException, ApplicationManagementException; + + /** + * Validate web application release + * + */ + void validateWebAppReleaseCreatingRequest(WebAppReleaseWrapper releaseWrapper) + throws RequestValidatingException, ApplicationManagementException; + + /** + * Validate public application release + * + */ + void validatePublicAppReleaseCreatingRequest(PublicAppReleaseWrapper releaseWrapper, String deviceType) + throws RequestValidatingException, ApplicationManagementException; + + /** + * Validates image files of the application release + * + * @param iconFile icon of the application release + * @param screenshots screenshots of the application release + * @throws RequestValidatingException if any image is invalid + */ void validateImageArtifacts(Base64File iconFile, List screenshots) throws RequestValidatingException; + /** + * Validates any base64 files, for example a base64file may an empty file name which is invalid + * + * @param file Base64 File to be validated + * @throws RequestValidatingException if the file is invalid + */ void validateBase64File(Base64File file) throws RequestValidatingException; /*** @@ -301,6 +378,12 @@ public interface ApplicationManager { void validateImageArtifacts(Attachment iconFile, Attachment bannerFile, List attachmentList) throws RequestValidatingException; + /** + * Validates binary file of the application release + * + * @param binaryFile binary file of the application release + * @throws RequestValidatingException if binary file is invalid + */ void validateBinaryArtifact(Base64File binaryFile) throws RequestValidatingException; void validateBinaryArtifact(Attachment binaryFile) throws RequestValidatingException; @@ -343,7 +426,6 @@ public interface ApplicationManager { void updateSubsStatus (int deviceId, int operationId, String status) throws ApplicationManagementException; - /** * Get plist content to download and install the application. * diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java index ad96347ed66..94ee0cd0ac3 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.common.services; import io.entgra.application.mgt.common.IdentityServer; @@ -6,28 +24,93 @@ import io.entgra.application.mgt.common.SPApplication; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.exception.RequestValidatingException; import io.entgra.application.mgt.common.response.Application; - import java.util.List; public interface SPApplicationManager { - + /** + * This method adds existing consumer applications of service providers to the SPApplication bean + * + * @param identityServerId identity server id of the service provider + * @param applications Service providers list to which the existing applications should be added + * @throws ApplicationManagementException if error occurred while adding existing applications + */ void addExistingApps(int identityServerId, List applications) throws ApplicationManagementException; + /** + * Removes consumer application from service provider + * + * @param identityServerId of the service provider + * @param spUID uid of the service provider + * @param appIds List of application ids to be removed + * @throws ApplicationManagementException if errors while removing appIds from service provider + */ void detachSPApplications(int identityServerId, String spUID, List appIds) throws ApplicationManagementException; + /** + * Maps consumer applications to service provider + * + * @param identityServerId of the service provider + * @param spUID uid of the service provider + * @param appIds List of application ids to be mapped + * @throws ApplicationManagementException if errors while mapping appIds to service provider + */ void attachSPApplications(int identityServerId, String spUID, List appIds) throws ApplicationManagementException; + /** + * + * @param identityServerId of the identity server that is to be retrieved + * @return Identity server for the given ID + * @throws ApplicationManagementException if error occurred while getting identity server + */ IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException; + /** + * + * @return Available identity servers + * @throws ApplicationManagementException if error occurred while getting identity servers + */ IdentityServerList getIdentityServers() throws ApplicationManagementException; + /** + * + * @param identityServerId of the service provider + * @param spUID uid of the service provider + * @return Applications that are mapped to given service provider uid and identity server id + * @throws ApplicationManagementException + */ List getSPApplications(int identityServerId, String spUID) throws ApplicationManagementException; + /** + * This method is responsible for creating a new application and mapping it the given service provider uid + * and identity server id + * + * @param app Application wrapper of the application that should be created + * @param identityServerId id of the identity server to which the created application should be mapped + * @param spId uid of the service provder to which the created application should be mapped + * @param Application wrapper class which depends on application type (PUBLIC, ENTERPRISE & etc) + * @return Application bean of the created application + * @throws ApplicationManagementException if errors while creating and mapping the application + * @throws RequestValidatingException if app contains any invalid payload + */ Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException, RequestValidatingException; + /** + * Validates application ids of the applications that should be attached + * + * @param appIds application ids to be validated + * @throws ApplicationManagementException + */ void validateAttachAppsRequest(int identityServerId, List appIds) throws ApplicationManagementException; + /** + * Validates application ids of the applications that should be detached + * + * @param identityServerId id of identity server + * @param spId uid of service provider from which applications should be detached + * @param appIds applications ids to be detached + * @throws ApplicationManagementException + */ void validateDetachAppsRequest(int identityServerId, String spId, List appIds) throws ApplicationManagementException; } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java index adac0bf2f33..566e67d5d5a 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java @@ -79,6 +79,10 @@ public class CustomAppReleaseWrapper { value = "binary file of the application") private Base64File binaryFile; + @ApiModelProperty(name = "icon", + value = "banner of the application") + private Base64File banner; + public String getReleaseType() { return releaseType; } @@ -160,4 +164,12 @@ public class CustomAppReleaseWrapper { public void setBinaryFile(Base64File binaryFile) { this.binaryFile = binaryFile; } + + public Base64File getBanner() { + return banner; + } + + public void setBanner(Base64File banner) { + this.banner = banner; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java index 2aa952ac400..6fdb22dc80e 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java @@ -82,6 +82,10 @@ public class EntAppReleaseWrapper { value = "binary file of the application") private Base64File binaryFile; + @ApiModelProperty(name = "icon", + value = "banner of the application") + private Base64File banner; + public String getReleaseType() { return releaseType; } @@ -161,4 +165,12 @@ public class EntAppReleaseWrapper { public void setBinaryFile(Base64File binaryFile) { this.binaryFile = binaryFile; } + + public Base64File getBanner() { + return banner; + } + + public void setBanner(Base64File banner) { + this.banner = banner; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java index c9c5499bc27..3fdbdab0b45 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java @@ -82,6 +82,10 @@ public class PublicAppReleaseWrapper { value = "icon of the application") private Base64File icon; + @ApiModelProperty(name = "icon", + value = "banner of the application") + private Base64File banner; + public String getReleaseType() { return releaseType; } @@ -149,4 +153,12 @@ public class PublicAppReleaseWrapper { public void setScreenshots(List screenshots) { this.screenshots = screenshots; } + + public Base64File getBanner() { + return banner; + } + + public void setBanner(Base64File banner) { + this.banner = banner; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java index b2a8c2f3e46..3d0a343c74d 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java @@ -73,6 +73,10 @@ public class WebAppReleaseWrapper { value = "icon of the application") private Base64File icon; + @ApiModelProperty(name = "icon", + value = "banner of the application") + private Base64File banner; + public String getReleaseType() { return releaseType; } @@ -140,4 +144,12 @@ public class WebAppReleaseWrapper { public void setIcon(Base64File icon) { this.icon = icon; } + + public Base64File getBanner() { + return banner; + } + + public void setBanner(Base64File banner) { + this.banner = banner; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java index 878a032be09..850e11bf88e 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.core.dao; import io.entgra.application.mgt.common.IdentityServer; @@ -7,47 +25,68 @@ import io.entgra.application.mgt.core.exception.ApplicationManagementDAOExceptio import java.util.List; public interface SPApplicationDAO { + /** * - * @param tenantId - * @return the application with the provided installer location - * @throws ApplicationManagementDAOException + * @param identityServerId Id of identity server in which the service provider is in + * @param spUID Service provider uid of which the applications to be retrieved + * @return the service provider applications for the given service provider + * @throws ApplicationManagementDAOException if any db error occurred */ List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException; /** * - * @param tenantId - * @return the application with the provided installer location - * @throws ApplicationManagementDAOException + * @param identityServerId Id of identity server in which the service provider is in + * @param spUID Id of the service provider to which the application should be mapped + * @param appId Id of the application that should be mapped + * @return Primary key of the new service provider and application mapping entry + * @throws ApplicationManagementDAOException if any db error occurred */ int attachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException; /** * - * @param tenantId - * @return the application with the provided installer location - * @throws ApplicationManagementDAOException + * @param identityServerId Id of identity server in which the service provider is in + * @param spUID Id of the service provider from which the application should be removed + * @param appId Id of the application that should be removed + * @throws ApplicationManagementDAOException if any db error occurred */ void detachSPApplication(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException; + /** + * + * @return All available identity servers + * @throws ApplicationManagementDAOException if any db error occurred + */ List getIdentityServers(int tenantId) throws ApplicationManagementDAOException; + /** + * + * @param id Id of the Identity Server to be retrieved + * @return Identity Server of the given id + * @throws ApplicationManagementDAOException if any db error occurred + */ IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException; /** - * Verify whether application exist for given application name and device type. Because a name and device type is - * unique for an application. + * Verify whether application exist for given identity server id, service provider id and application id. + * Because if an application does not exist for those, it should not be mapped * - * @param appId id of the application. - * @param spUID UID of the service provider. - * @param tenantId ID of the tenant. - * @return ID of the ApplicationDTO. + * @param appId Id of the application. + * @param identityServerId Id of the identity server. + * @param spUID UID of the service provider. * @throws ApplicationManagementDAOException Application Management DAO Exception. */ boolean isSPApplicationExist(int identityServerId, String spUID, int appId, int tenantId) throws ApplicationManagementDAOException; + /** + * Delete application from all service providers if exists. When an application is deleted from the database + * it shoulbe be deleted from mapping table as well + * + * @param applicationId Id of the application to be deleted + * @throws ApplicationManagementDAOException if any db error occurred + */ void deleteApplicationFromServiceProviders(int applicationId, int tenantId) throws ApplicationManagementDAOException; - } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 9972fb05cc4..1bcdae86a90 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -262,9 +262,6 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic ResultSet rs = null; String sql = "SELECT count(AP_APP.ID) AS APP_COUNT " + "FROM AP_APP " - + "INNER JOIN AP_APP_RELEASE ON " - + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " - + "INNER JOIN (SELECT ID FROM AP_APP) AS app_data ON app_data.ID = AP_APP.ID " + "WHERE AP_APP.TENANT_ID = ?"; if (filter == null) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java index f7ab51eef05..fbbd57c8497 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.core.dao.impl.application.spapplication; import io.entgra.application.mgt.common.IdentityServer; @@ -24,7 +42,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class); @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT * " + String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -52,7 +70,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT * " + String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -181,7 +199,6 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -196,7 +213,6 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp + "AND AP_APP_ID = ? " + "AND IS_ID = ? " + "AND TENANT_ID = ? "; - try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -231,7 +247,6 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp + "AP_APP_ID, " + "IS_ID, TENANT_ID) " + "VALUES (?, ?, ?, ?)"; - int mappingId = -1; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -242,9 +257,9 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { - mappingId = rs.getInt(1); + return rs.getInt(1); } - return mappingId; + return -1; } } } catch (DBConnectionException e) { @@ -286,5 +301,4 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } - } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java index 553daa263c0..6372f3a2df3 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.core.dao.impl.application.spapplication; import io.entgra.application.mgt.common.IdentityServer; @@ -24,7 +42,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT * " + String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -52,7 +70,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT * " + String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -231,7 +249,6 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp + "AP_APP_ID, " + "IS_ID, TENANT_ID) " + "VALUES (?, ?, ?, ?)"; - int mappingId = -1; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -242,9 +259,9 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { - mappingId = rs.getInt(1); + return rs.getInt(1); } - return mappingId; + return -1; } } } catch (DBConnectionException e) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java index 309c77b1d86..5ceb9403fc2 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.core.dao.impl.application.spapplication; import io.entgra.application.mgt.common.IdentityServer; @@ -24,7 +42,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT * " + String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -52,7 +70,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT * " + String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -231,7 +249,6 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S + "AP_APP_ID, " + "IS_ID, TENANT_ID) " + "VALUES (?, ?, ?, ?)"; - int mappingId = -1; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -242,9 +259,9 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { - mappingId = rs.getInt(1); + return rs.getInt(1); } - return mappingId; + return -1; } } } catch (DBConnectionException e) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java index e31be220275..f8baebb7a4c 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.core.dao.impl.application.spapplication; import io.entgra.application.mgt.common.IdentityServer; @@ -24,7 +42,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT * " + String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -52,7 +70,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT * " + String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -231,7 +249,6 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S + "AP_APP_ID, " + "IS_ID, TENANT_ID) " + "VALUES (?, ?, ?, ?)"; - int mappingId = -1; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -242,9 +259,9 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { - mappingId = rs.getInt(1); + return rs.getInt(1); } - return mappingId; + return -1; } } } catch (DBConnectionException e) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java index f413fee76ce..ffdd342c785 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java @@ -19,6 +19,7 @@ package io.entgra.application.mgt.core.impl; import io.entgra.application.mgt.common.Base64File; import io.entgra.application.mgt.core.dao.SPApplicationDAO; +import io.entgra.application.mgt.core.util.ApplicationManagementUtil; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; @@ -137,112 +138,222 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public ApplicationReleaseDTO uploadEntAppReleaseArtifacts(EntAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, - String deviceType) throws ApplicationManagementException { - ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - return uploadEntAppReleaseArtifacts(releaseDTO, artifact, deviceType, tenantId, true); + public Application createApplication(T app) throws ApplicationManagementException { + ApplicationDTO applicationDTO = uploadReleaseArtifactIfExist(app); + try { + ConnectionManagerUtil.beginDBTransaction(); + Application application = addAppDataIntoDB(applicationDTO); + ConnectionManagerUtil.commitDBTransaction(); + return application; + } catch (DBConnectionException e) { + String msg = "Error occurred while getting database connection."; + log.error(msg, e); + ApplicationManagementUtil.deleteArtifactIfExist(applicationDTO); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred while disabling AutoCommit."; + log.error(msg, e); + ApplicationManagementUtil.deleteArtifactIfExist(applicationDTO); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + ApplicationManagementUtil.deleteArtifactIfExist(applicationDTO); + String msg = "Error occurred while adding application with the name " + applicationDTO.getName() + " to database "; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } } @Override - public ApplicationDTO uploadEntAppReleaseArtifacts(ApplicationWrapper applicationWrapper, - ApplicationArtifact applicationArtifact) - throws ApplicationManagementException{ - if (log.isDebugEnabled()) { - log.debug("Ent. Application create request is received. Application name: " + applicationWrapper.getName() - + " Device type: " + applicationWrapper.getDeviceType()); + public ApplicationRelease createEntAppRelease(int appId, EntAppReleaseWrapper releaseWrapper) + throws ApplicationManagementException { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), releaseWrapper.getScreenshots(), + releaseWrapper.getBinaryFile(), releaseWrapper.getBanner()); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + releaseDTO = uploadEntAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName(), true); + try { + return createRelease(applicationDTO, releaseDTO, ApplicationType.ENTERPRISE); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating ent app release for application with the name: " + applicationDTO.getName(); + log.error(msg, e); + deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); + throw new ApplicationManagementException(msg, e); } - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(applicationWrapper); - - //uploading application artifacts - ApplicationReleaseDTO applicationReleaseDTO = uploadEntAppReleaseArtifacts( - applicationDTO.getApplicationReleaseDTOs().get(0), applicationArtifact, - applicationWrapper.getDeviceType(), tenantId, false); - applicationDTO.getApplicationReleaseDTOs().clear(); - applicationDTO.getApplicationReleaseDTOs().add(applicationReleaseDTO); - return applicationDTO; } @Override - public ApplicationReleaseDTO uploadWebAppReleaseArtifacts(WebAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact) - throws ResourceManagementException { + public ApplicationRelease createWebAppRelease(int appId, WebAppReleaseWrapper releaseWrapper) + throws ApplicationManagementException, ResourceManagementException { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), null, releaseWrapper.getBanner()); ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - return uploadWebAppReleaseArtifacts(releaseDTO, artifact, tenantId); + releaseDTO = uploadWebAppReleaseArtifacts(releaseDTO, artifact); + try { + return createRelease(applicationDTO, releaseDTO, ApplicationType.WEB_CLIP); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating web app release for application with the name: " + applicationDTO.getName(); + log.error(msg, e); + deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); + throw new ApplicationManagementException(msg, e); + } } @Override - public ApplicationDTO uploadWebAppReleaseArtifacts(WebAppWrapper webAppWrapper, - ApplicationArtifact applicationArtifact) - throws ApplicationManagementException{ - if (log.isDebugEnabled()) { - log.debug("Web clip create request is received. App name: " + webAppWrapper.getName() + " Device type: " - + Constants.ANY); - } - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(webAppWrapper); - ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); + public ApplicationRelease createPubAppRelease(int appId, PublicAppReleaseWrapper releaseWrapper) throws + ResourceManagementException, ApplicationManagementException { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), null, releaseWrapper.getBanner()); + ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); + releaseDTO = uploadPubAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName()); try { - applicationDTO.getApplicationReleaseDTOs().clear(); - applicationDTO.getApplicationReleaseDTOs().add(uploadWebAppReleaseArtifacts(applicationReleaseDTO, applicationArtifact, tenantId)); - return applicationDTO; - } catch (ResourceManagementException e) { - String msg = "Error Occurred when uploading artifacts of the web clip: " + webAppWrapper.getName(); - log.error(msg); + return createRelease(applicationDTO, releaseDTO, ApplicationType.PUBLIC); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating ent public release for application with the name: " + applicationDTO.getName(); + log.error(msg, e); + deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); throw new ApplicationManagementException(msg, e); } } - public ApplicationReleaseDTO uploadWebAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, - int tenantId) - throws ResourceManagementException { - releaseDTO.setUuid(UUID.randomUUID().toString()); - releaseDTO.setAppHashValue(DigestUtils.md5Hex(releaseDTO.getInstallerName())); - //uploading application artifacts - return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); - } - @Override - public ApplicationReleaseDTO uploadPubAppReleaseArtifacts(PublicAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, - String deviceType) throws ResourceManagementException { + public ApplicationRelease createCustomAppRelease(int appId, CustomAppReleaseWrapper releaseWrapper) + throws ResourceManagementException, ApplicationManagementException { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + ApplicationDTO applicationDTO = applicationManager.getApplication(appId); + DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), releaseWrapper.getBanner()); ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - return uploadPubAppReleaseArtifacts(releaseDTO, artifact, deviceType, tenantId); + releaseDTO = uploadCustomAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName()); + try { + return createRelease(applicationDTO, releaseDTO, ApplicationType.CUSTOM); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while creating custom app release for application with the name: " + applicationDTO.getName(); + log.error(msg, e); + deleteApplicationArtifacts(Collections.singletonList(releaseDTO.getAppHashValue())); + throw new ApplicationManagementException(msg, e); + } } @Override - public ApplicationDTO uploadPublicAppReleaseArtifacts(PublicAppWrapper publicAppWrapper, - ApplicationArtifact applicationArtifact) - throws ApplicationManagementException{ - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + public ApplicationDTO uploadReleaseArtifactIfExist(T app) throws ApplicationManagementException { + if (ApplicationManagementUtil.isReleaseAvailable(app)) { + return uploadReleaseArtifact(app); + } + return APIUtil.convertToAppDTO(app); + } + /** + * Upload release artifacts depending on the application wrapper type + * + * @param app Application wrapper bean + * @param Application Wrapper class + * @return ApplicationDTO that is constructed after uploading the artifacts + * @throws ApplicationManagementException if any error occurred while uploading artifacts + */ + private ApplicationDTO uploadReleaseArtifact(T app) + throws ApplicationManagementException { + ApplicationArtifact artifact; + ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(app); + ApplicationReleaseDTO releaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); if (log.isDebugEnabled()) { - log.debug("Public app creating request is received. App name: " + publicAppWrapper.getName() - + " Device Type: " + publicAppWrapper.getDeviceType()); + log.debug("Ent. Application create request is received. Application name: " + applicationDTO.getName()); } + try { + if (app instanceof ApplicationWrapper) { + ApplicationWrapper wrapper = (ApplicationWrapper) app; + EntAppReleaseWrapper releaseWrapper = wrapper.getEntAppReleaseWrappers().get(0); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), releaseWrapper.getBanner()); + releaseDTO = uploadEntAppReleaseArtifacts(releaseDTO, + artifact, wrapper.getDeviceType(), false); + } else if (app instanceof PublicAppWrapper) { + PublicAppWrapper wrapper = (PublicAppWrapper) app; + PublicAppReleaseWrapper releaseWrapper = wrapper.getPublicAppReleaseWrappers().get(0); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), null, releaseWrapper.getBanner()); + releaseDTO = uploadPubAppReleaseArtifacts(releaseDTO, artifact, wrapper.getDeviceType()); + } else if (app instanceof WebAppWrapper) { + WebAppWrapper wrapper = (WebAppWrapper) app; + WebAppReleaseWrapper releaseWrapper = wrapper.getWebAppReleaseWrappers().get(0); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), null, releaseWrapper.getBanner()); + releaseDTO = uploadWebAppReleaseArtifacts(releaseDTO, artifact); + } else if (app instanceof CustomAppWrapper) { + CustomAppWrapper wrapper = (CustomAppWrapper) app; + CustomAppReleaseWrapper releaseWrapper = wrapper.getCustomAppReleaseWrappers().get(0); + artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), + releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), releaseWrapper.getBanner()); + try { + releaseDTO = uploadCustomAppReleaseArtifacts(releaseDTO, artifact, wrapper.getDeviceType()); + } catch (ResourceManagementException e) { + String msg = "Error Occurred when uploading artifacts of the web clip: " + wrapper.getName(); + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + } else { + String msg = "Invalid payload found with the request. Hence verify the request payload object."; + log.error(msg); + throw new ApplicationManagementException(msg); + } + } catch (ResourceManagementException e) { + String msg = "Error Occurred when uploading artifacts of the web clip: " + applicationDTO.getName(); + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + applicationDTO.getApplicationReleaseDTOs().clear(); + applicationDTO.getApplicationReleaseDTOs().add(releaseDTO); + return applicationDTO; + } - ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(publicAppWrapper); - ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); - validatePublicAppReleasePackageName(applicationReleaseDTO.getPackageName()); - + /** + * Upload enterprise application release artifact into file system. + * + * @param releaseDTO Application Release + * @param applicationArtifact Application Release artifacts + * @param deviceTypeName Device Type name + * @param isNewRelease New Release or Not + * @return {@link ApplicationReleaseDTO} + * @throws ApplicationManagementException if error occurred while uploading artifacts into file system. + */ + private ApplicationReleaseDTO uploadEntAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, + ApplicationArtifact applicationArtifact, String deviceTypeName, boolean isNewRelease) + throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { - //uploading application artifacts - applicationReleaseDTO = uploadPubAppReleaseArtifacts(applicationReleaseDTO, applicationArtifact, - publicAppWrapper.getDeviceType(), tenantId); - applicationDTO.getApplicationReleaseDTOs().clear(); - applicationDTO.getApplicationReleaseDTOs().add(applicationReleaseDTO); - return applicationDTO; + ApplicationReleaseDTO applicationReleaseDTO = addApplicationReleaseArtifacts(deviceTypeName, releaseDTO, + applicationArtifact, isNewRelease); + return addImageArtifacts(applicationReleaseDTO, applicationArtifact, tenantId); } catch (ResourceManagementException e) { - String msg = "Error Occured when uploading artifacts of the public app: " + publicAppWrapper.getName(); + String msg = "Error occurred while uploading application release artifacts."; log.error(msg, e); throw new ApplicationManagementException(msg, e); } } - public ApplicationReleaseDTO uploadPubAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, - String deviceType, int tenantId) + private ApplicationReleaseDTO uploadWebAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact) + throws ResourceManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + releaseDTO.setUuid(UUID.randomUUID().toString()); + releaseDTO.setAppHashValue(DigestUtils.md5Hex(releaseDTO.getInstallerName())); + //uploading application artifacts + return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); + } + + private ApplicationReleaseDTO uploadPubAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, + String deviceType) throws ResourceManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String appInstallerUrl = getPublicAppStorePath(deviceType) + releaseDTO.getPackageName(); releaseDTO.setInstallerName(appInstallerUrl); releaseDTO.setUuid(UUID.randomUUID().toString()); @@ -273,38 +384,10 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - @Override - public ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(CustomAppReleaseWrapper releaseWrapper, ApplicationArtifact artifact, - String deviceType) throws ResourceManagementException, ApplicationManagementException { - ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - return uploadCustomAppReleaseArtifacts(releaseDTO, artifact, deviceType, tenantId); - } - - @Override - public ApplicationDTO uploadCustomAppReleaseArtifactsAndConstructAppDTO(CustomAppWrapper customAppWrapper, - ApplicationArtifact applicationArtifact) - throws ApplicationManagementException { - try { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - ApplicationDTO applicationDTO = APIUtil.convertToAppDTO(customAppWrapper); - ApplicationReleaseDTO applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); - applicationReleaseDTO = uploadCustomAppReleaseArtifacts(applicationReleaseDTO, applicationArtifact, - customAppWrapper.getDeviceType(), tenantId); - applicationDTO.getApplicationReleaseDTOs().clear(); - applicationDTO.getApplicationReleaseDTOs().add(applicationReleaseDTO); - return applicationDTO; - } catch (ResourceManagementException e) { - String msg = "Error occurred while uploading application artifact into the server. Application name: " - + customAppWrapper.getName() + " Device type: " + customAppWrapper.getDeviceType(); - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } - } - - public ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, - String deviceType, int tenantId) + private ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, + String deviceType) throws ResourceManagementException, ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); byte[] content = getByteContentOfApp(applicationArtifact); String md5OfApp = generateMD5OfApp(applicationArtifact, content); @@ -379,16 +462,15 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - - /** * Delete Application release artifacts * * @param directoryPaths Directory paths - * @param tenantId Tenant Id * @throws ApplicationManagementException if error occurred while deleting application release artifacts. */ - private void deleteApplicationArtifacts(List directoryPaths, int tenantId) throws ApplicationManagementException { + @Override + public void deleteApplicationArtifacts(List directoryPaths) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); try { applicationStorageManager.deleteAllApplicationReleaseArtifacts(directoryPaths, tenantId); @@ -693,7 +775,6 @@ public class ApplicationManagerImpl implements ApplicationManager { return applicationReleaseDTO; } - @Override public ApplicationList getApplications(Filter filter) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -950,32 +1031,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public Application persistApplication(ApplicationDTO applicationDTO) throws ApplicationManagementException { - try { - ConnectionManagerUtil.beginDBTransaction(); - Application application = executeApplicationPersistenceTransaction(applicationDTO); - ConnectionManagerUtil.commitDBTransaction(); - return application; - } catch (DBConnectionException e) { - String msg = "Error occurred while getting database connection."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (TransactionManagementException e) { - String msg = "Error occurred while disabling AutoCommit."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (ApplicationManagementException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Error occurred while adding application with the name " + applicationDTO.getName() + " to database "; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - } - - @Override - public Application executeApplicationPersistenceTransaction(ApplicationDTO applicationDTO) throws + public Application addAppDataIntoDB(ApplicationDTO applicationDTO) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationReleaseDTO applicationReleaseDTO = null; @@ -986,10 +1042,6 @@ public class ApplicationManagerImpl implements ApplicationManager { // Insert to application table int appId = this.applicationDAO.createApplication(applicationDTO, tenantId); if (appId == -1) { - if (applicationReleaseDTO != null) { - deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), - tenantId); - } String msg = "Application data storing is Failed."; log.error(msg); throw new ApplicationManagementDAOException(msg); @@ -1061,35 +1113,22 @@ public class ApplicationManagerImpl implements ApplicationManager { String msg = "Error occurred while adding lifecycle state. application name: " + applicationDTO.getName() + "."; log.error(msg, e); - try { - APIUtil.getApplicationStorageManager().deleteAllApplicationReleaseArtifacts( - Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); - } catch (ApplicationStorageManagementException ex) { - String errorLog = - "Error occurred when deleting application artifacts. Application artifacts are tried to " - + "delete because of lifecycle state adding issue in the application creating operation."; - log.error(errorLog, ex); - throw new ApplicationManagementException(errorLog, ex); - } throw new ApplicationManagementException(msg, e); } catch (ApplicationManagementDAOException e) { String msg = "Error occurred while adding application or application release. application name: " + applicationDTO.getName() + "."; log.error(msg, e); - deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); throw new ApplicationManagementException(msg, e); } catch (LifecycleManagementException e) { String msg = "Error occurred when getting initial lifecycle state. application name: " + applicationDTO.getName() + "."; log.error(msg, e); - deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); throw new ApplicationManagementException(msg, e); } catch (VisibilityManagementDAOException e) { String msg = "Error occurred while adding unrestricted roles. application name: " + applicationDTO.getName() + "."; log.error(msg, e); - deleteApplicationArtifacts(Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); throw new ApplicationManagementException(msg, e); } } @@ -1103,7 +1142,6 @@ public class ApplicationManagerImpl implements ApplicationManager { log.debug("Application release creating request is received for the application id: " + applicationDTO.getId()); } - if (!type.toString().equals(applicationDTO.getType())) { String msg = "It is possible to add new application release for " + type + " app type. But you are requesting to add new application release for " + applicationDTO.getType() @@ -1192,31 +1230,6 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - /** - * Upload enterprise application release artifact into file system. - * - * @param releaseDTO Apllication Release - * @param applicationArtifact Application Release artifacts - * @param deviceTypeName Device Type name - * @param tenantId Tenant Id - * @param isNewRelease New Release or Not - * @return {@link ApplicationReleaseDTO} - * @throws ApplicationManagementException if error occurred while uploading artifacts into file system. - */ - private ApplicationReleaseDTO uploadEntAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, - ApplicationArtifact applicationArtifact, String deviceTypeName, int tenantId, boolean isNewRelease) - throws ApplicationManagementException { - try { - ApplicationReleaseDTO applicationReleaseDTO = addApplicationReleaseArtifacts(deviceTypeName, releaseDTO, - applicationArtifact, isNewRelease); - return addImageArtifacts(applicationReleaseDTO, applicationArtifact, tenantId); - } catch (ResourceManagementException e) { - String msg = "Error occurred while uploading application release artifacts."; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } - } - /** * Check whether given OS range is valid or invalid * @@ -1373,7 +1386,6 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - @Override public Application getApplicationByUuid(String releaseUuid, String state) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); @@ -1658,66 +1670,62 @@ public class ApplicationManagerImpl implements ApplicationManager { ConnectionManagerUtil.closeDBConnection(); } - if (applicationDTO.getApplicationReleaseDTOs().size() == 1) { - deleteApplication(applicationDTO, tenantId); - } else { - for (ApplicationReleaseDTO applicationReleaseDTO : applicationDTO.getApplicationReleaseDTOs()) { - if (releaseUuid.equals(applicationReleaseDTO.getUuid())) { - if (!lifecycleStateManager.isDeletableState(applicationReleaseDTO.getCurrentState())) { - String msg = - "Application state is not in the deletable state. Therefore you are not permitted to " - + "delete the application release."; + for (ApplicationReleaseDTO applicationReleaseDTO : applicationDTO.getApplicationReleaseDTOs()) { + if (releaseUuid.equals(applicationReleaseDTO.getUuid())) { + if (!lifecycleStateManager.isDeletableState(applicationReleaseDTO.getCurrentState())) { + String msg = + "Application state is not in the deletable state. Therefore you are not permitted to " + + "delete the application release."; + log.error(msg); + throw new ForbiddenException(msg); + } + try { + ConnectionManagerUtil.beginDBTransaction(); + List deviceSubscriptionDTOS = subscriptionDAO + .getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId, null, null); + if (!deviceSubscriptionDTOS.isEmpty()) { + String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid() + + " either subscribed to device/s or it had subscribed to device/s. Therefore you " + + "are not permitted to delete the application release."; log.error(msg); throw new ForbiddenException(msg); } - try { - ConnectionManagerUtil.beginDBTransaction(); - List deviceSubscriptionDTOS = subscriptionDAO - .getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId, null, null); - if (!deviceSubscriptionDTOS.isEmpty()) { - String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid() - + " either subscribed to device/s or it had subscribed to device/s. Therefore you " - + "are not permitted to delete the application release."; - log.error(msg); - throw new ForbiddenException(msg); - } - lifecycleStateDAO.deleteLifecycleStateByReleaseId(applicationReleaseDTO.getId()); - applicationReleaseDAO.deleteRelease(applicationReleaseDTO.getId()); - applicationStorageManager.deleteAllApplicationReleaseArtifacts( - Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); - ConnectionManagerUtil.commitDBTransaction(); - } catch (DBConnectionException e) { - String msg = "Error occurred while observing the database connection to delete application " - + "release which has the UUID:" + releaseUuid; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (TransactionManagementException e) { - String msg = "Database access error is occurred when deleting application release which has " - + "the UUID: " + releaseUuid; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (ApplicationManagementDAOException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Error occurred while verifying whether application relase has an subscription or " - + "not. Application release UUID: " + releaseUuid; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (ApplicationStorageManagementException e) { - String msg = "Error occurred when deleting the application release artifact from the file " - + "system. Application release UUID: " + releaseUuid; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } catch (LifeCycleManagementDAOException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - String msg = "Error occurred when deleting lifecycle data for application release UUID: " - + releaseUuid; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } finally { - ConnectionManagerUtil.closeDBConnection(); - } - break; + lifecycleStateDAO.deleteLifecycleStateByReleaseId(applicationReleaseDTO.getId()); + applicationReleaseDAO.deleteRelease(applicationReleaseDTO.getId()); + applicationStorageManager.deleteAllApplicationReleaseArtifacts( + Collections.singletonList(applicationReleaseDTO.getAppHashValue()), tenantId); + ConnectionManagerUtil.commitDBTransaction(); + } catch (DBConnectionException e) { + String msg = "Error occurred while observing the database connection to delete application " + + "release which has the UUID:" + releaseUuid; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Database access error is occurred when deleting application release which has " + + "the UUID: " + releaseUuid; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while verifying whether application relase has an subscription or " + + "not. Application release UUID: " + releaseUuid; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (ApplicationStorageManagementException e) { + String msg = "Error occurred when deleting the application release artifact from the file " + + "system. Application release UUID: " + releaseUuid; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } catch (LifeCycleManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred when deleting lifecycle data for application release UUID: " + + releaseUuid; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); } + break; } } } @@ -3187,9 +3195,8 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - @Override - public void validateAppCreatingRequest(T param, boolean isReleaseRequired) throws ApplicationManagementException { + public void validateAppCreatingRequest(T param) throws ApplicationManagementException, RequestValidatingException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); int deviceTypeId = -1; @@ -3223,17 +3230,12 @@ public class ApplicationManagerImpl implements ApplicationManager { } DeviceType deviceType = APIUtil.getDeviceTypeData(applicationWrapper.getDeviceType()); deviceTypeId = deviceType.getId(); - - List entAppReleaseWrappers; - entAppReleaseWrappers = applicationWrapper.getEntAppReleaseWrappers(); - - if (isReleaseRequired && entAppReleaseWrappers.size() != 1) { - String msg = "Invalid application creating request. Application creating request must have single " - + "application release. Application name:" + applicationWrapper.getName() + "."; - log.error(msg); - throw new BadRequestException(msg); - } unrestrictedRoles = applicationWrapper.getUnrestrictedRoles(); + List releaseWrappers = applicationWrapper.getEntAppReleaseWrappers(); + if (!releaseWrappers.isEmpty()) { + EntAppReleaseWrapper releaseWrapper = releaseWrappers.get(0); + validateEntAppReleaseCreatingRequest(releaseWrapper, applicationWrapper.getDeviceType()); + } } else if (param instanceof WebAppWrapper) { WebAppWrapper webAppWrapper = (WebAppWrapper) param; appName = webAppWrapper.getName(); @@ -3261,17 +3263,12 @@ public class ApplicationManagerImpl implements ApplicationManager { log.error(msg); throw new BadRequestException(msg); } - - List webAppReleaseWrappers; - webAppReleaseWrappers = webAppWrapper.getWebAppReleaseWrappers(); - - if (isReleaseRequired && webAppReleaseWrappers.size() != 1) { - String msg = "Invalid web clip creating request. Web clip creating request must have single " - + "web clip release. Web clip name:" + webAppWrapper.getName() + "."; - log.error(msg); - throw new BadRequestException(msg); - } unrestrictedRoles = webAppWrapper.getUnrestrictedRoles(); + List releaseWrappers = webAppWrapper.getWebAppReleaseWrappers(); + if(!releaseWrappers.isEmpty()) { + WebAppReleaseWrapper releaseWrapper = releaseWrappers.get(0); + validateWebAppReleaseCreatingRequest(releaseWrapper); + } } else if (param instanceof PublicAppWrapper) { PublicAppWrapper publicAppWrapper = (PublicAppWrapper) param; appName = publicAppWrapper.getName(); @@ -3298,17 +3295,12 @@ public class ApplicationManagerImpl implements ApplicationManager { } DeviceType deviceType = APIUtil.getDeviceTypeData(publicAppWrapper.getDeviceType()); deviceTypeId = deviceType.getId(); - - List publicAppReleaseWrappers; - publicAppReleaseWrappers = publicAppWrapper.getPublicAppReleaseWrappers(); - - if (isReleaseRequired && publicAppReleaseWrappers.size() != 1) { - String msg = "Invalid public app creating request. Request must have single release. Application name:" - + publicAppWrapper.getName() + "."; - log.error(msg); - throw new BadRequestException(msg); - } unrestrictedRoles = publicAppWrapper.getUnrestrictedRoles(); + List releaseWrappers = publicAppWrapper.getPublicAppReleaseWrappers(); + if(!releaseWrappers.isEmpty()) { + PublicAppReleaseWrapper releaseWrapper = releaseWrappers.get(0); + validatePublicAppReleaseCreatingRequest(releaseWrapper, publicAppWrapper.getDeviceType()); + } } else if (param instanceof CustomAppWrapper) { CustomAppWrapper customAppWrapper = (CustomAppWrapper) param; appName = customAppWrapper.getName(); @@ -3335,17 +3327,12 @@ public class ApplicationManagerImpl implements ApplicationManager { } DeviceType deviceType = APIUtil.getDeviceTypeData(customAppWrapper.getDeviceType()); deviceTypeId = deviceType.getId(); - - List customAppReleaseWrappers; - customAppReleaseWrappers = customAppWrapper.getCustomAppReleaseWrappers(); - - if (isReleaseRequired && customAppReleaseWrappers.size() != 1) { - String msg = "Invalid custom app creating request. Application creating request must have single " - + "application release. Application name:" + customAppWrapper.getName() + "."; - log.error(msg); - throw new BadRequestException(msg); - } unrestrictedRoles = customAppWrapper.getUnrestrictedRoles(); + List releaseWrappers = customAppWrapper.getCustomAppReleaseWrappers(); + if(!releaseWrappers.isEmpty()) { + CustomAppReleaseWrapper releaseWrapper = releaseWrappers.get(0); + validateCustomAppReleaseCreatingRequest(releaseWrapper, customAppWrapper.getDeviceType()); + } } else { String msg = "Invalid payload found with the request. Hence verify the request payload object."; log.error(msg); @@ -3518,6 +3505,37 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + @Override + public void validateEntAppReleaseCreatingRequest(EntAppReleaseWrapper releaseWrapper, String deviceType) + throws RequestValidatingException, ApplicationManagementException { + validateReleaseCreatingRequest(releaseWrapper, deviceType); + validateBinaryArtifact(releaseWrapper.getBinaryFile()); + validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); + } + + @Override + public void validateCustomAppReleaseCreatingRequest(CustomAppReleaseWrapper releaseWrapper, String deviceType) + throws RequestValidatingException, ApplicationManagementException { + validateReleaseCreatingRequest(releaseWrapper, deviceType); + validateBinaryArtifact(releaseWrapper.getBinaryFile()); + validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); + } + + @Override + public void validateWebAppReleaseCreatingRequest(WebAppReleaseWrapper releaseWrapper) + throws RequestValidatingException, ApplicationManagementException { + validateReleaseCreatingRequest(releaseWrapper, Constants.ANY); + validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); + } + + @Override + public void validatePublicAppReleaseCreatingRequest(PublicAppReleaseWrapper releaseWrapper, String deviceType) + throws RequestValidatingException, ApplicationManagementException { + validateReleaseCreatingRequest(releaseWrapper, deviceType); + validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); + validatePublicAppReleasePackageName(releaseWrapper.getPackageName()); + } + @Override public void validateImageArtifacts(Base64File iconFile, List screenshots) throws RequestValidatingException { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java index 447487e0d47..1f90f5db06e 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -1,25 +1,33 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.core.impl; -import io.entgra.application.mgt.common.ApplicationArtifact; import io.entgra.application.mgt.common.IdentityServer; import io.entgra.application.mgt.common.IdentityServerList; import io.entgra.application.mgt.common.SPApplication; import io.entgra.application.mgt.common.dto.ApplicationDTO; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.exception.DBConnectionException; -import io.entgra.application.mgt.common.exception.RequestValidatingException; import io.entgra.application.mgt.common.exception.TransactionManagementException; import io.entgra.application.mgt.common.response.Application; import io.entgra.application.mgt.common.services.ApplicationManager; import io.entgra.application.mgt.common.services.SPApplicationManager; -import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; -import io.entgra.application.mgt.common.wrapper.CustomAppReleaseWrapper; -import io.entgra.application.mgt.common.wrapper.CustomAppWrapper; -import io.entgra.application.mgt.common.wrapper.EntAppReleaseWrapper; -import io.entgra.application.mgt.common.wrapper.PublicAppReleaseWrapper; -import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; -import io.entgra.application.mgt.common.wrapper.WebAppReleaseWrapper; -import io.entgra.application.mgt.common.wrapper.WebAppWrapper; import io.entgra.application.mgt.core.dao.ApplicationDAO; import io.entgra.application.mgt.core.dao.SPApplicationDAO; import io.entgra.application.mgt.core.dao.VisibilityDAO; @@ -31,12 +39,9 @@ import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.application.mgt.core.util.APIUtil; import io.entgra.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.application.mgt.core.util.ConnectionManagerUtil; -import io.entgra.application.mgt.core.util.Constants; -import io.entgra.application.mgt.core.util.SPApplicationManagementUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; - import java.util.ArrayList; import java.util.List; @@ -218,7 +223,6 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } - public void detachSPApplications(int identityServerId, String spUID, List appIds) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { @@ -239,54 +243,40 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } @Override - public Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException, - RequestValidatingException { + public Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException { ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); - applicationManager.validateAppCreatingRequest(app, false); - ApplicationDTO applicationDTO = constructApplicationDTO(app); + ApplicationDTO applicationDTO = applicationManager.uploadReleaseArtifactIfExist(app); + if (log.isDebugEnabled()) { + log.debug("Application release create request is received. Application name: " + applicationDTO.getName() + + " Device type ID: " + applicationDTO.getDeviceTypeId()); + } try { ConnectionManagerUtil.beginDBTransaction(); - Application createdApp = createSPApplication(applicationDTO); + Application createdApp = applicationManager.addAppDataIntoDB(applicationDTO); attachCreatedSPApplication(createdApp, identityServerId, spId); ConnectionManagerUtil.commitDBTransaction(); return createdApp; } catch (DBConnectionException e) { String msg = "Error occurred while getting database connection."; log.error(msg, e); + ApplicationManagementUtil.deleteArtifactIfExist(applicationDTO); throw new ApplicationManagementException(msg, e); } catch (TransactionManagementException e) { String msg = "Error occurred while disabling AutoCommit."; log.error(msg, e); + ApplicationManagementUtil.deleteArtifactIfExist(applicationDTO); throw new ApplicationManagementException(msg, e); } catch (ApplicationManagementException e) { ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred while creating and attaching application with the name " + applicationDTO.getName() ; log.error(msg, e); + ApplicationManagementUtil.deleteArtifactIfExist(applicationDTO); throw new ApplicationManagementException(msg, e); } finally { ConnectionManagerUtil.closeDBConnection(); } } - private ApplicationDTO constructApplicationDTO(T app) throws ApplicationManagementException, - RequestValidatingException { - if (ApplicationManagementUtil.isReleaseAvailable(app)) { - return uploadReleaseArtifactAndConstructApplicationDTO(app); - } - return APIUtil.convertToAppDTO(app); - } - - public Application createSPApplication(ApplicationDTO applicationDTO) throws ApplicationManagementException { - if (log.isDebugEnabled()) { - log.debug("Application release create request is received. Application name: " + applicationDTO.getName() - + " Device type ID: " + applicationDTO.getDeviceTypeId()); - } - ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); - return applicationManager.executeApplicationPersistenceTransaction(applicationDTO); - } - - - public void attachCreatedSPApplication(Application createdApp, int identityServerId, String spUID) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { @@ -298,50 +288,4 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } - public ApplicationDTO uploadReleaseArtifactAndConstructApplicationDTO(T app) throws ApplicationManagementException, - RequestValidatingException { - ApplicationArtifact artifact; - ApplicationDTO applicationDTO; - ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); - if (app instanceof ApplicationWrapper) { - ApplicationWrapper wrapper = (ApplicationWrapper) app; - EntAppReleaseWrapper releaseWrapper = wrapper.getEntAppReleaseWrappers().get(0); - applicationManager.validateReleaseCreatingRequest(releaseWrapper, wrapper.getDeviceType()); - applicationManager.validateBinaryArtifact(releaseWrapper.getBinaryFile()); - applicationManager.validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); - artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), null); - applicationDTO = applicationManager.uploadEntAppReleaseArtifacts(wrapper, artifact); - } else if (app instanceof PublicAppWrapper) { - PublicAppWrapper wrapper = (PublicAppWrapper) app; - PublicAppReleaseWrapper releaseWrapper = wrapper.getPublicAppReleaseWrappers().get(0); - applicationManager.validateReleaseCreatingRequest(releaseWrapper, wrapper.getDeviceType()); - applicationManager.validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); - artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), null, null); - applicationDTO = applicationManager.uploadPublicAppReleaseArtifacts(wrapper, artifact); - } else if (app instanceof WebAppWrapper) { - WebAppWrapper wrapper = (WebAppWrapper) app; - WebAppReleaseWrapper releaseWrapper = wrapper.getWebAppReleaseWrappers().get(0); - applicationManager.validateReleaseCreatingRequest(releaseWrapper, Constants.ANY); - applicationManager.validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); - artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), null, null); - applicationDTO = applicationManager.uploadWebAppReleaseArtifacts(wrapper, artifact); - } else if (app instanceof CustomAppWrapper) { - CustomAppWrapper wrapper = (CustomAppWrapper) app; - CustomAppReleaseWrapper releaseWrapper = wrapper.getCustomAppReleaseWrappers().get(0); - applicationManager.validateReleaseCreatingRequest(releaseWrapper, wrapper.getDeviceType()); - applicationManager.validateBinaryArtifact(releaseWrapper.getBinaryFile()); - applicationManager.validateImageArtifacts(releaseWrapper.getIcon(), releaseWrapper.getScreenshots()); - artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), - releaseWrapper.getScreenshots(), releaseWrapper.getBinaryFile(), null); - applicationDTO = applicationManager.uploadCustomAppReleaseArtifactsAndConstructAppDTO(wrapper, artifact); - } else { - String msg = "Invalid payload found with the request. Hence verify the request payload object."; - log.error(msg); - throw new ApplicationManagementException(msg); - } - return applicationDTO; - } } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java index ad5cabf8a40..f0ef6c4b299 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java @@ -18,12 +18,13 @@ package io.entgra.application.mgt.core.util; import io.entgra.application.mgt.common.ApplicationArtifact; -import io.entgra.application.mgt.common.ApplicationSubscriptionType; -import io.entgra.application.mgt.common.ApplicationType; import io.entgra.application.mgt.common.Base64File; import io.entgra.application.mgt.common.FileDataHolder; +import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.dto.ApplicationReleaseDTO; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.exception.RequestValidatingException; +import io.entgra.application.mgt.common.exception.ResourceManagementException; import io.entgra.application.mgt.common.services.SPApplicationManager; import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; import io.entgra.application.mgt.common.wrapper.CustomAppReleaseWrapper; @@ -46,11 +47,10 @@ import io.entgra.application.mgt.core.config.Extension; import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager; import org.wso2.carbon.device.mgt.core.common.util.FileUtil; -import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -63,6 +63,16 @@ public class ApplicationManagementUtil { private static Log log = LogFactory.getLog(ApplicationManagementUtil.class); + /** + * Construct ApplicationArtifact from given base64 artifact files + * + * @param iconBase64 icon of the application + * @param screenshotsBase64 screenshots of the application + * @param binaryFileBase64 binary file of the application + * @param bannerFileBase64 banner of the application + * @return ApplicationArtifact the give base64 release artifact files + * @throws BadRequestException if any invalid payload is found + */ public static ApplicationArtifact constructApplicationArtifact(Base64File iconBase64, List screenshotsBase64, Base64File binaryFileBase64, Base64File bannerFileBase64) throws BadRequestException { @@ -107,6 +117,8 @@ public class ApplicationManagementUtil { if (screenshotsBase64 != null) { Map screenshotData = new TreeMap<>(); + // This is to handle cases in which multiple screenshots have the same name + Map screenshotNameCount = new HashMap<>(); for (Base64File screenshot : screenshotsBase64) { try { applicationManager.validateBase64File(screenshot); @@ -116,13 +128,21 @@ public class ApplicationManagementUtil { throw new BadRequestException(msg, e); } FileDataHolder screenshotFile = base64FileToFileDataHolder(screenshot); - screenshotData.put(screenshotFile.getName(), screenshotFile.getFile()); + String screenshotName = screenshotFile.getName(); + screenshotNameCount.put(screenshotName, screenshotNameCount.getOrDefault(screenshotName, 0) + 1); + screenshotName = FileUtil.generateDuplicateFileName(screenshotName, screenshotNameCount.get(screenshotName)); + screenshotData.put(screenshotName, screenshotFile.getFile()); } applicationArtifact.setScreenshots(screenshotData); } return applicationArtifact; } + /** + * + * @param base64File Base64File that should be converted to FileDataHolder bean + * @return FileDataHolder bean which contains input stream and name of the file + */ public static FileDataHolder base64FileToFileDataHolder(Base64File base64File) { InputStream stream = FileUtil.base64ToInputStream(base64File.getBase64String()); return new FileDataHolder(base64File.getName(), stream); @@ -165,6 +185,27 @@ public class ApplicationManagementUtil { return getInstance(extension, LifecycleStateManager.class); } + /** + * This is useful to delete application artifacts if any error occurred while creating release/application + * after uploading the artifacts + * + * @param app ApplicationDTO of the application of which the artifacts should be deleted + * @throws ApplicationManagementException if error occurred while deleting artifacts + */ + public static void deleteArtifactIfExist(ApplicationDTO app) throws ApplicationManagementException { + ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); + if (!app.getApplicationReleaseDTOs().isEmpty()) { + applicationManager.deleteApplicationArtifacts(Collections.singletonList(app.getApplicationReleaseDTOs().get(0).getAppHashValue())); + } + } + + /** + * Check if application release available for a given application wrapper. This is useful since + * if a release is available for an application that needs to handled separately + * + * @param appWrapper Application wrapper bean of the application + * @return if release is available or not + */ public static boolean isReleaseAvailable(T appWrapper) { if (appWrapper instanceof ApplicationWrapper) { List entAppReleaseWrappers = ((ApplicationWrapper) appWrapper).getEntAppReleaseWrappers(); diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java index dc276ddf257..4502c8987bf 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java @@ -194,7 +194,7 @@ public class DAOUtil { * To create application object from the result set retrieved from the Database. * * @param rs ResultSet - * @return List of Applications that is retrieved from the Database. + * @return List of Identity Servers that is retrieved from the Database. * @throws SQLException SQL Exception * @throws JSONException JSONException. */ @@ -215,7 +215,6 @@ public class DAOUtil { return identityServers; } - /** * To create application object from the result set retrieved from the Database. * diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/SPApplicationManagementUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/SPApplicationManagementUtil.java deleted file mode 100644 index 53c11fd6f31..00000000000 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/SPApplicationManagementUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. 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 io.entgra.application.mgt.core.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import java.util.ArrayList; -import java.util.List; - -/** - * This DAOUtil class is responsible for making sure single instance of each Extension Manager is used throughout for - * all the tasks. - */ -public class SPApplicationManagementUtil { - - private static Log log = LogFactory.getLog(SPApplicationManagementUtil.class); - - private static List getDefaultSPAppCategories() { - List categories = new ArrayList<>(); - categories.add(Constants.SP_APP_CATEGORY); - return categories; - } - - -} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java index c781b674df9..7cb9e9491e6 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java @@ -122,8 +122,7 @@ public class ApplicationManagementTest extends BaseTestCase { applicationArtifact.setScreenshots(screenshots); ApplicationManager manager = new ApplicationManagerImpl(); - ApplicationDTO applicationDTO = manager.uploadEntAppReleaseArtifacts(applicationWrapper, applicationArtifact); - manager.persistApplication(applicationDTO); + manager.createApplication(applicationWrapper); } @DataProvider(name = "applicationIdDataProvider") diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java index 905f140de75..23ca981b00b 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java @@ -17,6 +17,7 @@ */ package io.entgra.application.mgt.publisher.api.services; +import io.entgra.application.mgt.common.Base64File; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -27,8 +28,6 @@ import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.Info; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; -import org.apache.cxf.jaxrs.ext.multipart.Attachment; -import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; import io.entgra.application.mgt.common.ApplicationList; @@ -284,7 +283,7 @@ public interface ApplicationManagementPublisherAPI { @POST @Path("/ent-app") @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, @@ -318,42 +317,12 @@ public interface ApplicationManagementPublisherAPI { name = "application", value = "The application that need to be created.", required = true) - @Multipart("application") ApplicationWrapper application, - @ApiParam( - name = "binaryFile", - value = "Binary file of uploading application", - required = true) - @Multipart(value = "binaryFile") Attachment binaryFile, - @ApiParam( - name = "icon", - value = "Icon of the uploading application", - required = true) - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "Banner of the uploading application") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "Screen Shots of the uploading application", - required = true) - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot3") Attachment screenshot3 - ); + ApplicationWrapper application); @POST @Path("/web-app") @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, @@ -387,37 +356,13 @@ public interface ApplicationManagementPublisherAPI { name = "webapp", value = "The web app that need to be created.", required = true) - @Multipart("webapp") WebAppWrapper webAppWrapper, - @ApiParam( - name = "icon", - value = "Icon of the uploading web app", - required = true) - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "Banner of the uploading web app") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "Screen Shots of the uploading web app", - required = true) - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading web app", - required = false) - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading web app", - required = false) - @Multipart(value = "screenshot3") Attachment screenshot3 + WebAppWrapper webAppWrapper ); @POST @Path("/public-app") @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, @@ -451,35 +396,13 @@ public interface ApplicationManagementPublisherAPI { name = "public-app", value = "The public app that need to be created.", required = true) - @Multipart("public-app") PublicAppWrapper publicAppWrapper, - @ApiParam( - name = "icon", - value = "Icon of the uploading public app", - required = true) - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "Banner of the uploading public app") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "Screen Shots of the uploading public app", - required = true) - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading public app") - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading public app") - @Multipart(value = "screenshot3") Attachment screenshot3 + PublicAppWrapper publicAppWrapper ); @POST @Path("/custom-app") @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON, @@ -513,41 +436,12 @@ public interface ApplicationManagementPublisherAPI { name = "application", value = "The application that need to be created.", required = true) - @Multipart("application") CustomAppWrapper customAppWrapper, - @ApiParam( - name = "binaryFile", - value = "Binary file of uploading application", - required = true) - @Multipart(value = "binaryFile") Attachment binaryFile, - @ApiParam( - name = "icon", - value = "Icon of the uploading application", - required = true) - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "Banner of the uploading application") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "Screen Shots of the uploading application", - required = true) - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot3") Attachment screenshot3 + CustomAppWrapper customAppWrapper ); @POST @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/{deviceType}/ent-app/{appId}") @ApiOperation( consumes = MediaType.APPLICATION_JSON, @@ -592,41 +486,12 @@ public interface ApplicationManagementPublisherAPI { name = "applicationRelease", value = "The application release that need to be created.", required = true) - @Multipart("applicationRelease") EntAppReleaseWrapper entAppReleaseWrapper, - @ApiParam( - name = "binaryFile", - value = "Binary file of uploading application", - required = true) - @Multipart(value = "binaryFile") Attachment binaryFile, - @ApiParam( - name = "icon", - value = "Icon of the uploading application", - required = true) - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "Banner of the uploading application") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "Screen Shots of the uploading application", - required = true) - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot3") Attachment screenshot3 + EntAppReleaseWrapper entAppReleaseWrapper ); @POST @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/{deviceType}/public-app/{appId}") @ApiOperation( consumes = MediaType.APPLICATION_JSON, @@ -671,36 +536,12 @@ public interface ApplicationManagementPublisherAPI { name = "applicationRelease", value = "The application release that need to be created.", required = true) - @Multipart("applicationRelease") PublicAppReleaseWrapper publicAppReleaseWrapper, - @ApiParam( - name = "icon", - value = "Icon of the uploading application", - required = true) - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "Banner of the uploading application") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "Screen Shots of the uploading application", - required = true) - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot3") Attachment screenshot3 + PublicAppReleaseWrapper publicAppReleaseWrapper ); @POST @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/web-app/{appId}") @ApiOperation( consumes = MediaType.APPLICATION_JSON, @@ -740,36 +581,12 @@ public interface ApplicationManagementPublisherAPI { name = "applicationRelease", value = "The application release that need to be created.", required = true) - @Multipart("applicationRelease") WebAppReleaseWrapper webAppReleaseWrapper, - @ApiParam( - name = "icon", - value = "Icon of the uploading application", - required = true) - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "Banner of the uploading application") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "Screen Shots of the uploading application", - required = true) - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot3") Attachment screenshot3 + WebAppReleaseWrapper webAppReleaseWrapper ); @POST @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/{deviceType}/custom-app/{appId}") @ApiOperation( consumes = MediaType.APPLICATION_JSON, @@ -814,42 +631,13 @@ public interface ApplicationManagementPublisherAPI { name = "applicationRelease", value = "The application release that need to be created.", required = true) - @Multipart("applicationRelease") CustomAppReleaseWrapper customAppReleaseWrapper, - @ApiParam( - name = "binaryFile", - value = "Binary file of uploading application", - required = true) - @Multipart(value = "binaryFile") Attachment binaryFile, - @ApiParam( - name = "icon", - value = "Icon of the uploading application", - required = true) - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "Banner of the uploading application") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "Screen Shots of the uploading application", - required = true) - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading application", - required = false) - @Multipart(value = "screenshot3") Attachment screenshot3 + CustomAppReleaseWrapper customAppReleaseWrapper ); @PUT @Path("/image-artifacts/{uuid}") @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.APPLICATION_JSON, @@ -885,23 +673,15 @@ public interface ApplicationManagementPublisherAPI { @ApiParam( name = "icon", value = "Icon of the uploading application") - @Multipart(value = "icon") Attachment iconFile, + Base64File iconFile, @ApiParam( name = "banner", value = "Banner of the uploading application") - @Multipart(value = "banner") Attachment bannerFile, + Base64File bannerFile, @ApiParam( name = "screenshot1", value = "Screen Shots of the uploading application") - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Screen Shots of the uploading application") - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Screen Shots of the uploading application") - @Multipart(value = "screenshot3") Attachment screenshot3 + List screenshots ); @GET @@ -951,7 +731,7 @@ public interface ApplicationManagementPublisherAPI { @PUT @Path("/ent-app-artifacts/{deviceType}/{appId}/{uuid}") @Produces(MediaType.APPLICATION_JSON) - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.APPLICATION_JSON, @@ -994,13 +774,13 @@ public interface ApplicationManagementPublisherAPI { value = "UUID of the application", required = true) @PathParam("uuid") String applicationUUID, - @Multipart("binaryFile") Attachment binaryFile + Base64File binaryFile ); @PUT @Path("/ent-app-release/{uuid}") @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.MULTIPART_FORM_DATA) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.APPLICATION_JSON, @@ -1039,39 +819,12 @@ public interface ApplicationManagementPublisherAPI { name = "entAppReleaseWrapper", value = "Application release wrapper which is going to update.", required = true) - @Multipart( - value = "entAppReleaseWrapper", - type = "application/json") EntAppReleaseWrapper entAppReleaseWrapper, - @ApiParam( - name = "binaryFile", - value = "Application installer file.", - required = true) - @Multipart(value = "binaryFile") Attachment binaryFile, - @ApiParam( - name = "icon", - value = "Icon file of the application release.") - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "banner file of the application release.") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "First screenshot of the uploading application") - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Second screenshot 2 of the uploading application") - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Third screenshot of the uploading application") - @Multipart(value = "screenshot3") Attachment screenshot3); + EntAppReleaseWrapper entAppReleaseWrapper); @PUT @Path("/public-app-release/{uuid}") @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.MULTIPART_FORM_DATA) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.APPLICATION_JSON, @@ -1110,34 +863,12 @@ public interface ApplicationManagementPublisherAPI { name = "pubAppReleaseWrapper", value = "Application release wrapper which is going to update.", required = true) - @Multipart( - value = "pubAppReleaseWrapper", - type = "application/json") PublicAppReleaseWrapper publicAppReleaseWrapper, - @ApiParam( - name = "icon", - value = "Icon file of the application release.") - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "banner file of the application release.") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "First screenshot of the uploading application") - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Second screenshot 2 of the uploading application") - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Third screenshot of the uploading application") - @Multipart(value = "screenshot3") Attachment screenshot3); + PublicAppReleaseWrapper publicAppReleaseWrapper); @PUT @Path("/web-app-release/{uuid}") @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.MULTIPART_FORM_DATA) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.APPLICATION_JSON, @@ -1176,34 +907,13 @@ public interface ApplicationManagementPublisherAPI { name = "pubAppReleaseWrapper", value = "Application release wrapper which is going to update.", required = true) - @Multipart( - value = "pubAppReleaseWrapper", - type = "application/json") WebAppReleaseWrapper webAppReleaseWrapper, - @ApiParam( - name = "icon", - value = "Icon file of the application release.") - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "banner file of the application release.") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "First screenshot of the uploading application") - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Second screenshot 2 of the uploading application") - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Third screenshot of the uploading application") - @Multipart(value = "screenshot3") Attachment screenshot3); + WebAppReleaseWrapper webAppReleaseWrapper + ); @PUT @Path("/custom-app-release/{uuid}") @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.MULTIPART_FORM_DATA) + @Consumes(MediaType.APPLICATION_JSON) @ApiOperation( consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.APPLICATION_JSON, @@ -1242,34 +952,7 @@ public interface ApplicationManagementPublisherAPI { name = "entAppReleaseWrapper", value = "Application release wrapper which is going to update.", required = true) - @Multipart( - value = "entAppReleaseWrapper", - type = "application/json") CustomAppReleaseWrapper customAppReleaseWrapper, - @ApiParam( - name = "binaryFile", - value = "Application installer file.", - required = true) - @Multipart(value = "binaryFile") Attachment binaryFile, - @ApiParam( - name = "icon", - value = "Icon file of the application release.") - @Multipart(value = "icon") Attachment iconFile, - @ApiParam( - name = "banner", - value = "banner file of the application release.") - @Multipart(value = "banner") Attachment bannerFile, - @ApiParam( - name = "screenshot1", - value = "First screenshot of the uploading application") - @Multipart(value = "screenshot1") Attachment screenshot1, - @ApiParam( - name = "screenshot2", - value = "Second screenshot 2 of the uploading application") - @Multipart(value = "screenshot2") Attachment screenshot2, - @ApiParam( - name = "screenshot3", - value = "Third screenshot of the uploading application") - @Multipart(value = "screenshot3") Attachment screenshot3); + CustomAppReleaseWrapper customAppReleaseWrapper); @GET @Path("/life-cycle/state-changes/{uuid}") @@ -1634,7 +1317,7 @@ public interface ApplicationManagementPublisherAPI { name = "appId", value = "application Id", required = true) - List tagNames + List tagNames ); @GET diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java index c39c9b8ea79..002c54de469 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -38,20 +38,14 @@ 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.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; import java.util.List; -/** - * This is the application registration service that exposed for apimApplicationRegistration - */ - @SwaggerDefinition( info = @Info( version = "1.0.0", - title = "Service Provider Application Management Publisher Service", + title = "Service Provider Application Management Service", extensions = { @Extension(properties = { @ExtensionProperty(name = "name", value = "SPApplicationService"), @@ -67,28 +61,28 @@ import java.util.List; scopes = { @Scope( name = "view a service provider applications", - description = "Get application details", + description = "Get service provider application details", key = "perm:app:publisher:service-provider:view", roles = {"Internal/devicemgt-user"}, permissions = {"/app-mgt/publisher/service-provider/application/view"} ), @Scope( name = "Create a service provider application", - description = "Update an application", + description = "Create an application and attach (map) to service provider", key = "perm:app:publisher:service-provider:create", roles = {"Internal/devicemgt-user"}, permissions = {"/app-mgt/publisher/service-provider/application/create"} ), @Scope( name = "Attach a service provider application", - description = "Update an application", + description = "Map an application to service provider", key = "perm:app:publisher:service-provider:attach", roles = {"Internal/devicemgt-user"}, permissions = {"/app-mgt/publisher/service-provider/application/attach"} ), @Scope( name = "Detach a service provider application", - description = "Update an application", + description = "Remove an application from service provider", key = "perm:app:publisher:service-provider:detach", roles = {"Internal/devicemgt-user"}, permissions = {"/app-mgt/publisher/service-provider/application/detach"} @@ -102,18 +96,14 @@ public interface SPApplicationService { String SCOPE = "scope"; - /** - * This method is used to register an APIM application for tenant domain. - */ @GET @Produces(MediaType.APPLICATION_JSON) @Path("/identity-servers") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "get all identity servers", + tags = "Identity Server Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") @@ -128,9 +118,8 @@ public interface SPApplicationService { @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "get identity server by id", + tags = "Identity Server Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") @@ -148,9 +137,9 @@ public interface SPApplicationService { @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "get service providers by identity server id", + notes = "This will get service providers with the existing applications", + tags = "Service Provider Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") @@ -160,15 +149,15 @@ public interface SPApplicationService { Response getServiceProviders(@QueryParam("limit") Integer limit, @QueryParam("offset") Integer offset, @PathParam("identity-server-id") int identityServerId); - @Path("/{identity-server-id}/{service-provider-id}/attach") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/applications") @POST @Produces(MediaType.APPLICATION_JSON) @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "POST", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "map application to service provider", + notes = "This will map a given list application ids with the given service provider id", + tags = "Service Provider Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:attach") @@ -181,15 +170,15 @@ public interface SPApplicationService { /** * This method is used to register an APIM application for tenant domain. */ - @Path("/{identity-server-id}/{service-provider-id}/detach") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/delete/applications") @POST @Produces(MediaType.APPLICATION_JSON) @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "POST", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "Remove mapping with service provider of the given application ids", + notes = "This will remove applications from service provider", + tags = "Service Provider Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:detach") @@ -202,15 +191,15 @@ public interface SPApplicationService { /** * This method is used to register an APIM application for tenant domain. */ - @Path("/{identity-server-id}/{service-provider-id}/create/ent-app") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/ent-app") @POST @Produces(MediaType.APPLICATION_JSON) @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "POST", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "Create enterprise application and attach to service provider", + notes = "This will get create an enterprise application and map with service provider", + tags = "Service Provider Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:create") @@ -220,19 +209,18 @@ public interface SPApplicationService { Response createEntApp(@PathParam("identity-server-id") int identityServerId, @PathParam("service-provider-id") String serviceProviderId, ApplicationWrapper app); - /** * This method is used to register an APIM application for tenant domain. */ - @Path("/{identity-server-id}/{service-provider-id}/create/public-app") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/public-app") @POST @Produces(MediaType.APPLICATION_JSON) @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "POST", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "Create public application and attach to service provider", + notes = "This will get create a public application and map with service provider", + tags = "Service Provider Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:create") @@ -242,15 +230,15 @@ public interface SPApplicationService { Response createPubApp(@PathParam("identity-server-id") int identityServerId, @PathParam("service-provider-id") String serviceProviderId, PublicAppWrapper app); - @Path("/{identity-server-id}/{service-provider-id}/create/web-app") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/web-app") @POST @Produces(MediaType.APPLICATION_JSON) @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "POST", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "Create web application and attach to service provider", + notes = "This will get create a web application and map with service provider", + tags = "Service Provider Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:create") @@ -260,15 +248,15 @@ public interface SPApplicationService { Response createWebApp(@PathParam("identity-server-id") int identityServerId, @PathParam("service-provider-id") String serviceProviderId, WebAppWrapper app); - @Path("/{identity-server-id}/{service-provider-id}/create/custom-app") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/custom-app") @POST @Produces(MediaType.APPLICATION_JSON) @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "POST", - value = "get the application of requesting application id and state", - notes = "This will get the application identified by the application id and state, if exists", - tags = "ApplicationDTO Management", + value = "Create custom application and attach to service provider", + notes = "This will get create an custom application and map with service provider", + tags = "Service Provider Management", extensions = { @Extension(properties = { @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:create") diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java index 9aaeeb1d5a7..561a65b7674 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java @@ -16,14 +16,15 @@ */ package io.entgra.application.mgt.publisher.api.services.impl; -import io.entgra.application.mgt.common.dto.ApplicationDTO; -import io.entgra.application.mgt.common.dto.ApplicationReleaseDTO; +import io.entgra.application.mgt.common.ApplicationArtifact; +import io.entgra.application.mgt.common.ApplicationList; +import io.entgra.application.mgt.common.Base64File; +import io.entgra.application.mgt.common.Filter; +import io.entgra.application.mgt.common.LifecycleChanger; import io.entgra.application.mgt.common.exception.ResourceManagementException; +import io.entgra.application.mgt.core.util.ApplicationManagementUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.cxf.jaxrs.ext.multipart.Attachment; -import org.apache.cxf.jaxrs.ext.multipart.Multipart; -import io.entgra.application.mgt.common.*; import io.entgra.application.mgt.common.LifecycleState; import io.entgra.application.mgt.common.exception.LifecycleManagementException; import io.entgra.application.mgt.common.exception.RequestValidatingException; @@ -45,20 +46,12 @@ import io.entgra.application.mgt.core.exception.BadRequestException; import io.entgra.application.mgt.core.exception.ForbiddenException; import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.application.mgt.core.util.APIUtil; -import io.entgra.application.mgt.core.util.Constants; import io.entgra.application.mgt.publisher.api.services.ApplicationManagementPublisherAPI; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.services.ApplicationManager; import io.entgra.application.mgt.core.exception.NotFoundException; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import javax.activation.DataHandler; import javax.validation.Valid; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -173,36 +166,12 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } @POST - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/ent-app") public Response createEntApp( - @Multipart("application") ApplicationWrapper applicationWrapper, - @Multipart("binaryFile") Attachment binaryFile, - @Multipart("icon") Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart("screenshot1") Attachment screenshot1, - @Multipart("screenshot2") Attachment screenshot2, - @Multipart("screenshot3") Attachment screenshot3) { - ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); + ApplicationWrapper applicationWrapper) { try { - applicationManager.validateAppCreatingRequest(applicationWrapper, true); - applicationManager.validateReleaseCreatingRequest(applicationWrapper.getEntAppReleaseWrappers().get(0), - applicationWrapper.getDeviceType()); - applicationManager.validateBinaryArtifact(binaryFile); - applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); - - // Created new Ent App - ApplicationDTO applicationDTO = applicationManager.uploadEntAppReleaseArtifacts(applicationWrapper, - constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList)); - Application application = applicationManager.persistApplication(applicationDTO); - if (application != null) { - return Response.status(Response.Status.CREATED).entity(application).build(); - } else { - String msg = "Application creation is failed"; - log.error(msg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } + return createApplication(applicationWrapper); } catch (BadRequestException e) { String msg = "Found incompatible payload with ent. app creating request."; log.error(msg, e); @@ -219,34 +188,12 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } @POST - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/web-app") public Response createWebApp( - @Multipart("webapp") WebAppWrapper webAppWrapper, - @Multipart("icon") Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart("screenshot1") Attachment screenshot1, - @Multipart("screenshot2") Attachment screenshot2, - @Multipart("screenshot3") Attachment screenshot3) { - ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); + WebAppWrapper webAppWrapper) { try { - applicationManager.validateAppCreatingRequest(webAppWrapper, true); - applicationManager - .validateReleaseCreatingRequest(webAppWrapper.getWebAppReleaseWrappers().get(0), Constants.ANY); - applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); - - // Created new Web App - ApplicationDTO applicationDTO = applicationManager.uploadWebAppReleaseArtifacts(webAppWrapper, - constructApplicationArtifact(null, iconFile, bannerFile, attachmentList)); - Application application = applicationManager.persistApplication(applicationDTO); - if (application != null) { - return Response.status(Response.Status.CREATED).entity(application).build(); - } else { - String msg = "Web app creation is failed"; - log.error(msg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } + return createApplication(webAppWrapper); } catch (BadRequestException e) { String msg = "Found incompatible payload with web app creating request."; log.error(msg, e); @@ -263,34 +210,12 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } @POST - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/public-app") public Response createPubApp( - @Multipart("public-app") PublicAppWrapper publicAppWrapper, - @Multipart("icon") Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart("screenshot1") Attachment screenshot1, - @Multipart("screenshot2") Attachment screenshot2, - @Multipart("screenshot3") Attachment screenshot3) { - ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); + PublicAppWrapper publicAppWrapper) { try { - applicationManager.validateAppCreatingRequest(publicAppWrapper, true); - applicationManager.validateReleaseCreatingRequest(publicAppWrapper.getPublicAppReleaseWrappers().get(0), - publicAppWrapper.getDeviceType()); - applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); - - // Created new Public App - ApplicationDTO applicationDTO = applicationManager.uploadPublicAppReleaseArtifacts(publicAppWrapper, - constructApplicationArtifact(null, iconFile, bannerFile, attachmentList)); - Application application = applicationManager.persistApplication(applicationDTO); - if (application != null) { - return Response.status(Response.Status.CREATED).entity(application).build(); - } else { - String msg = "Web app creation is failed"; - log.error(msg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } + return createApplication(publicAppWrapper); } catch (BadRequestException e) { String msg = "Found incompatible payload with pub app creating request."; log.error(msg, e); @@ -307,36 +232,12 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } @POST - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/custom-app") public Response createCustomApp( - @Multipart("application") CustomAppWrapper customAppWrapper, - @Multipart("binaryFile") Attachment binaryFile, - @Multipart("icon") Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart("screenshot1") Attachment screenshot1, - @Multipart("screenshot2") Attachment screenshot2, - @Multipart("screenshot3") Attachment screenshot3) { - ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); + CustomAppWrapper customAppWrapper) { try { - applicationManager.validateAppCreatingRequest(customAppWrapper, true); - applicationManager.validateReleaseCreatingRequest(customAppWrapper.getCustomAppReleaseWrappers().get(0), - customAppWrapper.getDeviceType()); - applicationManager.validateBinaryArtifact(binaryFile); - applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); - - // Created new Custom App - ApplicationDTO applicationDTO = applicationManager.uploadCustomAppReleaseArtifactsAndConstructAppDTO(customAppWrapper, - constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList)); - Application application = applicationManager.persistApplication(applicationDTO); - if (application != null) { - return Response.status(Response.Status.CREATED).entity(application).build(); - } else { - String msg = "Custom app creation is failed"; - log.error(msg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } + return createApplication(customAppWrapper); } catch (BadRequestException e) { String msg = "Found incompatible payload with custom app creating request."; log.error(msg, e); @@ -353,28 +254,16 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } @POST - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/{deviceType}/ent-app/{appId}") public Response createEntAppRelease( @PathParam("deviceType") String deviceTypeName, @PathParam("appId") int appId, - @Multipart("applicationRelease") EntAppReleaseWrapper entAppReleaseWrapper, - @Multipart("binaryFile") Attachment binaryFile, - @Multipart("icon") Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart("screenshot1") Attachment screenshot1, - @Multipart("screenshot2") Attachment screenshot2, - @Multipart("screenshot3") Attachment screenshot3) { + EntAppReleaseWrapper entAppReleaseWrapper) { try { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - applicationManager.validateBinaryArtifact(binaryFile); - ApplicationDTO applicationDTO = applicationManager.getApplication(appId); - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); - ApplicationArtifact artifact = constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList); - ApplicationReleaseDTO applicationReleaseDTO = applicationManager.uploadEntAppReleaseArtifacts( - entAppReleaseWrapper, artifact, deviceType.getName()); - ApplicationRelease release = applicationManager.createRelease(applicationDTO, applicationReleaseDTO, ApplicationType.ENTERPRISE); + applicationManager.validateEntAppReleaseCreatingRequest(entAppReleaseWrapper, deviceTypeName); + ApplicationRelease release = applicationManager.createEntAppRelease(appId, entAppReleaseWrapper); return Response.status(Response.Status.CREATED).entity(release).build(); } catch (RequestValidatingException e) { String msg = "Error occurred while validating binaryArtifact"; @@ -388,29 +277,19 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } @POST - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/{deviceType}/public-app/{appId}") @Override public Response createPubAppRelease( @PathParam("deviceType") String deviceTypeName, @PathParam("appId") int appId, - @Multipart("applicationRelease") PublicAppReleaseWrapper publicAppReleaseWrapper, - @Multipart("icon") Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart("screenshot1") Attachment screenshot1, - @Multipart("screenshot2") Attachment screenshot2, - @Multipart("screenshot3") Attachment screenshot3) { + PublicAppReleaseWrapper publicAppReleaseWrapper) { try { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - ApplicationDTO applicationDTO = applicationManager.getApplication(appId); - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); - ApplicationArtifact artifact = constructApplicationArtifact(null, iconFile, bannerFile, attachmentList); - ApplicationReleaseDTO applicationReleaseDTO = applicationManager.uploadPubAppReleaseArtifacts( - publicAppReleaseWrapper, artifact, deviceType.getName()); - ApplicationRelease release = applicationManager.createRelease(applicationDTO, applicationReleaseDTO, ApplicationType.PUBLIC); - return Response.status(Response.Status.CREATED).entity(release).build(); + applicationManager.validatePublicAppReleaseCreatingRequest(publicAppReleaseWrapper, deviceTypeName); + ApplicationRelease applicationRelease = applicationManager.createPubAppRelease(appId, publicAppReleaseWrapper); + return Response.status(Response.Status.CREATED).entity(applicationRelease).build(); } catch (ApplicationManagementException e) { String msg = "Error occurred while creating application release for the application with the id " + appId; log.error(msg, e); @@ -419,29 +298,25 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem String msg = "Error occurred while uploading application release artifacts"; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (RequestValidatingException e) { + String msg = "Invalid payload found in public app release create request"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } } @POST - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/web-app/{appId}") @Override public Response createWebAppRelease( @PathParam("appId") int appId, - @Multipart("applicationRelease") WebAppReleaseWrapper webAppReleaseWrapper, - @Multipart("icon") Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart("screenshot1") Attachment screenshot1, - @Multipart("screenshot2") Attachment screenshot2, - @Multipart("screenshot3") Attachment screenshot3) { + WebAppReleaseWrapper webAppReleaseWrapper) { try { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - ApplicationDTO applicationDTO = applicationManager.getApplication(appId); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); - ApplicationArtifact artifact = constructApplicationArtifact(null, iconFile, bannerFile, attachmentList); - ApplicationReleaseDTO applicationReleaseDTO = applicationManager.uploadWebAppReleaseArtifacts(webAppReleaseWrapper, artifact); - ApplicationRelease release = applicationManager.createRelease(applicationDTO, applicationReleaseDTO, ApplicationType.WEB_CLIP); - return Response.status(Response.Status.CREATED).entity(release).build(); + applicationManager.validateWebAppReleaseCreatingRequest(webAppReleaseWrapper); + ApplicationRelease applicationRelease= applicationManager.createWebAppRelease(appId, webAppReleaseWrapper); + return Response.status(Response.Status.CREATED).entity(applicationRelease).build(); } catch (ResourceManagementException e) { String msg = "Error occurred while uploading application release artifacts"; log.error(msg, e); @@ -450,33 +325,25 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem String msg = "Error occurred while creating application release for the application with the id " + appId; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (RequestValidatingException e) { + String msg = "Invalid payload found in web app release create request"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } } @POST - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/{deviceType}/custom-app/{appId}") @Override public Response createCustomAppRelease( @PathParam("deviceType") String deviceTypeName, @PathParam("appId") int appId, - @Multipart("applicationRelease") CustomAppReleaseWrapper customAppReleaseWrapper, - @Multipart("binaryFile") Attachment binaryFile, - @Multipart("icon") Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart("screenshot1") Attachment screenshot1, - @Multipart("screenshot2") Attachment screenshot2, - @Multipart("screenshot3") Attachment screenshot3) { + CustomAppReleaseWrapper customAppReleaseWrapper) { try { - APIUtil.getApplicationManager().validateBinaryArtifact(binaryFile); ApplicationManager applicationManager = APIUtil.getApplicationManager(); - ApplicationDTO applicationDTO = applicationManager.getApplication(appId); - DeviceType deviceType = APIUtil.getDeviceTypeData(applicationDTO.getDeviceTypeId()); - List attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3); - ApplicationArtifact artifact = constructApplicationArtifact(binaryFile, iconFile, bannerFile, attachmentList); - ApplicationReleaseDTO applicationReleaseDTO = applicationManager.uploadCustomAppReleaseArtifacts( - customAppReleaseWrapper, artifact, deviceType.getName()); - ApplicationRelease release = applicationManager.createRelease(applicationDTO, applicationReleaseDTO, ApplicationType.CUSTOM); + applicationManager.validateCustomAppReleaseCreatingRequest(customAppReleaseWrapper, deviceTypeName); + ApplicationRelease release = applicationManager.createCustomAppRelease(appId, customAppReleaseWrapper); return Response.status(Response.Status.CREATED).entity(release).build(); } catch (RequestValidatingException e) { String msg = "Error occurred while validating binaryArtifact"; @@ -521,21 +388,20 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Override @PUT - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/image-artifacts/{uuid}") public Response updateApplicationImageArtifacts( @PathParam("uuid") String applicationReleaseUuid, - @Multipart(value = "icon", required = false) Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart(value = "screenshot1", required = false) Attachment screenshot1, - @Multipart(value = "screenshot2", required = false) Attachment screenshot2, - @Multipart(value = "screenshot3", required = false) Attachment screenshot3) { + Base64File iconFile, + Base64File bannerFile, + List screenshots) { try { - List attachments = constructAttachmentList(screenshot1, screenshot2, screenshot3); + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(iconFile, screenshots, + null, bannerFile); ApplicationManager applicationManager = APIUtil.getApplicationManager(); applicationManager.updateApplicationImageArtifact(applicationReleaseUuid, - constructApplicationArtifact(null, iconFile, bannerFile, attachments)); + artifact); return Response.status(Response.Status.OK) .entity("Successfully uploaded artifacts for the application " + applicationReleaseUuid).build(); } catch (NotFoundException e) { @@ -554,18 +420,19 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Override @PUT - @Consumes({"multipart/mixed", MediaType.MULTIPART_FORM_DATA}) + @Consumes(MediaType.APPLICATION_JSON) @Path("/ent-app-artifact/{deviceType}/{uuid}") public Response updateApplicationArtifact( @PathParam("deviceType") String deviceType, @PathParam("uuid") String applicationReleaseUuid, - @Multipart("binaryFile") Attachment binaryFile) { + Base64File binaryFile) { try { ApplicationManager applicationManager = APIUtil.getApplicationManager(); applicationManager.validateBinaryArtifact(binaryFile); applicationManager.updateApplicationArtifact(deviceType, applicationReleaseUuid, - constructApplicationArtifact(binaryFile, null, null, null)); + ApplicationManagementUtil.constructApplicationArtifact(null, null, + binaryFile, null)); return Response.status(Response.Status.OK) .entity("Successfully uploaded artifacts for the application release. UUID is " + applicationReleaseUuid).build(); @@ -622,19 +489,13 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Path("/ent-app-release/{uuid}") public Response updateEntAppRelease( @PathParam("uuid") String applicationUUID, - @Multipart("applicationRelease") EntAppReleaseWrapper entAppReleaseWrapper, - @Multipart(value = "binaryFile", required = false) Attachment binaryFile, - @Multipart(value = "icon", required = false) Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart(value = "screenshot1", required = false) Attachment screenshot1, - @Multipart(value = "screenshot2", required = false) Attachment screenshot2, - @Multipart(value = "screenshot3", required = false) Attachment screenshot3) { + EntAppReleaseWrapper entAppReleaseWrapper) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List screenshots = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(entAppReleaseWrapper.getIcon(), + entAppReleaseWrapper.getScreenshots(), entAppReleaseWrapper.getBinaryFile(), entAppReleaseWrapper.getBanner()); ApplicationRelease applicationRelease = applicationManager - .updateEntAppRelease(applicationUUID, entAppReleaseWrapper, - constructApplicationArtifact(binaryFile, iconFile, bannerFile, screenshots)); + .updateEntAppRelease(applicationUUID, entAppReleaseWrapper, artifact); if (applicationRelease == null) { String msg ="Ent app release updating is failed. Please contact the administrator. Application release " + "UUID: " + applicationUUID; @@ -669,18 +530,13 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Path("/public-app-release/{uuid}") public Response updatePubAppRelease( @PathParam("uuid") String applicationUUID, - @Multipart("applicationRelease") PublicAppReleaseWrapper publicAppReleaseWrapper, - @Multipart(value = "icon", required = false) Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart(value = "screenshot1", required = false) Attachment screenshot1, - @Multipart(value = "screenshot2", required = false) Attachment screenshot2, - @Multipart(value = "screenshot3", required = false) Attachment screenshot3) { + PublicAppReleaseWrapper publicAppReleaseWrapper) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List screenshots = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(publicAppReleaseWrapper.getIcon(), + publicAppReleaseWrapper.getScreenshots(), null, publicAppReleaseWrapper.getBanner()); ApplicationRelease applicationRelease = applicationManager - .updatePubAppRelease(applicationUUID, publicAppReleaseWrapper, - constructApplicationArtifact(null, iconFile, bannerFile, screenshots)); + .updatePubAppRelease(applicationUUID, publicAppReleaseWrapper, artifact); if (applicationRelease == null) { String msg ="Public app release updating is failed. Please contact the administrator. " + "Application release UUID: " + applicationUUID + ", Supported device type:"; @@ -714,18 +570,13 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Path("/web-app-release/{uuid}") public Response updateWebAppRelease( @PathParam("uuid") String applicationUUID, - @Multipart("applicationRelease") WebAppReleaseWrapper webAppReleaseWrapper, - @Multipart(value = "icon", required = false) Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart(value = "screenshot1", required = false) Attachment screenshot1, - @Multipart(value = "screenshot2", required = false) Attachment screenshot2, - @Multipart(value = "screenshot3", required = false) Attachment screenshot3) { + WebAppReleaseWrapper webAppReleaseWrapper) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List screenshots = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(webAppReleaseWrapper.getIcon(), + webAppReleaseWrapper.getScreenshots(), null, webAppReleaseWrapper.getBanner()); ApplicationRelease applicationRelease = applicationManager - .updateWebAppRelease(applicationUUID, webAppReleaseWrapper, - constructApplicationArtifact(null, iconFile, bannerFile, screenshots)); + .updateWebAppRelease(applicationUUID, webAppReleaseWrapper, artifact); if (applicationRelease == null) { String msg ="web app release updating is failed. Please contact the administrator. Application " + "release UUID: " + applicationUUID; @@ -758,19 +609,13 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Path("/custom-app-release/{uuid}") public Response updateCustomAppRelease( @PathParam("uuid") String applicationUUID, - @Multipart("applicationRelease") CustomAppReleaseWrapper customAppReleaseWrapper, - @Multipart(value = "binaryFile", required = false) Attachment binaryFile, - @Multipart(value = "icon", required = false) Attachment iconFile, - @Multipart(value = "banner", required = false) Attachment bannerFile, - @Multipart(value = "screenshot1", required = false) Attachment screenshot1, - @Multipart(value = "screenshot2", required = false) Attachment screenshot2, - @Multipart(value = "screenshot3", required = false) Attachment screenshot3) { + CustomAppReleaseWrapper customAppReleaseWrapper) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - List screenshots = constructAttachmentList(screenshot1, screenshot2, screenshot3); try { + ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(customAppReleaseWrapper.getIcon(), + customAppReleaseWrapper.getScreenshots(), customAppReleaseWrapper.getBinaryFile(), customAppReleaseWrapper.getBanner()); ApplicationRelease applicationRelease = applicationManager - .updateCustomAppRelease(applicationUUID, customAppReleaseWrapper, - constructApplicationArtifact(binaryFile, iconFile, bannerFile, screenshots)); + .updateCustomAppRelease(applicationUUID, customAppReleaseWrapper, artifact); if (applicationRelease == null) { String msg ="Custom app release updating is failed. Please contact the administrator. Application " + "release UUID: " + applicationUUID; @@ -1019,134 +864,16 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } } - /*** - * Construct the screenshot list by evaluating the availability of each screenshot. - * - * @param screenshot1 First Screenshot - * @param screenshot2 Second Screenshot - * @param screenshot3 Third Screenshot - * @return List of {@link Attachment} - */ - private List constructAttachmentList(Attachment screenshot1, Attachment screenshot2, - Attachment screenshot3) { - List attachments = new ArrayList<>(); - if (screenshot1 != null) { - attachments.add(screenshot1); - } - if (screenshot2 != null) { - attachments.add(screenshot2); - } - if (screenshot3 != null) { - attachments.add(screenshot3); - } - return attachments; - } - - /*** - * This method can be used to construct {@link ApplicationArtifact} - * - * @param binaryFile binary file of the application release - * @param iconFile icon file of the application release - * @param bannerFile banner file of the application release - * @param attachmentList list of screenshot of the application release - * @return {@link ApplicationArtifact} - * @throws ApplicationManagementException if an error occurs when reading the attached data. - */ - private ApplicationArtifact constructApplicationArtifact(Attachment binaryFile, Attachment iconFile, - Attachment bannerFile, List attachmentList) throws ApplicationManagementException { - try { - ApplicationArtifact applicationArtifact = new ApplicationArtifact(); - DataHandler dataHandler; - if (binaryFile != null) { - dataHandler = binaryFile.getDataHandler(); - InputStream installerStream = dataHandler.getInputStream(); - String installerFileName = dataHandler.getName(); - if (installerStream == null) { - String msg = "Stream of the application release installer is null. Hence can't proceed. Please " - + "verify the installer file."; - log.error(msg); - throw new BadRequestException(msg); - } - if (installerFileName == null) { - String msg = "Installer file name retrieving is failed.. Hence can't proceed. Please verify the " - + "installer file."; - log.error(msg); - throw new BadRequestException(msg); - } - applicationArtifact.setInstallerName(installerFileName.replaceAll("\\s", "")); - applicationArtifact.setInstallerStream(installerStream); - } - - if (iconFile != null) { - dataHandler = iconFile.getDataHandler(); - String iconFileName = dataHandler.getName(); - InputStream iconStream = dataHandler.getInputStream(); - - if (iconStream == null) { - String msg = "Stream of the application release icon is null. Hence can't proceed. Please " - + "verify the uploaded icon file."; - log.error(msg); - throw new BadRequestException(msg); - } - if (iconFileName == null) { - String msg = "Icon file name retrieving is failed.. Hence can't proceed. Please verify the " - + "icon file."; - log.error(msg); - throw new BadRequestException(msg); - } - applicationArtifact.setIconName(iconFileName); - applicationArtifact.setIconStream(iconStream); - } - - if (bannerFile != null) { - dataHandler = bannerFile.getDataHandler(); - String bannerFileName = dataHandler.getName(); - InputStream bannerStream = dataHandler.getInputStream(); - if (bannerStream == null) { - String msg = "Stream of the application release banner is null. Hence can't proceed. Please " - + "verify the uploaded banner file."; - log.error(msg); - throw new BadRequestException(msg); - } - if (bannerFileName == null) { - String msg = "Banner file name retrieving is failed.. Hence can't proceed. Please verify the " - + "banner file."; - log.error(msg); - throw new BadRequestException(msg); - } - applicationArtifact.setBannerName(bannerFileName); - applicationArtifact.setBannerStream(bannerStream); - } - - if (attachmentList != null && !attachmentList.isEmpty()) { - Map screenshotData = new TreeMap<>(); - for (Attachment sc : attachmentList) { - dataHandler = sc.getDataHandler(); - String screenshotFileName = dataHandler.getName(); - InputStream screenshotStream = dataHandler.getInputStream(); - if (screenshotStream == null) { - String msg = - "Stream of one of the application release screenshot is null. Hence can't proceed. Please " - + "verify the uploaded screenshots."; - log.error(msg); - throw new BadRequestException(msg); - } - if (screenshotFileName == null) { - String msg = - "Screenshot file name retrieving is failed for one screenshot. Hence can't proceed. " - + "Please verify the screenshots."; - log.error(msg); - throw new BadRequestException(msg); - } - screenshotData.put(screenshotFileName, screenshotStream); - } - applicationArtifact.setScreenshots(screenshotData); - } - return applicationArtifact; - } catch (IOException e) { - String msg = "Error occurred when reading attachment data."; - log.error(msg, e); - throw new ApplicationManagementException(msg); + public Response createApplication(T appWrapper) throws ApplicationManagementException, RequestValidatingException { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + applicationManager.validateAppCreatingRequest(appWrapper); + Application application = applicationManager.createApplication(appWrapper); + if (application != null) { + return Response.status(Response.Status.CREATED).entity(application).build(); + } else { + String msg = "Application creation is failed"; + log.error(msg); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } } diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java index 79a86655218..52696b09813 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -35,7 +35,6 @@ import io.entgra.application.mgt.publisher.api.services.SPApplicationService; import io.entgra.application.mgt.publisher.api.services.util.SPAppRequestHandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; @@ -46,7 +45,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; - @Produces(MediaType.APPLICATION_JSON) @Path("/identity-server-applications") public class SPApplicationServiceImpl implements SPApplicationService { @@ -90,7 +88,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { try { SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); SPApplicationListResponse applications = SPAppRequestHandlerUtil. - getServiceProvidersFromIdentityServer(identityServerId, limit, offset); + retrieveSPApplications(identityServerId, limit, offset); spAppManager.addExistingApps(identityServerId, applications.getApplications()); return Response.status(Response.Status.OK).entity(applications).build(); } catch (ApplicationManagementException e) { @@ -100,7 +98,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { } } - @Path("/{identity-server-id}/{service-provider-id}/attach") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/applications") @POST @Override public Response attachApps(@PathParam("identity-server-id") int identityServerId, @@ -118,7 +116,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).build(); } - @Path("/{identity-server-id}/{service-provider-id}/detach") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/delete/applications") @POST @Override public Response detachApps(@PathParam("identity-server-id") int identityServerId, @@ -136,7 +134,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).build(); } - @Path("/{identity-server-id}/{service-provider-id}/create/ent-app") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/ent-app") @POST @Override public Response createEntApp(@PathParam("identity-server-id") int identityServerId, @@ -144,7 +142,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return createSPApplication(identityServerId, serviceProviderId, app); } - @Path("/{identity-server-id}/{service-provider-id}/create/public-app") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/public-app") @POST @Override public Response createPubApp(@PathParam("identity-server-id") int identityServerId, @@ -152,7 +150,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return createSPApplication(identityServerId, serviceProviderId, app); } - @Path("/{identity-server-id}/{service-provider-id}/create/web-app") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/web-app") @POST @Override public Response createWebApp(@PathParam("identity-server-id") int identityServerId, @@ -160,7 +158,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return createSPApplication(identityServerId, serviceProviderId, app); } - @Path("/{identity-server-id}/{service-provider-id}/create/custom-app") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/custom-app") @POST @Override public Response createCustomApp(@PathParam("identity-server-id") int identityServerId, @@ -168,11 +166,20 @@ public class SPApplicationServiceImpl implements SPApplicationService { return createSPApplication(identityServerId, serviceProviderId, app); } - private Response createSPApplication(int identityServerId, String serviceProviderId, T appWrapper) { + /** + * Validates and creates service provider application + * + * @param identityServerId id of the identity server + * @param spUID uid of the service provider + * @param appWrapper application wrapper + * @param application wrapper class + * @return Response + */ + private Response createSPApplication(int identityServerId, String spUID, T appWrapper) { try { - validateServiceProviderUID(identityServerId, serviceProviderId); + validateServiceProviderUID(identityServerId, spUID); SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); - Application createdApp = spApplicationManager.createSPApplication(appWrapper, identityServerId, serviceProviderId); + Application createdApp = spApplicationManager.createSPApplication(appWrapper, identityServerId, spUID); return Response.status(Response.Status.CREATED).entity(createdApp).build(); } catch (BadRequestException e) { String msg = "Found incompatible payload with create service provider app request."; @@ -190,6 +197,13 @@ public class SPApplicationServiceImpl implements SPApplicationService { } } + /** + * Responsible for validating service provider in requests + * + * @param identityServerId identity server id of the service provider + * @param spUID uid of the service provider + * @throws ApplicationManagementException + */ private void validateServiceProviderUID(int identityServerId, String spUID) throws ApplicationManagementException { try { @@ -207,5 +221,4 @@ public class SPApplicationServiceImpl implements SPApplicationService { } } - } \ No newline at end of file diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java index 307cb91342f..b9d6b60e991 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.publisher.api.services.util; import com.google.gson.Gson; @@ -27,19 +45,26 @@ public class SPAppRequestHandlerUtil { private static final Log log = LogFactory.getLog(SPAppRequestHandlerUtil.class); + /** + * Check if service provider application exists + * + * @param identityServerId id of the identity server + * @param spAppId uid of the service provider + * @return if service provider exist + * @throws ApplicationManagementException + */ public static boolean isSPApplicationExist(int identityServerId, String spAppId) throws ApplicationManagementException { SPApplication application = retrieveSPApplication(identityServerId, spAppId); - if (application == null) { - return false; - } - return true; - } - - public static SPApplicationListResponse getServiceProvidersFromIdentityServer(int identityServerId, Integer limit, Integer offSet) - throws ApplicationManagementException { - return retrieveSPApplications(identityServerId, limit, offSet); + return application != null; } + /** + * Get service provider by identity server id and service provider uid + * @param identityServerId id of the identity server + * @param spAppId uid of service provider to be retrieved + * @return {@link SPApplication} + * @throws ApplicationManagementException + */ public static SPApplication retrieveSPApplication(int identityServerId, String spAppId) throws ApplicationManagementException { IdentityServer identityServer = getIdentityServer(identityServerId); @@ -74,7 +99,13 @@ public class SPAppRequestHandlerUtil { } } - + /** + * Retrieve service provider apps from identity server + * + * @param identityServerId id of the identity server + * @return {@link SPApplicationListResponse} + * @throws ApplicationManagementException + */ public static SPApplicationListResponse retrieveSPApplications(int identityServerId, Integer limit, Integer offset) throws ApplicationManagementException { IdentityServer identityServer = getIdentityServer(identityServerId); @@ -113,17 +144,23 @@ public class SPAppRequestHandlerUtil { } } + /** + * + * @param identityServerId id of the identity server + * @return {@link IdentityServer} + * @throws ApplicationManagementException + */ public static IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException { SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); return spApplicationManager.getIdentityServer(identityServerId); } - public static HttpResponse invokeISAPI(IdentityServer identityServer, HttpClient client, HttpRequestBase request) throws IOException { + private static HttpResponse invokeISAPI(IdentityServer identityServer, HttpClient client, HttpRequestBase request) throws IOException { setBasicAuthHeader(identityServer, request); return client.execute(request); } - public static void setBasicAuthHeader(IdentityServer identityServer, HttpRequestBase request) { + private static void setBasicAuthHeader(IdentityServer identityServer, HttpRequestBase request) { String basicAuthHeader = HttpUtil.getBasicAuthBase64Header(identityServer.getUserName(), identityServer.getPassword()); request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java index 2f9a7207b89..0ff71608f44 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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.wso2.carbon.device.mgt.core.common; public class Constants { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java index 28a5084003b..dc9ce7cc588 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. 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.wso2.carbon.device.mgt.core.common.util; import java.io.ByteArrayInputStream; @@ -20,5 +38,47 @@ public class FileUtil { return new ByteArrayInputStream(base64Bytes); } + /** + * This generates file name with a suffix depending on the duplicate name count, useful when saving + * files with the same name + * + * @param fileNameCount File count + * @return generated file name with suffix + */ + public static String generateDuplicateFileName(String fileName, int fileNameCount) { + String suffix = generateDuplicateFileNameSuffix(fileNameCount); + String fileNameWithoutExtension = extractFileNameWithoutExtension(fileName); + String fileNameWithSuffix = fileNameWithoutExtension + suffix; + fileNameWithSuffix = fileNameWithSuffix + '.' + extractFileExtension(fileName); + return fileNameWithSuffix; + } + + /** + * This generates file name suffix for duplicate file names. For example, + * if it's the first file, the count is 1 in which case the name doesn't have any suffix + * else it adds suffix with (count - 1) + * + * @param fileNameCount File count + * @return generated file name suffix + */ + private static String generateDuplicateFileNameSuffix(int fileNameCount) { + String suffix = ""; + if (fileNameCount < 1) { + throw new IllegalArgumentException("file name count must be above 0"); + } + if (fileNameCount > 1) { + suffix = "(" + (fileNameCount - 1) + ")"; + } + return suffix; + } + + private static String extractFileExtension(String fileName) { + return fileName.substring(fileName.lastIndexOf('.') + 1); + } + + private static String extractFileNameWithoutExtension(String fileName) { + return fileName.substring(0, fileName.lastIndexOf('.')); + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java index 130cd07c490..05db183b2a0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * * Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except From fb2ab0963d8d45b01a91d5fb2af9a4f2151da72d Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Sat, 26 Feb 2022 22:34:26 +0530 Subject: [PATCH 03/13] Remove unwanted new lines --- .../spapplication/GenericSPApplicationDAOImpl.java | 3 --- .../spapplication/OracleSPApplicationDAOImpl.java | 5 ----- .../spapplication/PostgreSQLSPApplicationDAOImpl.java | 5 ----- .../spapplication/SQLServerSPApplicationDAOImpl.java | 5 ----- 4 files changed, 18 deletions(-) diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java index fbbd57c8497..31b56cfa0ed 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -29,7 +29,6 @@ import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -65,7 +64,6 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -99,7 +97,6 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java index 6372f3a2df3..9a513f81923 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -28,7 +28,6 @@ import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -65,7 +64,6 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -99,7 +97,6 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -199,7 +196,6 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -214,7 +210,6 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp + "AND AP_APP_ID = ? " + "AND IS_ID = ? " + "AND TENANT_ID = ? "; - try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java index 5ceb9403fc2..9b251aed14c 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -28,7 +28,6 @@ import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -65,7 +64,6 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -99,7 +97,6 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -199,7 +196,6 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -214,7 +210,6 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S + "AND AP_APP_ID = ? " + "AND IS_ID = ? " + "AND TENANT_ID = ? "; - try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java index f8baebb7a4c..f6ac4f4d67a 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -28,7 +28,6 @@ import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -65,7 +64,6 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -99,7 +97,6 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -199,7 +196,6 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } - } @Override @@ -214,7 +210,6 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S + "AND AP_APP_ID = ? " + "AND IS_ID = ? " + "AND TENANT_ID = ? "; - try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { From 097423b2b0b0f6a54491885c9831d735961837a7 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Tue, 1 Mar 2022 19:33:07 +0530 Subject: [PATCH 04/13] Improve api --- .../mgt/publisher/api/services/SPApplicationService.java | 4 ++-- .../publisher/api/services/impl/SPApplicationServiceImpl.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java index 002c54de469..9070ff29ba5 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java @@ -149,7 +149,7 @@ public interface SPApplicationService { Response getServiceProviders(@QueryParam("limit") Integer limit, @QueryParam("offset") Integer offset, @PathParam("identity-server-id") int identityServerId); - @Path("/{identity-server-id}/service-provider/{service-provider-id}/applications") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/attach") @POST @Produces(MediaType.APPLICATION_JSON) @ApiOperation( @@ -170,7 +170,7 @@ public interface SPApplicationService { /** * This method is used to register an APIM application for tenant domain. */ - @Path("/{identity-server-id}/service-provider/{service-provider-id}/delete/applications") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/detach") @POST @Produces(MediaType.APPLICATION_JSON) @ApiOperation( diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java index 52696b09813..4a649c75ea8 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -98,7 +98,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { } } - @Path("/{identity-server-id}/service-provider/{service-provider-id}/applications") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/attach") @POST @Override public Response attachApps(@PathParam("identity-server-id") int identityServerId, @@ -116,7 +116,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).build(); } - @Path("/{identity-server-id}/service-provider/{service-provider-id}/delete/applications") + @Path("/{identity-server-id}/service-provider/{service-provider-id}/detach") @POST @Override public Response detachApps(@PathParam("identity-server-id") int identityServerId, From 986828bc16a6f0a49d9f56f51643839437a9c12a Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Wed, 2 Mar 2022 19:22:47 +0530 Subject: [PATCH 05/13] Fix application count query not containing AP_APP_RELEASE columns when filtering Fix inaccurate application count when an appliction has more than 1 release --- .../core/dao/impl/application/GenericApplicationDAOImpl.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 1bcdae86a90..05279c29ef3 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -260,8 +260,11 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic Connection conn; PreparedStatement stmt = null; ResultSet rs = null; - String sql = "SELECT count(AP_APP.ID) AS APP_COUNT " + String sql = "SELECT count(DISTINCT AP_APP.ID) AS APP_COUNT " + "FROM AP_APP " + + "LEFT JOIN AP_APP_RELEASE ON " + + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + + "INNER JOIN (SELECT ID FROM AP_APP) AS app_data ON app_data.ID = AP_APP.ID " + "WHERE AP_APP.TENANT_ID = ?"; if (filter == null) { From 3dd0690552de6267f3924bbfd9f9b11de18f75b1 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Mon, 7 Mar 2022 21:58:43 +0530 Subject: [PATCH 06/13] Add identity server config Add api to create identity server Return List of identity servers withtout extra bean for response --- .../mgt/common/IdentityServer.java | 45 +++++---- .../mgt/common/IdentityServerList.java | 8 +- .../mgt/common/dto/IdentityServerDTO.java | 94 +++++++++++++++++++ .../common/services/SPApplicationManager.java | 6 +- .../mgt/core/config/ConfigurationManager.java | 18 ++++ .../config/IdentityServerConfiguration.java | 52 ++++++++++ .../mgt/core/config/IdentityServerDetail.java | 37 ++++++++ .../mgt/core/dao/SPApplicationDAO.java | 8 +- .../GenericApplicationDAOImpl.java | 4 - .../GenericSPApplicationDAOImpl.java | 46 ++++++++- .../OracleSPApplicationDAOImpl.java | 6 +- .../PostgreSQLSPApplicationDAOImpl.java | 6 +- .../SQLServerSPApplicationDAOImpl.java | 6 +- .../core/impl/SPApplicationManagerImpl.java | 27 ++++-- .../application/mgt/core/util/APIUtil.java | 20 ++++ .../application/mgt/core/util/Constants.java | 3 + .../application/mgt/core/util/DAOUtil.java | 40 ++++---- .../api/services/SPApplicationService.java | 24 +++++ .../impl/SPApplicationServiceImpl.java | 18 +++- .../util/SPAppRequestHandlerUtil.java | 7 +- 20 files changed, 404 insertions(+), 71 deletions(-) create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerConfiguration.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerDetail.java diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java index 24a3cd7cf72..62daec2595c 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java @@ -20,11 +20,12 @@ package io.entgra.application.mgt.common; public class IdentityServer { private int id; + private String providerName; private String name; private String description; private String url; - private String spAppsUri; - private String spAppsApi; + private String apiUrl; + private String serviceProviderAppsUrl; private String userName; private String password; @@ -60,22 +61,6 @@ public class IdentityServer { this.url = url; } - public String getSpAppsUri() { - return spAppsUri; - } - - public void setSpAppsURI(String spAppsUri) { - this.spAppsUri = spAppsUri; - } - - public String getSpAppsApi() { - return spAppsApi; - } - - public void setSpAppsApi(String spAppsApi) { - this.spAppsApi = spAppsApi; - } - public String getPassword() { return password; } @@ -91,4 +76,28 @@ public class IdentityServer { public void setUserName(String userName) { this.userName = userName; } + + public String getProviderName() { + return providerName; + } + + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + public String getApiUrl() { + return apiUrl; + } + + public void setApiUrl(String apiUrl) { + this.apiUrl = apiUrl; + } + + public String getServiceProviderAppsUrl() { + return serviceProviderAppsUrl; + } + + public void setServiceProviderAppsUrl(String serviceProviderAppsUrl) { + this.serviceProviderAppsUrl = serviceProviderAppsUrl; + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java index a3944580000..85a2ecdacfd 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java @@ -18,16 +18,18 @@ package io.entgra.application.mgt.common; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; + import java.util.List; public class IdentityServerList { - private List identityServers; + private List identityServers; - public List getIdentityServers() { + public List getIdentityServers() { return identityServers; } - public void setIdentityServers(List identityServers) { + public void setIdentityServers(List identityServers) { this.identityServers = identityServers; } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java new file mode 100644 index 00000000000..aba002b76aa --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.common.dto; + +public class IdentityServerDTO { + private int id; + private String providerName; + private String name; + private String description; + private String url; + private String apiUrl; + private String userName; + private String password; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getProviderName() { + return providerName; + } + + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + public String getApiUrl() { + return apiUrl; + } + + public void setApiUrl(String apiUrl) { + this.apiUrl = apiUrl; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java index 94ee0cd0ac3..78da3357624 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java @@ -19,7 +19,7 @@ package io.entgra.application.mgt.common.services; import io.entgra.application.mgt.common.IdentityServer; -import io.entgra.application.mgt.common.IdentityServerList; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.SPApplication; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.exception.RequestValidatingException; @@ -70,7 +70,9 @@ public interface SPApplicationManager { * @return Available identity servers * @throws ApplicationManagementException if error occurred while getting identity servers */ - IdentityServerList getIdentityServers() throws ApplicationManagementException; + List getIdentityServers() throws ApplicationManagementException; + + IdentityServer createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException; /** * diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java index ab85f87bb3f..5887ef36eac 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java @@ -36,8 +36,12 @@ public class ConfigurationManager { private Configuration configuration; + private IdentityServerConfiguration identityServerConfiguration; + private static String configPath; + private static String identityServerConfigPath; + private static volatile ConfigurationManager configurationManager; private ConfigurationManager() { @@ -60,6 +64,14 @@ public class ConfigurationManager { return configurationManager; } + public static synchronized void setIdentityServerConfigPathConfigLocation(String configPath) throws InvalidConfigurationException { + if (identityServerConfigPath == null) { + identityServerConfigPath = configPath; + } else { + throw new InvalidConfigurationException("Configuration path " + configPath + " is already defined"); + } + } + public static synchronized void setConfigLocation(String configPath) throws InvalidConfigurationException { if (ConfigurationManager.configPath == null) { ConfigurationManager.configPath = configPath; @@ -74,9 +86,11 @@ public class ConfigurationManager { Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); if (configPath == null) { configPath = Constants.DEFAULT_CONFIG_FILE_LOCATION; + identityServerConfigPath = Constants.DEFAULT_IDENTITY_SERVERS_CONFIG_FILE_LOCATION; } //TODO: Add validation for the configurations this.configuration = (Configuration) unmarshaller.unmarshal(new File(configPath)); + this.identityServerConfiguration = (IdentityServerConfiguration) unmarshaller.unmarshal(new File(identityServerConfigPath)); } catch (Exception e) { log.error(e); throw new InvalidConfigurationException("Error occurred while initializing application config: " @@ -88,6 +102,10 @@ public class ConfigurationManager { return configuration; } + public IdentityServerConfiguration getIdentityServerConfiguration() { + return identityServerConfiguration; + } + public Extension getExtension(Extension.Name extName) throws InvalidConfigurationException { for (Extension extension : configuration.getExtensions()) { if (extension.getName().contentEquals(extName.toString())) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerConfiguration.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerConfiguration.java new file mode 100644 index 00000000000..fda9f8ef9f8 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerConfiguration.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * + * Entgra (pvt) Ltd. 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 io.entgra.application.mgt.core.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +/** + * Represents the Application Management Configuration. + */ +@XmlRootElement(name = "IdentityServerConfiguration") +public class IdentityServerConfiguration { + + private List identityServers; + + @XmlElementWrapper(name = "IdentityServers") + @XmlElement(name = "IdentityServerDTO") + public List getIdentityServers() { + return identityServers; + } + + public IdentityServerDetail getIdentityServerDetailByProviderName(String identityServerProviderName) { + for (IdentityServerDetail identityServerDetail : identityServers) { + if (identityServerDetail.getProviderName().equals(identityServerProviderName)) { + return identityServerDetail; + } + } + return null; + } + + public void setIdentityServers(List identityServers) { + this.identityServers = identityServers; + } +} + diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerDetail.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerDetail.java new file mode 100644 index 00000000000..a73b70f0091 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerDetail.java @@ -0,0 +1,37 @@ +package io.entgra.application.mgt.core.config; + +import javax.xml.bind.annotation.XmlAttribute; + +public class IdentityServerDetail { + private String providerName; + private String serviceProvidersPageUri; + private String serviceProvidersAPIContextPath; + + @XmlAttribute(name = "ProviderName") + public String getProviderName() { + return providerName; + } + + public void setProviderName(String providerName) { + this.providerName = providerName; + } + + + @XmlAttribute(name = "ServiceProvidersPageUri") + public String getServiceProvidersPageUri() { + return serviceProvidersPageUri; + } + + public void setServiceProvidersPageUri(String serviceProvidersPageUri) { + this.serviceProvidersPageUri = serviceProvidersPageUri; + } + + @XmlAttribute(name = "ServiceProvidersAPIContextPath") + public String getServiceProvidersAPIContextPath() { + return serviceProvidersAPIContextPath; + } + + public void setServiceProvidersAPIContextPath(String serviceProvidersAPIContextPath) { + this.serviceProvidersAPIContextPath = serviceProvidersAPIContextPath; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java index 850e11bf88e..62f97db9d0b 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java @@ -18,7 +18,7 @@ package io.entgra.application.mgt.core.dao; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.dto.ApplicationDTO; import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException; @@ -26,6 +26,8 @@ import java.util.List; public interface SPApplicationDAO { + int createIdentityServer(IdentityServerDTO identityServer, int tenantId) throws ApplicationManagementDAOException; + /** * * @param identityServerId Id of identity server in which the service provider is in @@ -59,7 +61,7 @@ public interface SPApplicationDAO { * @return All available identity servers * @throws ApplicationManagementDAOException if any db error occurred */ - List getIdentityServers(int tenantId) throws ApplicationManagementDAOException; + List getIdentityServers(int tenantId) throws ApplicationManagementDAOException; /** * @@ -67,7 +69,7 @@ public interface SPApplicationDAO { * @return Identity Server of the given id * @throws ApplicationManagementDAOException if any db error occurred */ - IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException; + IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException; /** * Verify whether application exist for given identity server id, service provider id and application id. diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 05279c29ef3..420afdbbde7 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -17,9 +17,6 @@ */ package io.entgra.application.mgt.core.dao.impl.application; -import io.entgra.application.mgt.common.ApplicationType; -import io.entgra.application.mgt.common.IdentityServer; -import io.entgra.application.mgt.core.util.Constants; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -27,7 +24,6 @@ import io.entgra.application.mgt.common.AppLifecycleState; import io.entgra.application.mgt.common.dto.ApplicationDTO; import io.entgra.application.mgt.common.dto.CategoryDTO; import io.entgra.application.mgt.common.Filter; -import io.entgra.application.mgt.common.dto.ReviewDTO; import io.entgra.application.mgt.common.dto.TagDTO; import io.entgra.application.mgt.common.exception.DBConnectionException; import io.entgra.application.mgt.core.dao.ApplicationDAO; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java index 31b56cfa0ed..4a586d8af60 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -18,7 +18,7 @@ package io.entgra.application.mgt.core.dao.impl.application.spapplication; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.dto.ApplicationDTO; import io.entgra.application.mgt.common.exception.DBConnectionException; import io.entgra.application.mgt.core.dao.SPApplicationDAO; @@ -40,7 +40,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class); @Override - public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { + public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; @@ -67,7 +67,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } @Override - public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { + public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " @@ -99,6 +99,46 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } + @Override + public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to create an identity server"); + } + String sql = "INSERT INTO AP_IDENTITY_SERVER " + + "(PROVIDER_NAME, " + + "NAME, " + + "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) " + + "VALUES (?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, identityServerDTO.getProviderName()); + stmt.setString(2, identityServerDTO.getName()); + stmt.setString(3, identityServerDTO.getDescription()); + stmt.setString(4, identityServerDTO.getUrl()); + stmt.setString(5, identityServerDTO.getApiUrl()); + stmt.setString(6, identityServerDTO.getUserName()); + stmt.setString(7, identityServerDTO.getPassword()); + stmt.setInt(8, tenantId); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + return rs.getInt(1); + } + return -1; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while creating identity server "; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an identity server "; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java index 9a513f81923..3526fe88e2a 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -18,7 +18,7 @@ package io.entgra.application.mgt.core.dao.impl.application.spapplication; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.dto.ApplicationDTO; import io.entgra.application.mgt.common.exception.DBConnectionException; import io.entgra.application.mgt.core.dao.SPApplicationDAO; @@ -40,7 +40,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp private static final Log log = LogFactory.getLog(OracleSPApplicationDAOImpl.class); @Override - public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { + public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; @@ -67,7 +67,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } @Override - public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { + public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java index 9b251aed14c..88d482bf132 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -18,7 +18,7 @@ package io.entgra.application.mgt.core.dao.impl.application.spapplication; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.dto.ApplicationDTO; import io.entgra.application.mgt.common.exception.DBConnectionException; import io.entgra.application.mgt.core.dao.SPApplicationDAO; @@ -40,7 +40,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S private static final Log log = LogFactory.getLog(PostgreSQLSPApplicationDAOImpl.class); @Override - public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { + public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; @@ -67,7 +67,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S } @Override - public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { + public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java index f6ac4f4d67a..acbfe124b56 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -18,7 +18,7 @@ package io.entgra.application.mgt.core.dao.impl.application.spapplication; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.dto.ApplicationDTO; import io.entgra.application.mgt.common.exception.DBConnectionException; import io.entgra.application.mgt.core.dao.SPApplicationDAO; @@ -40,7 +40,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S private static final Log log = LogFactory.getLog(SQLServerSPApplicationDAOImpl.class); @Override - public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { + public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; @@ -67,7 +67,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S } @Override - public IdentityServer getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { + public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java index 1f90f5db06e..f1ed00f98e8 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -19,7 +19,7 @@ package io.entgra.application.mgt.core.impl; import io.entgra.application.mgt.common.IdentityServer; -import io.entgra.application.mgt.common.IdentityServerList; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.SPApplication; import io.entgra.application.mgt.common.dto.ApplicationDTO; import io.entgra.application.mgt.common.exception.ApplicationManagementException; @@ -44,6 +44,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; public class SPApplicationManagerImpl implements SPApplicationManager { @@ -76,7 +77,8 @@ public class SPApplicationManagerImpl implements SPApplicationManager { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { ConnectionManagerUtil.openDBConnection(); - return spApplicationDAO.getIdentityServerById(identityServerId, tenantId); + IdentityServerDTO identityServerDTO = spApplicationDAO.getIdentityServerById(identityServerId, tenantId); + return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO); } catch (DBConnectionException e) { String msg = "Error occurred when getting database connection to get identity server with the id: " + identityServerId; log.error(msg, e); @@ -92,13 +94,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } @Override - public IdentityServerList getIdentityServers() throws ApplicationManagementException { + public List getIdentityServers() throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { ConnectionManagerUtil.openDBConnection(); - IdentityServerList identityServerList = new IdentityServerList(); - identityServerList.setIdentityServers(spApplicationDAO.getIdentityServers(tenantId)); - return identityServerList; + return spApplicationDAO.getIdentityServers(tenantId).stream(). + map(APIUtil::identityServerDtoToIdentityServerResponse).collect(Collectors.toList()); } catch (DBConnectionException e) { String msg = "Error occurred when getting database connection to get identity servers"; log.error(msg, e); @@ -113,6 +114,20 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + @Override + public IdentityServer createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + int id = spApplicationDAO.createIdentityServer(identityServerDTO, tenantId); + identityServerDTO.setId(id); + return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO); + } catch (ApplicationManagementDAOException e) { + String msg = "Error occurred while creating identity server " + identityServerDTO.getName(); + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } + } + @Override public List getSPApplications(int identityServerId, String spUID) throws ApplicationManagementException { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java index cb4eb7edffc..00229f67604 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java @@ -18,6 +18,9 @@ package io.entgra.application.mgt.core.util; +import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; +import io.entgra.application.mgt.core.config.IdentityServerDetail; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -363,6 +366,23 @@ public class APIUtil { return applicationReleaseDTO; } + public static IdentityServer identityServerDtoToIdentityServerResponse(IdentityServerDTO identityServerDTO) { + IdentityServer identityServer = new IdentityServer(); + identityServer.setId(identityServerDTO.getId()); + identityServer.setProviderName(identityServerDTO.getProviderName()); + identityServer.setName(identityServerDTO.getName()); + identityServer.setDescription(identityServerDTO.getDescription()); + identityServer.setUrl(identityServerDTO.getUrl()); + identityServer.setApiUrl(identityServerDTO.getApiUrl()); + identityServer.setUserName(identityServerDTO.getUserName()); + identityServer.setPassword(identityServerDTO.getPassword()); + IdentityServerDetail identityServerDetail = ConfigurationManager.getInstance().getIdentityServerConfiguration() + .getIdentityServerDetailByProviderName(identityServerDTO.getProviderName()); + String serviceProviderAppsUrl = identityServerDTO.getUrl() + Constants.FORWARD_SLASH + identityServerDetail.getServiceProvidersPageUri(); + identityServer.setServiceProviderAppsUrl(serviceProviderAppsUrl); + return identityServer; + } + public static Application appDtoToAppResponse(ApplicationDTO applicationDTO) throws ApplicationManagementException { Application application = new Application(); diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java index 03f94ef1d0f..4082edb492d 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java @@ -31,9 +31,12 @@ import java.util.Map; public class Constants { public static final String APPLICATION_CONFIG_XML_FILE = "application-mgt.xml"; + public static final String IDENTITY_SERVERS_CONFIG_XML_FILE = "identity-servers-config.xml"; public static final String DEFAULT_CONFIG_FILE_LOCATION = CarbonUtils.getCarbonConfigDirPath() + File.separator + Constants.APPLICATION_CONFIG_XML_FILE; + public static final String DEFAULT_IDENTITY_SERVERS_CONFIG_FILE_LOCATION = CarbonUtils.getCarbonConfigDirPath() + File.separator + + IDENTITY_SERVERS_CONFIG_XML_FILE; public static final String DEFAULT_VERSION = "1.0.0"; public static final String SCREENSHOT_NAME = "screenshot"; public static final String ICON_NAME = "icon"; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java index 4502c8987bf..4291d95525d 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java @@ -19,7 +19,7 @@ package io.entgra.application.mgt.core.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; @@ -172,22 +172,22 @@ public class DAOUtil { * To create application object from the result set retrieved from the Database. * * @param rs ResultSet - * @return IdentityServer that is retrieved from the Database. + * @return IdentityServerDTO that is retrieved from the Database. * @throws SQLException SQL Exception * @throws JSONException JSONException. */ - public static IdentityServer loadIdentityServer(ResultSet rs) + public static IdentityServerDTO loadIdentityServer(ResultSet rs) throws SQLException, JSONException, UnexpectedServerErrorException { - List identityServers = loadIdentityServers(rs); - if (identityServers.isEmpty()) { + List identityServerDTOS = loadIdentityServers(rs); + if (identityServerDTOS.isEmpty()) { return null; } - if (identityServers.size() > 1) { + if (identityServerDTOS.size() > 1) { String msg = "Internal server error. Found more than one identity server for requested ID"; log.error(msg); throw new UnexpectedServerErrorException(msg); } - return identityServers.get(0); + return identityServerDTOS.get(0); } /** @@ -198,21 +198,21 @@ public class DAOUtil { * @throws SQLException SQL Exception * @throws JSONException JSONException. */ - public static List loadIdentityServers(ResultSet rs) throws SQLException, JSONException { - List identityServers = new ArrayList<>(); + public static List loadIdentityServers(ResultSet rs) throws SQLException, JSONException { + List identityServerDTOS = new ArrayList<>(); while (rs.next()) { - IdentityServer identityServer = new IdentityServer(); - identityServer.setId(rs.getInt("ID")); - identityServer.setName(rs.getString("NAME")); - identityServer.setDescription(rs.getString("DESCRIPTION")); - identityServer.setUrl(rs.getString("URL")); - identityServer.setSpAppsURI(rs.getString("SP_APPS_URI")); - identityServer.setSpAppsApi(rs.getString("SP_APPS_API")); - identityServer.setUserName(rs.getString("USERNAME")); - identityServer.setPassword(rs.getString("PASSWORD")); - identityServers.add(identityServer); + IdentityServerDTO identityServerDTO = new IdentityServerDTO(); + identityServerDTO.setId(rs.getInt("ID")); + identityServerDTO.setProviderName(rs.getString("PROVIDER_NAME")); + identityServerDTO.setName(rs.getString("NAME")); + identityServerDTO.setDescription(rs.getString("DESCRIPTION")); + identityServerDTO.setUrl(rs.getString("URL")); + identityServerDTO.setApiUrl(rs.getString("API_URI")); + identityServerDTO.setUserName(rs.getString("USERNAME")); + identityServerDTO.setPassword(rs.getString("PASSWORD")); + identityServerDTOS.add(identityServerDTO); } - return identityServers; + return identityServerDTOS; } /** diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java index 9070ff29ba5..ffaa3c7a8ab 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java @@ -18,6 +18,7 @@ package io.entgra.application.mgt.publisher.api.services; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; import io.entgra.application.mgt.common.wrapper.CustomAppWrapper; import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; @@ -66,6 +67,13 @@ import java.util.List; roles = {"Internal/devicemgt-user"}, permissions = {"/app-mgt/publisher/service-provider/application/view"} ), + @Scope( + name = "Create new identity server", + description = "Connect to new identity server", + key = "perm:app:publisher:service-provider:connect", + roles = {"Internal/devicemgt-user"}, + permissions = {"/app-mgt/publisher/service-provider/application/connect"} + ), @Scope( name = "Create a service provider application", description = "Create an application and attach (map) to service provider", @@ -128,6 +136,22 @@ public interface SPApplicationService { ) Response getIdentityServer(@PathParam("id") int id); + @POST + @Produces(MediaType.APPLICATION_JSON) + @Path("/identity-servers") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "create new identity server", + tags = "Identity Server Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:connect") + }) + } + ) + Response createIdentityServer(IdentityServerDTO identityServerDTO); + /** * This method is used to register an APIM application for tenant domain. */ diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java index 4a649c75ea8..0fac1122115 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -19,6 +19,7 @@ package io.entgra.application.mgt.publisher.api.services.impl; import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.IdentityServerList; import io.entgra.application.mgt.common.SPApplicationListResponse; import io.entgra.application.mgt.common.exception.ApplicationManagementException; @@ -56,7 +57,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { public Response getIdentityServers() { try { SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); - IdentityServerList identityServers = spAppManager.getIdentityServers(); + List identityServers = spAppManager.getIdentityServers(); return Response.status(Response.Status.OK).entity(identityServers).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; @@ -80,6 +81,21 @@ public class SPApplicationServiceImpl implements SPApplicationService { } } + @Path("/identity-servers") + @POST + @Override + public Response createIdentityServer(IdentityServerDTO identityServerDTO) { + try { + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + IdentityServer identityServer = spAppManager.createIdentityServer(identityServerDTO); + return Response.status(Response.Status.CREATED).entity(identityServer).build(); + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; + log.error(errMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build(); + } + } + @Path("/{identity-server-id}/service-providers") @GET @Override diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java index b9d6b60e991..d71b3534721 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java @@ -24,6 +24,8 @@ import io.entgra.application.mgt.common.SPApplication; import io.entgra.application.mgt.common.SPApplicationListResponse; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.services.SPApplicationManager; +import io.entgra.application.mgt.core.config.ConfigurationManager; +import io.entgra.application.mgt.core.config.IdentityServerDetail; import io.entgra.application.mgt.core.util.APIUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -167,8 +169,9 @@ public class SPAppRequestHandlerUtil { } private static String getSPApplicationsAPI(IdentityServer identityServer) { - String api = identityServer.getSpAppsApi(); - return api; + IdentityServerDetail identityServerDetail = ConfigurationManager.getInstance().getIdentityServerConfiguration(). + getIdentityServerDetailByProviderName(identityServer.getProviderName()); + return identityServer.getApiUrl() + identityServerDetail.getServiceProvidersAPIContextPath(); } } \ No newline at end of file From 3f60a0cdda48e8e35763ea21da4e1e6a47c97fb0 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Tue, 8 Mar 2022 08:27:00 +0530 Subject: [PATCH 07/13] Fix sql query columns Add createIdentityServer method to all DAOs --- .../mgt/core/dao/SPApplicationDAO.java | 2 +- .../GenericSPApplicationDAOImpl.java | 4 +- .../OracleSPApplicationDAOImpl.java | 44 ++++++++++++++++++- .../PostgreSQLSPApplicationDAOImpl.java | 44 ++++++++++++++++++- .../SQLServerSPApplicationDAOImpl.java | 44 ++++++++++++++++++- 5 files changed, 129 insertions(+), 9 deletions(-) diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java index 62f97db9d0b..9fe44a72e76 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java @@ -26,7 +26,7 @@ import java.util.List; public interface SPApplicationDAO { - int createIdentityServer(IdentityServerDTO identityServer, int tenantId) throws ApplicationManagementDAOException; + int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException; /** * diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java index 4a586d8af60..ab2ca8cca69 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -41,7 +41,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class); @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -68,7 +68,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java index 3526fe88e2a..828ad1acaee 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -41,7 +41,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -68,7 +68,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -99,6 +99,46 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } + @Override + public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to create an identity server"); + } + String sql = "INSERT INTO AP_IDENTITY_SERVER " + + "(PROVIDER_NAME, " + + "NAME, " + + "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) " + + "VALUES (?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, identityServerDTO.getProviderName()); + stmt.setString(2, identityServerDTO.getName()); + stmt.setString(3, identityServerDTO.getDescription()); + stmt.setString(4, identityServerDTO.getUrl()); + stmt.setString(5, identityServerDTO.getApiUrl()); + stmt.setString(6, identityServerDTO.getUserName()); + stmt.setString(7, identityServerDTO.getPassword()); + stmt.setInt(8, tenantId); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + return rs.getInt(1); + } + return -1; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while creating identity server "; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an identity server "; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java index 88d482bf132..629b0b3df88 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -41,7 +41,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -68,7 +68,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -99,6 +99,46 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S } } + @Override + public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to create an identity server"); + } + String sql = "INSERT INTO AP_IDENTITY_SERVER " + + "(PROVIDER_NAME, " + + "NAME, " + + "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) " + + "VALUES (?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, identityServerDTO.getProviderName()); + stmt.setString(2, identityServerDTO.getName()); + stmt.setString(3, identityServerDTO.getDescription()); + stmt.setString(4, identityServerDTO.getUrl()); + stmt.setString(5, identityServerDTO.getApiUrl()); + stmt.setString(6, identityServerDTO.getUserName()); + stmt.setString(7, identityServerDTO.getPassword()); + stmt.setInt(8, tenantId); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + return rs.getInt(1); + } + return -1; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while creating identity server "; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an identity server "; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java index acbfe124b56..e9435702862 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -41,7 +41,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -68,7 +68,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, NAME, DESCRIPTION, URL, SP_APPS_URI, SP_APPS_API, TENANT_ID, USERNAME, PASSWORD " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -99,6 +99,46 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S } } + @Override + public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to create an identity server"); + } + String sql = "INSERT INTO AP_IDENTITY_SERVER " + + "(PROVIDER_NAME, " + + "NAME, " + + "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) " + + "VALUES (?, ?, ?, ?)"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setString(1, identityServerDTO.getProviderName()); + stmt.setString(2, identityServerDTO.getName()); + stmt.setString(3, identityServerDTO.getDescription()); + stmt.setString(4, identityServerDTO.getUrl()); + stmt.setString(5, identityServerDTO.getApiUrl()); + stmt.setString(6, identityServerDTO.getUserName()); + stmt.setString(7, identityServerDTO.getPassword()); + stmt.setInt(8, tenantId); + stmt.executeUpdate(); + try (ResultSet rs = stmt.getGeneratedKeys()) { + if (rs.next()) { + return rs.getInt(1); + } + return -1; + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while creating identity server "; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to create an identity server "; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public List getSPApplications(int identityServerId, String spUID, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { From c58f8375851127307ee9259b1f6c1be8a64b5072 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Wed, 6 Apr 2022 00:55:18 +0530 Subject: [PATCH 08/13] Complete Identity Server create/delete/update APIs --- .../mgt/common/IdentityServerList.java | 35 -- ...erver.java => IdentityServerResponse.java} | 48 +-- .../mgt/common/dto/IdentityServerDTO.java | 39 +- .../dto/IdentityServiceProviderDTO.java | 24 ++ .../IdentityServerManagementException.java | 28 ++ .../common/services/SPApplicationManager.java | 79 +++- .../io.entgra.application.mgt.core/pom.xml | 1 + .../mgt/core/config/ConfigurationManager.java | 18 +- ...tail.java => IdentityServiceProvider.java} | 31 +- ...IdentityServiceProviderConfiguration.java} | 26 +- .../mgt/core/dao/SPApplicationDAO.java | 37 ++ .../GenericSPApplicationDAOImpl.java | 162 +++++++- .../OracleSPApplicationDAOImpl.java | 159 +++++++- .../PostgreSQLSPApplicationDAOImpl.java | 159 +++++++- .../SQLServerSPApplicationDAOImpl.java | 163 +++++++- .../ISServiceProviderApplicationService.java | 68 ++++ .../impl/WSO2IAMSPApplicationService.java | 156 ++++++++ .../core/impl/SPApplicationManagerImpl.java | 348 +++++++++++++++++- .../application/mgt/core/util/APIUtil.java | 30 +- .../application/mgt/core/util/Constants.java | 3 + .../application/mgt/core/util/DAOUtil.java | 8 +- .../api/services/SPApplicationService.java | 81 ++++ .../impl/SPApplicationServiceImpl.java | 196 ++++++++-- .../util/SPAppRequestHandlerUtil.java | 177 --------- 24 files changed, 1693 insertions(+), 383 deletions(-) delete mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java rename components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/{IdentityServer.java => IdentityServerResponse.java} (70%) create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServiceProviderDTO.java create mode 100644 components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java rename components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/{IdentityServerDetail.java => IdentityServiceProvider.java} (50%) rename components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/{IdentityServerConfiguration.java => IdentityServiceProviderConfiguration.java} (52%) create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/ISServiceProviderApplicationService.java create mode 100644 components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java delete mode 100644 components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java deleted file mode 100644 index 85a2ecdacfd..00000000000 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerList.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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 io.entgra.application.mgt.common; - -import io.entgra.application.mgt.common.dto.IdentityServerDTO; - -import java.util.List; - -public class IdentityServerList { - private List identityServers; - - public List getIdentityServers() { - return identityServers; - } - - public void setIdentityServers(List identityServers) { - this.identityServers = identityServers; - } -} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerResponse.java similarity index 70% rename from components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java rename to components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerResponse.java index 62daec2595c..f36883da50e 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServer.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerResponse.java @@ -18,16 +18,20 @@ package io.entgra.application.mgt.common; -public class IdentityServer { +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class IdentityServerResponse { private int id; private String providerName; private String name; private String description; private String url; - private String apiUrl; private String serviceProviderAppsUrl; - private String userName; - private String password; + private String username; + private List> apiParamList; public int getId() { return id; @@ -61,20 +65,12 @@ public class IdentityServer { this.url = url; } - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; + public String getUsername() { + return username; } - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; + public void setUsername(String username) { + this.username = username; } public String getProviderName() { @@ -85,14 +81,6 @@ public class IdentityServer { this.providerName = providerName; } - public String getApiUrl() { - return apiUrl; - } - - public void setApiUrl(String apiUrl) { - this.apiUrl = apiUrl; - } - public String getServiceProviderAppsUrl() { return serviceProviderAppsUrl; } @@ -100,4 +88,16 @@ public class IdentityServer { public void setServiceProviderAppsUrl(String serviceProviderAppsUrl) { this.serviceProviderAppsUrl = serviceProviderAppsUrl; } + + public List> getApiParamList() { + return apiParamList; + } + + public void setApiParamList(Map apiParams) { + this.apiParamList = apiParams.entrySet().stream().map(param -> { + Map paramMap = new HashMap<>(); + paramMap.put(param.getKey(), param.getValue()); + return paramMap; + }).collect(Collectors.toList()); + } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java index aba002b76aa..71e11c75cc3 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java @@ -18,15 +18,26 @@ package io.entgra.application.mgt.common.dto; +import com.google.gson.Gson; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + public class IdentityServerDTO { + private int id; private String providerName; private String name; private String description; private String url; - private String apiUrl; - private String userName; + private String username; private String password; + private Map apiParams; + + public IdentityServerDTO() { + this.apiParams = new HashMap<>(); + } public int getId() { return id; @@ -68,12 +79,12 @@ public class IdentityServerDTO { this.password = password; } - public String getUserName() { - return userName; + public String getUsername() { + return username; } - public void setUserName(String userName) { - this.userName = userName; + public void setUsername(String username) { + this.username = username; } public String getProviderName() { @@ -84,11 +95,19 @@ public class IdentityServerDTO { this.providerName = providerName; } - public String getApiUrl() { - return apiUrl; + public String constructApiParamsJsonString() { + return new Gson().toJson(apiParams); + } + + public Set getApiParamKeys() { + return apiParams.keySet(); + } + + public Map getApiParams() { + return apiParams; } - public void setApiUrl(String apiUrl) { - this.apiUrl = apiUrl; + public void setApiParams(Map apiParams) { + this.apiParams = apiParams; } } diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServiceProviderDTO.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServiceProviderDTO.java new file mode 100644 index 00000000000..ad378daec2c --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServiceProviderDTO.java @@ -0,0 +1,24 @@ +package io.entgra.application.mgt.common.dto; + +import java.util.List; + +public class IdentityServiceProviderDTO { + private String name; + private List requiredApiParams; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getRequiredApiParams() { + return requiredApiParams; + } + + public void setRequiredApiParams(List requiredApiParams) { + this.requiredApiParams = requiredApiParams; + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java new file mode 100644 index 00000000000..602a8eddeed --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java @@ -0,0 +1,28 @@ +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.application.mgt.common.exception; + +/** + * Exception that will be thrown if any error occurs while calling identity server services . + */ +public class IdentityServerManagementException extends ApplicationManagementException { + public IdentityServerManagementException(String message) { + super(message); + setMessage(message); + } +} diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java index 78da3357624..8dfbc18fc6b 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java @@ -18,9 +18,10 @@ package io.entgra.application.mgt.common.services; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.IdentityServerResponse; +import io.entgra.application.mgt.common.SPApplicationListResponse; import io.entgra.application.mgt.common.dto.IdentityServerDTO; -import io.entgra.application.mgt.common.SPApplication; +import io.entgra.application.mgt.common.dto.IdentityServiceProviderDTO; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.exception.RequestValidatingException; import io.entgra.application.mgt.common.response.Application; @@ -28,15 +29,6 @@ import java.util.List; public interface SPApplicationManager { - /** - * This method adds existing consumer applications of service providers to the SPApplication bean - * - * @param identityServerId identity server id of the service provider - * @param applications Service providers list to which the existing applications should be added - * @throws ApplicationManagementException if error occurred while adding existing applications - */ - void addExistingApps(int identityServerId, List applications) throws ApplicationManagementException; - /** * Removes consumer application from service provider * @@ -63,16 +55,65 @@ public interface SPApplicationManager { * @return Identity server for the given ID * @throws ApplicationManagementException if error occurred while getting identity server */ - IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException; + IdentityServerResponse getIdentityServerResponse(int identityServerId) throws ApplicationManagementException; /** * * @return Available identity servers * @throws ApplicationManagementException if error occurred while getting identity servers */ - List getIdentityServers() throws ApplicationManagementException; + List getIdentityServers() throws ApplicationManagementException; + + /** + * Create a new Identity Server + * + * @return {@link IdentityServerResponse} + * @throws ApplicationManagementException if error occurred while getting identity servers + */ + IdentityServerResponse createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException; + + /** + * Update existing Identity Server + * + * @param id of the identity server to be updated + * @param updateIdentityServerDTO identity server dto bean with updated fields + * @throws ApplicationManagementException if error occurred while getting identity servers + */ + IdentityServerResponse updateIdentityServer(IdentityServerDTO updateIdentityServerDTO, int id) throws ApplicationManagementException; + + /** + * Delete Identity Server + * + * @param id of the identity server to be deleted + * @throws ApplicationManagementException if error occurred while getting identity servers + */ + void deleteIdentityServer(int id) throws ApplicationManagementException; - IdentityServer createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException; + /** + * Check if Identity Server exists with the same name + * + * @param name of the identity server + * @return if name already exists for identity server + */ + boolean isIdentityServerNameExist(String name) throws ApplicationManagementException; + + /** + * Check if Identity Server exists with the same url + * + * @param url of the identity server + * @return if url already exists for identity server + */ + boolean isIdentityServerUrlExist(String url) throws ApplicationManagementException; + + /** + * Retrieve service provider apps from identity server + * + * @param identityServerId Id of the identity server + * @return {@link SPApplicationListResponse} + * @throws ApplicationManagementException if error while retrieving sp applications + */ + SPApplicationListResponse retrieveSPApplicationFromIdentityServer(int identityServerId, Integer offset, Integer limit) + throws ApplicationManagementException; /** * @@ -101,9 +142,9 @@ public interface SPApplicationManager { * Validates application ids of the applications that should be attached * * @param appIds application ids to be validated - * @throws ApplicationManagementException + * @throws ApplicationManagementException if invalid service provider, identity server Id or app Ids provided */ - void validateAttachAppsRequest(int identityServerId, List appIds) throws ApplicationManagementException; + void validateAttachAppsRequest(int identityServerId, String serviceProviderId, List appIds) throws ApplicationManagementException; /** * Validates application ids of the applications that should be detached @@ -115,4 +156,10 @@ public interface SPApplicationManager { */ void validateDetachAppsRequest(int identityServerId, String spId, List appIds) throws ApplicationManagementException; + /** + * Get available identity service providers + * + * @return list of available service providers' names + */ + List getIdentityServiceProviders() throws ApplicationManagementException; } diff --git a/components/application-mgt/io.entgra.application.mgt.core/pom.xml b/components/application-mgt/io.entgra.application.mgt.core/pom.xml index f3458ef553d..bb87db35393 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/pom.xml +++ b/components/application-mgt/io.entgra.application.mgt.core/pom.xml @@ -90,6 +90,7 @@ !io.entgra.application.mgt.core.internal.*, io.entgra.application.mgt.core.* + * diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java index 5887ef36eac..898ef114213 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java @@ -36,7 +36,7 @@ public class ConfigurationManager { private Configuration configuration; - private IdentityServerConfiguration identityServerConfiguration; + private IdentityServiceProviderConfiguration identityServiceProviderConfiguration; private static String configPath; @@ -58,6 +58,12 @@ public class ConfigurationManager { } catch (ApplicationManagementException e) { log.error(e); } + } else { + try { + configurationManager.initConfig(); + } catch (ApplicationManagementException e) { + log.error(e); + } } } } @@ -83,14 +89,18 @@ public class ConfigurationManager { private void initConfig() throws ApplicationManagementException { try { JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class); + JAXBContext jaxbISConfigContext = JAXBContext.newInstance(IdentityServiceProviderConfiguration.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); + Unmarshaller identityServerConfigUnmarshaller = jaxbISConfigContext.createUnmarshaller(); if (configPath == null) { configPath = Constants.DEFAULT_CONFIG_FILE_LOCATION; + } + if (identityServerConfigPath == null) { identityServerConfigPath = Constants.DEFAULT_IDENTITY_SERVERS_CONFIG_FILE_LOCATION; } //TODO: Add validation for the configurations this.configuration = (Configuration) unmarshaller.unmarshal(new File(configPath)); - this.identityServerConfiguration = (IdentityServerConfiguration) unmarshaller.unmarshal(new File(identityServerConfigPath)); + this.identityServiceProviderConfiguration = (IdentityServiceProviderConfiguration) identityServerConfigUnmarshaller.unmarshal(new File(identityServerConfigPath)); } catch (Exception e) { log.error(e); throw new InvalidConfigurationException("Error occurred while initializing application config: " @@ -102,8 +112,8 @@ public class ConfigurationManager { return configuration; } - public IdentityServerConfiguration getIdentityServerConfiguration() { - return identityServerConfiguration; + public IdentityServiceProviderConfiguration getIdentityServerConfiguration() { + return identityServiceProviderConfiguration; } public Extension getExtension(Extension.Name extName) throws InvalidConfigurationException { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerDetail.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProvider.java similarity index 50% rename from components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerDetail.java rename to components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProvider.java index a73b70f0091..d7c82c0790e 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerDetail.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProvider.java @@ -1,37 +1,38 @@ package io.entgra.application.mgt.core.config; -import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; -public class IdentityServerDetail { +@XmlRootElement(name = "IdentityServiceProvider") +public class IdentityServiceProvider { private String providerName; + private String providerClassName; private String serviceProvidersPageUri; - private String serviceProvidersAPIContextPath; - @XmlAttribute(name = "ProviderName") + @XmlElement(name = "ProviderName") public String getProviderName() { return providerName; } - public void setProviderName(String providerName) { - this.providerName = providerName; + @XmlElement(name = "ProviderClassName") + public String getProviderClassName() { + return providerClassName; } - - @XmlAttribute(name = "ServiceProvidersPageUri") + @XmlElement(name = "ServiceProvidersPageUri") public String getServiceProvidersPageUri() { return serviceProvidersPageUri; } - public void setServiceProvidersPageUri(String serviceProvidersPageUri) { - this.serviceProvidersPageUri = serviceProvidersPageUri; + public void setProviderName(String providerName) { + this.providerName = providerName; } - @XmlAttribute(name = "ServiceProvidersAPIContextPath") - public String getServiceProvidersAPIContextPath() { - return serviceProvidersAPIContextPath; + public void setServiceProvidersPageUri(String serviceProvidersPageUri) { + this.serviceProvidersPageUri = serviceProvidersPageUri; } - public void setServiceProvidersAPIContextPath(String serviceProvidersAPIContextPath) { - this.serviceProvidersAPIContextPath = serviceProvidersAPIContextPath; + public void setProviderClassName(String providerClassName) { + this.providerClassName = providerClassName; } } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerConfiguration.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProviderConfiguration.java similarity index 52% rename from components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerConfiguration.java rename to components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProviderConfiguration.java index fda9f8ef9f8..86b1936a0d0 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServerConfiguration.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProviderConfiguration.java @@ -25,28 +25,28 @@ import java.util.List; /** * Represents the Application Management Configuration. */ -@XmlRootElement(name = "IdentityServerConfiguration") -public class IdentityServerConfiguration { +@XmlRootElement(name = "IdentityServiceProviderConfiguration") +public class IdentityServiceProviderConfiguration { - private List identityServers; + private List identityServiceProviders; - @XmlElementWrapper(name = "IdentityServers") - @XmlElement(name = "IdentityServerDTO") - public List getIdentityServers() { - return identityServers; + @XmlElementWrapper(name = "IdentityServiceProviders") + @XmlElement(name = "IdentityServiceProvider") + public List getIdentityServiceProviders() { + return identityServiceProviders; } - public IdentityServerDetail getIdentityServerDetailByProviderName(String identityServerProviderName) { - for (IdentityServerDetail identityServerDetail : identityServers) { - if (identityServerDetail.getProviderName().equals(identityServerProviderName)) { - return identityServerDetail; + public IdentityServiceProvider getIdentityServerDetailByProviderName(String identityServiceProviderName) { + for (IdentityServiceProvider identityServiceProvider : identityServiceProviders) { + if (identityServiceProvider.getProviderName().equals(identityServiceProviderName)) { + return identityServiceProvider; } } return null; } - public void setIdentityServers(List identityServers) { - this.identityServers = identityServers; + public void setIdentityServiceProviders(List identityServiceProviders) { + this.identityServiceProviders = identityServiceProviders; } } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java index 9fe44a72e76..ba7f00b24ae 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java @@ -26,6 +26,36 @@ import java.util.List; public interface SPApplicationDAO { + /** + * Use to check if an identity server exists with the same name + * + * @param name name of the identity server + * @return if identity server with the given name exists + */ + boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException; + + /** + * Use to check if an identity server exists with the same url + * + * @param url name of the identity server + * @return if identity server with the given url exists + */ + boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException; + + /** + * Update existing identity server in the database + * + * @param updatedIdentityServerDTO bean with the updated fields of the identity server + */ + void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId) + throws ApplicationManagementDAOException; + + /** + * Create new identity server in the database + * + * @param identityServerDTO DTO bean with the details of identity server to be created + * @return id of the newly created identity server + */ int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException; /** @@ -91,4 +121,11 @@ public interface SPApplicationDAO { */ void deleteApplicationFromServiceProviders(int applicationId, int tenantId) throws ApplicationManagementDAOException; + /** + * Delete identity server from db + * + * @param id of the identity server to be deleted + * @throws ApplicationManagementDAOException if any db error occurred + */ + void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java index ab2ca8cca69..6641d228bfa 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -29,6 +29,7 @@ import io.entgra.application.mgt.core.exception.UnexpectedServerErrorException; import io.entgra.application.mgt.core.util.DAOUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -41,7 +42,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class); @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -68,7 +69,7 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -99,16 +100,136 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } + @Override + public boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT ID AS ID " + + "FROM AP_IDENTITY_SERVER " + + "WHERE " + + "LOWER(NAME) = LOWER(?) AND " + + "TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, name); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check if identity server name: " + name + + " already exist"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check if identity server with the name " + name + + " already exists."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT ID AS ID " + + "FROM AP_IDENTITY_SERVER " + + "WHERE " + + "LOWER(URL) = LOWER(?) AND " + + "TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, url); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check if identity server url: " + url + + " already exist"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check if identity server with the url " + url + + " already exists."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId) + throws ApplicationManagementDAOException { + String sql = "UPDATE AP_IDENTITY_SERVER " + + "SET "; + if (updatedIdentityServerDTO.getName() != null) { + sql += "NAME = ?, "; + } + if (updatedIdentityServerDTO.getUrl() != null) { + sql += "URL = ?, "; + } + if (updatedIdentityServerDTO.getProviderName() != null) { + sql += "PROVIDER_NAME = ?, "; + } + if (updatedIdentityServerDTO.getUsername() != null) { + sql += "USERNAME = ?, "; + } + if (updatedIdentityServerDTO.getPassword() != null) { + sql += "PASSWORD = ?, "; + } + if (updatedIdentityServerDTO.getDescription() != null) { + sql += "DESCRIPTION = ?, "; + } + sql += "API_PARAMS = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + + try { + int index = 1; + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + if (updatedIdentityServerDTO.getName() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getName()); + } + if (updatedIdentityServerDTO.getUrl() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getUrl()); + } + if (updatedIdentityServerDTO.getProviderName() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getProviderName()); + } + if (updatedIdentityServerDTO.getUsername() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getUsername()); + } + if (updatedIdentityServerDTO.getPassword() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getPassword()); + } + if (updatedIdentityServerDTO.getDescription() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getDescription()); + } + stmt.setString(index++, updatedIdentityServerDTO.constructApiParamsJsonString()); + stmt.setInt(index++, identityServerId); + stmt.setInt(index, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to update identity server."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when executing SQL to update identity server. Executed query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { log.debug("Request received in DAO Layer to create an identity server"); } String sql = "INSERT INTO AP_IDENTITY_SERVER " - + "(PROVIDER_NAME, " - + "NAME, " - + "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) " - + "VALUES (?, ?, ?, ?)"; + + "(PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -116,8 +237,8 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp stmt.setString(2, identityServerDTO.getName()); stmt.setString(3, identityServerDTO.getDescription()); stmt.setString(4, identityServerDTO.getUrl()); - stmt.setString(5, identityServerDTO.getApiUrl()); - stmt.setString(6, identityServerDTO.getUserName()); + stmt.setString(5, identityServerDTO.constructApiParamsJsonString()); + stmt.setString(6, identityServerDTO.getUsername()); stmt.setString(7, identityServerDTO.getPassword()); stmt.setInt(8, tenantId); stmt.executeUpdate(); @@ -338,4 +459,29 @@ public class GenericSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } + @Override + public void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete identity server with the id: " + id); + } + String sql = "DELETE FROM AP_IDENTITY_SERVER WHERE ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, id); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete an identity server with the id " + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete an identity server which has the id " + + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java index 828ad1acaee..6f76e115438 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -41,7 +41,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -68,7 +68,7 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp @Override public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -99,6 +99,128 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } + @Override + public boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP.ID AS ID " + + "FROM AP_IDENTITY_SERVER " + + "WHERE " + + "LOWER(URL) = LOWER(?) AND " + + "AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, url); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check if identity server url: " + url + + " already exist"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check if identity server with the url " + url + + " already exists."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP.ID AS ID " + + "FROM AP_IDENTITY_SERVER " + + "WHERE " + + "LOWER(NAME) = LOWER(?) AND " + + "AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, name); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check if identity server name: " + name + + " already exist"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check if identity server with the name " + name + + " already exists."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId) + throws ApplicationManagementDAOException { + String sql = "UPDATE AP_IDENTITY_SERVER " + + "SET "; + if (updatedIdentityServerDTO.getName() != null) { + sql += "NAME = ?, "; + } + if (updatedIdentityServerDTO.getUrl() != null) { + sql += "URL = ?, "; + } + if (updatedIdentityServerDTO.getProviderName() != null) { + sql += "PROVIDER_NAME = ?, "; + } + if (updatedIdentityServerDTO.getUsername() != null) { + sql += "USERNAME = ?, "; + } + if (updatedIdentityServerDTO.getPassword() != null) { + sql += "PASSWORD = ?, "; + } + if (updatedIdentityServerDTO.getDescription() != null) { + sql += "DESCRIPTION = ?, "; + } + sql += "API_PARAMS = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + + try { + int index = 1; + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + if (updatedIdentityServerDTO.getName() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getName()); + } + if (updatedIdentityServerDTO.getUrl() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getUrl()); + } + if (updatedIdentityServerDTO.getProviderName() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getProviderName()); + } + if (updatedIdentityServerDTO.getUsername() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getUsername()); + } + if (updatedIdentityServerDTO.getPassword() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getPassword()); + } + if (updatedIdentityServerDTO.getDescription() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getDescription()); + } + stmt.setString(index++, updatedIdentityServerDTO.constructApiParamsJsonString()); + stmt.setInt(index++, identityServerId); + stmt.setInt(index, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to update identity server."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when executing SQL to update identity server. Executed query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { @@ -107,8 +229,8 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp String sql = "INSERT INTO AP_IDENTITY_SERVER " + "(PROVIDER_NAME, " + "NAME, " - + "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) " - + "VALUES (?, ?, ?, ?)"; + + "DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -116,8 +238,8 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp stmt.setString(2, identityServerDTO.getName()); stmt.setString(3, identityServerDTO.getDescription()); stmt.setString(4, identityServerDTO.getUrl()); - stmt.setString(5, identityServerDTO.getApiUrl()); - stmt.setString(6, identityServerDTO.getUserName()); + stmt.setString(5, identityServerDTO.constructApiParamsJsonString()); + stmt.setString(6, identityServerDTO.getUsername()); stmt.setString(7, identityServerDTO.getPassword()); stmt.setInt(8, tenantId); stmt.executeUpdate(); @@ -338,4 +460,29 @@ public class OracleSPApplicationDAOImpl extends AbstractDAOImpl implements SPAp } } + @Override + public void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete identity server with the id: " + id); + } + String sql = "DELETE FROM AP_IDENTITY_SERVER WHERE ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, id); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete an identity server with the id " + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete an identity server which has the id " + + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java index 629b0b3df88..87f0e1fbcfe 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -41,7 +41,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -68,7 +68,7 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -99,6 +99,128 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S } } + @Override + public boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP.ID AS ID " + + "FROM AP_IDENTITY_SERVER " + + "WHERE " + + "LOWER(URL) = LOWER(?) AND " + + "AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, url); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check if identity server url: " + url + + " already exist"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check if identity server with the url " + url + + " already exists."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP.ID AS ID " + + "FROM AP_IDENTITY_SERVER " + + "WHERE " + + "LOWER(NAME) = LOWER(?) AND " + + "AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, name); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check if identity server name: " + name + + " already exist"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check if identity server with the name " + name + + " already exists."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId) + throws ApplicationManagementDAOException { + String sql = "UPDATE AP_IDENTITY_SERVER " + + "SET "; + if (updatedIdentityServerDTO.getName() != null) { + sql += "NAME = ?, "; + } + if (updatedIdentityServerDTO.getUrl() != null) { + sql += "URL = ?, "; + } + if (updatedIdentityServerDTO.getProviderName() != null) { + sql += "PROVIDER_NAME = ?, "; + } + if (updatedIdentityServerDTO.getUsername() != null) { + sql += "USERNAME = ?, "; + } + if (updatedIdentityServerDTO.getPassword() != null) { + sql += "PASSWORD = ?, "; + } + if (updatedIdentityServerDTO.getDescription() != null) { + sql += "DESCRIPTION = ?, "; + } + sql += "API_PARAMS = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + + try { + int index = 1; + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + if (updatedIdentityServerDTO.getName() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getName()); + } + if (updatedIdentityServerDTO.getUrl() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getUrl()); + } + if (updatedIdentityServerDTO.getProviderName() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getProviderName()); + } + if (updatedIdentityServerDTO.getUsername() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getUsername()); + } + if (updatedIdentityServerDTO.getPassword() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getPassword()); + } + if (updatedIdentityServerDTO.getDescription() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getDescription()); + } + stmt.setString(index++, updatedIdentityServerDTO.constructApiParamsJsonString()); + stmt.setInt(index++, identityServerId); + stmt.setInt(index, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to update identity server."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when executing SQL to update identity server. Executed query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { @@ -107,8 +229,8 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S String sql = "INSERT INTO AP_IDENTITY_SERVER " + "(PROVIDER_NAME, " + "NAME, " - + "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) " - + "VALUES (?, ?, ?, ?)"; + + "DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -116,8 +238,8 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S stmt.setString(2, identityServerDTO.getName()); stmt.setString(3, identityServerDTO.getDescription()); stmt.setString(4, identityServerDTO.getUrl()); - stmt.setString(5, identityServerDTO.getApiUrl()); - stmt.setString(6, identityServerDTO.getUserName()); + stmt.setString(5, identityServerDTO.constructApiParamsJsonString()); + stmt.setString(6, identityServerDTO.getUsername()); stmt.setString(7, identityServerDTO.getPassword()); stmt.setInt(8, tenantId); stmt.executeUpdate(); @@ -338,4 +460,29 @@ public class PostgreSQLSPApplicationDAOImpl extends AbstractDAOImpl implements S } } + @Override + public void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete identity server with the id: " + id); + } + String sql = "DELETE FROM AP_IDENTITY_SERVER WHERE ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, id); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete an identity server with the id " + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete an identity server which has the id " + + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java index e9435702862..f0b676501d0 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -41,7 +41,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public List getIdentityServers(int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ?"; try { @@ -68,7 +68,7 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S @Override public IdentityServerDTO getIdentityServerById(int id, int tenantId) throws ApplicationManagementDAOException { - String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID " + String sql = "SELECT ID, PROVIDER_NAME, NAME, DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID " + "FROM AP_IDENTITY_SERVER " + "WHERE TENANT_ID = ? AND " + "ID = ?"; @@ -99,6 +99,128 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S } } + @Override + public boolean isExistingIdentityServerUrl(String url, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP.ID AS ID " + + "FROM AP_IDENTITY_SERVER " + + "WHERE " + + "LOWER(URL) = LOWER(?) AND " + + "AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, url); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check if identity server url: " + url + + " already exist"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check if identity server with the url " + url + + " already exists."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public boolean isExistingIdentityServerName(String name, int tenantId) throws ApplicationManagementDAOException { + String sql = "SELECT AP_APP.ID AS ID " + + "FROM AP_IDENTITY_SERVER " + + "WHERE " + + "LOWER(NAME) = LOWER(?) AND " + + "AP_APP.TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)){ + stmt.setString(1, name); + stmt.setInt(2, tenantId); + try (ResultSet rs = stmt.executeQuery()){ + return rs.next(); + } + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to check if identity server name: " + name + + " already exist"; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing query to check if identity server with the name " + name + + " already exists."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + + @Override + public void updateIdentityServer(IdentityServerDTO updatedIdentityServerDTO, int tenantId, int identityServerId) + throws ApplicationManagementDAOException { + String sql = "UPDATE AP_IDENTITY_SERVER " + + "SET "; + if (updatedIdentityServerDTO.getName() != null) { + sql += "NAME = ?, "; + } + if (updatedIdentityServerDTO.getUrl() != null) { + sql += "URL = ?, "; + } + if (updatedIdentityServerDTO.getProviderName() != null) { + sql += "PROVIDER_NAME = ?, "; + } + if (updatedIdentityServerDTO.getUsername() != null) { + sql += "USERNAME = ?, "; + } + if (updatedIdentityServerDTO.getPassword() != null) { + sql += "PASSWORD = ?, "; + } + if (updatedIdentityServerDTO.getDescription() != null) { + sql += "DESCRIPTION = ?, "; + } + sql += "API_PARAMS = ? " + + "WHERE ID = ? AND TENANT_ID = ?"; + + try { + int index = 1; + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + if (updatedIdentityServerDTO.getName() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getName()); + } + if (updatedIdentityServerDTO.getUrl() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getUrl()); + } + if (updatedIdentityServerDTO.getProviderName() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getProviderName()); + } + if (updatedIdentityServerDTO.getUsername() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getUsername()); + } + if (updatedIdentityServerDTO.getPassword() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getPassword()); + } + if (updatedIdentityServerDTO.getDescription() != null) { + stmt.setString(index++, updatedIdentityServerDTO.getDescription()); + } + stmt.setString(index++, updatedIdentityServerDTO.constructApiParamsJsonString()); + stmt.setInt(index++, identityServerId); + stmt.setInt(index, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to update identity server."; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred when executing SQL to update identity server. Executed query: " + sql; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + @Override public int createIdentityServer(IdentityServerDTO identityServerDTO, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { @@ -107,8 +229,8 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S String sql = "INSERT INTO AP_IDENTITY_SERVER " + "(PROVIDER_NAME, " + "NAME, " - + "DESCRIPTION, URL, API_URL, USERNAME, PASSWORD, TENANT_ID) " - + "VALUES (?, ?, ?, ?)"; + + "DESCRIPTION, URL, API_PARAMS, USERNAME, PASSWORD, TENANT_ID) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; try { Connection conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { @@ -116,8 +238,8 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S stmt.setString(2, identityServerDTO.getName()); stmt.setString(3, identityServerDTO.getDescription()); stmt.setString(4, identityServerDTO.getUrl()); - stmt.setString(5, identityServerDTO.getApiUrl()); - stmt.setString(6, identityServerDTO.getUserName()); + stmt.setString(5, identityServerDTO.constructApiParamsJsonString()); + stmt.setString(6, identityServerDTO.getUsername()); stmt.setString(7, identityServerDTO.getPassword()); stmt.setInt(8, tenantId); stmt.executeUpdate(); @@ -326,16 +448,41 @@ public class SQLServerSPApplicationDAOImpl extends AbstractDAOImpl implements S stmt.executeUpdate(); } } catch (DBConnectionException e) { - String msg = "Error occurred while obtaining the DB connection to create an sp application mapping which has " + String msg = "Error occurred while obtaining the DB connection to delete an sp application mapping which has " + "application id " + applicationId; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } catch (SQLException e) { - String msg = "Error occurred while executing SQL to create an application which has application id " + String msg = "Error occurred while executing SQL to delete an application which has application id " + applicationId; log.error(msg, e); throw new ApplicationManagementDAOException(msg, e); } } + @Override + public void deleteIdentityServer(int id, int tenantId) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to delete identity server with the id: " + id); + } + String sql = "DELETE FROM AP_IDENTITY_SERVER WHERE ID = ? AND TENANT_ID = ?"; + try { + Connection conn = this.getDBConnection(); + try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { + stmt.setInt(1, id); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } + } catch (DBConnectionException e) { + String msg = "Error occurred while obtaining the DB connection to delete an identity server with the id " + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while executing SQL to delete an identity server which has the id " + + id; + log.error(msg, e); + throw new ApplicationManagementDAOException(msg, e); + } + } + } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/ISServiceProviderApplicationService.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/ISServiceProviderApplicationService.java new file mode 100644 index 00000000000..fe2eec16e32 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/ISServiceProviderApplicationService.java @@ -0,0 +1,68 @@ +package io.entgra.application.mgt.core.identityserver.serviceprovider; + +import io.entgra.application.mgt.common.SPApplication; +import io.entgra.application.mgt.common.SPApplicationListResponse; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; +import io.entgra.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.application.mgt.common.exception.InvalidConfigurationException; +import io.entgra.application.mgt.core.config.ConfigurationManager; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.lang.reflect.Constructor; +import java.util.List; + +public interface ISServiceProviderApplicationService { + + Log log = LogFactory.getLog(ISServiceProviderApplicationService.class); + + static ISServiceProviderApplicationService of(String identityServerName) throws InvalidConfigurationException { + String className = ConfigurationManager.getInstance().getIdentityServerConfiguration(). + getIdentityServerDetailByProviderName(identityServerName).getProviderClassName(); + try { + Class theClass = Class.forName(className); + Constructor constructor = theClass.getConstructor(); + return constructor.newInstance(); + } catch (Exception e) { + String msg = "Unable to get instance of " + className; + log.error(msg, e); + throw new InvalidConfigurationException(msg, e); + } + } + + /** + * Use to get IS Service specific api params + * + * @return IS Service specific api params + */ + List getRequiredApiParams(); + + /** + * Check if service provider application exists + * + * @param identityServer {@link IdentityServerDTO} + * @param spAppId uid of the service provider + * @return if service provider exist + * @throws ApplicationManagementException + */ + boolean isSPApplicationExist(IdentityServerDTO identityServer, String spAppId) throws ApplicationManagementException; + + /** + * Get service provider by identity server id and service provider uid + * @param identityServer {@link IdentityServerDTO} + * @param spAppId uid of service provider to be retrieved + * @return {@link SPApplication} + * @throws ApplicationManagementException + */ + SPApplication retrieveSPApplication(IdentityServerDTO identityServer, String spAppId) throws ApplicationManagementException; + + /** + * Retrieve service provider apps from identity server + * + * @param identityServer {@link IdentityServerDTO} + * @return {@link SPApplicationListResponse} + * @throws ApplicationManagementException + */ + SPApplicationListResponse retrieveSPApplications(IdentityServerDTO identityServer, Integer limit, Integer offset) + throws ApplicationManagementException; +} diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java new file mode 100644 index 00000000000..fad3c6b5ba2 --- /dev/null +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. 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 io.entgra.application.mgt.core.identityserver.serviceprovider.impl; + +import com.google.gson.Gson; +import io.entgra.application.mgt.common.SPApplication; +import io.entgra.application.mgt.common.SPApplicationListResponse; +import io.entgra.application.mgt.common.dto.IdentityServerDTO; +import io.entgra.application.mgt.common.exception.ApplicationManagementException; +import io.entgra.application.mgt.common.exception.IdentityServerManagementException; +import io.entgra.application.mgt.core.identityserver.serviceprovider.ISServiceProviderApplicationService; +import io.entgra.application.mgt.core.util.Constants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.wso2.carbon.device.mgt.core.common.util.HttpUtil; +import javax.ws.rs.core.HttpHeaders; +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +public class WSO2IAMSPApplicationService implements ISServiceProviderApplicationService { + + private static final List REQUIRED_API_PARAM_LIST; + private static final String TENANT_DOMAIN = "Tenant domain"; + private static final String SP_APPLICATION_API_CONTEXT = "/t/%s/api/server/v1/applications"; + private static final Log log = LogFactory.getLog(WSO2IAMSPApplicationService.class); + + static { + REQUIRED_API_PARAM_LIST = Collections.singletonList(TENANT_DOMAIN); + } + + public List getRequiredApiParams() { + return REQUIRED_API_PARAM_LIST; + } + + public boolean isSPApplicationExist(IdentityServerDTO identityServer, String spAppId) throws ApplicationManagementException { + SPApplication application = retrieveSPApplication(identityServer, spAppId); + return application != null; + } + + public SPApplication retrieveSPApplication(IdentityServerDTO identityServer, String spAppId) throws ApplicationManagementException { + HttpGet req = new HttpGet(); + String uriString = constructAPIUrl(identityServer); + uriString += Constants.FORWARD_SLASH + spAppId; + req.setURI(HttpUtil.createURI(uriString)); + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpResponse response = invokeISAPI(identityServer, client, req); + String responseBody = HttpUtil.getResponseString(response); + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + return new Gson().fromJson(responseBody, + SPApplication.class); + } + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { + return null; + } + String msg = constructErrorMessage(response); + log.error(msg); + throw new IdentityServerManagementException(msg); + } catch (IOException e) { + String msg = "Error occurred while calling SP Applications API. Make sure identity server is up and running"; + log.error(msg, e); + throw new IdentityServerManagementException(msg); + } finally { + try { + client.close(); + } catch (IOException e) { + log.error("Error occurred while closing http connection"); + } + } + } + + private String constructErrorMessage(HttpResponse response) { + String msg = "Error occurred while calling SP Applications API"; + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + msg += ". Make sure provided identity Server credentials are valid"; + } + return msg; + } + + public SPApplicationListResponse retrieveSPApplications(IdentityServerDTO identityServer, Integer limit, Integer offset) + throws ApplicationManagementException { + HttpGet req = new HttpGet(); + String uriString = constructAPIUrl(identityServer); + uriString += Constants.URI_QUERY_SEPARATOR + Constants.LIMIT_QUERY_PARAM + Constants.QUERY_KEY_VALUE_SEPARATOR + + limit; + uriString += Constants.QUERY_STRING_SEPARATOR + Constants.OFFSET_QUERY_PARAM + Constants.QUERY_KEY_VALUE_SEPARATOR + + offset; + req.setURI(HttpUtil.createURI(uriString)); + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpResponse response = invokeISAPI(identityServer, client, req); + String responseBody = HttpUtil.getResponseString(response); + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + return new Gson().fromJson(responseBody, + SPApplicationListResponse.class); + } + String msg = constructErrorMessage(response); + log.error(msg); + throw new IdentityServerManagementException(msg); + } catch (IOException e) { + String msg = "Error occurred while calling SP Applications API. Make sure identity server is up and running"; + log.error(msg, e); + throw new IdentityServerManagementException(msg); + } finally { + try { + client.close(); + } catch (IOException e) { + log.error("Error occurred while closing http connection"); + } + } + } + + private HttpResponse invokeISAPI(IdentityServerDTO identityServer, HttpClient client, HttpGet request) throws IOException { + setBasicAuthHeader(identityServer, request); + return client.execute(request); + } + + private void setBasicAuthHeader(IdentityServerDTO identityServer, HttpRequestBase request) { + String basicAuthHeader = HttpUtil.getBasicAuthBase64Header(identityServer.getUsername(), + identityServer.getPassword()); + request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader); + } + + private String constructAPIUrl(IdentityServerDTO identityServer) { + String identityServerUrl = identityServer.getUrl(); + // add "/" at the end, if the server url doesn't contain "/" at the end + if (identityServerUrl.charAt(identityServerUrl.length() - 1) != Constants.FORWARD_SLASH.charAt(0)) { + identityServerUrl += Constants.FORWARD_SLASH; + } + return identityServerUrl + String.format(SP_APPLICATION_API_CONTEXT, identityServer.getApiParams().get(TENANT_DOMAIN)); + } +} \ No newline at end of file diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java index f1ed00f98e8..802a52f4c33 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -18,32 +18,42 @@ package io.entgra.application.mgt.core.impl; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.IdentityServerResponse; +import io.entgra.application.mgt.common.SPApplicationListResponse; import io.entgra.application.mgt.common.dto.IdentityServerDTO; import io.entgra.application.mgt.common.SPApplication; import io.entgra.application.mgt.common.dto.ApplicationDTO; +import io.entgra.application.mgt.common.dto.IdentityServiceProviderDTO; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.exception.DBConnectionException; import io.entgra.application.mgt.common.exception.TransactionManagementException; import io.entgra.application.mgt.common.response.Application; import io.entgra.application.mgt.common.services.ApplicationManager; import io.entgra.application.mgt.common.services.SPApplicationManager; +import io.entgra.application.mgt.core.config.ConfigurationManager; +import io.entgra.application.mgt.core.config.IdentityServiceProvider; import io.entgra.application.mgt.core.dao.ApplicationDAO; import io.entgra.application.mgt.core.dao.SPApplicationDAO; import io.entgra.application.mgt.core.dao.VisibilityDAO; import io.entgra.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import io.entgra.application.mgt.core.exception.ApplicationManagementDAOException; import io.entgra.application.mgt.core.exception.BadRequestException; +import io.entgra.application.mgt.core.exception.NotFoundException; +import io.entgra.application.mgt.core.identityserver.serviceprovider.ISServiceProviderApplicationService; import io.entgra.application.mgt.core.internal.DataHolder; import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager; import io.entgra.application.mgt.core.util.APIUtil; import io.entgra.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.application.mgt.core.util.ConnectionManagerUtil; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.commons.validator.routines.UrlValidator; import org.wso2.carbon.context.PrivilegedCarbonContext; + import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; public class SPApplicationManagerImpl implements SPApplicationManager { @@ -65,20 +75,27 @@ public class SPApplicationManagerImpl implements SPApplicationManager { this.spApplicationDAO = ApplicationManagementDAOFactory.getSPApplicationDAO(); } - public void addExistingApps(int identityServerId, List applications) throws ApplicationManagementException { - for (SPApplication application : applications) { - List existingApplications = getSPApplications(identityServerId, application.getId()); - application.setExistingApplications(existingApplications); + @Override + public IdentityServerResponse getIdentityServerResponse(int identityServerId) throws ApplicationManagementException { + IdentityServerDTO identityServerDTO = getIdentityServer(identityServerId); + return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO); + } + + private IdentityServerDTO getIdentityServer(int identityServerId) throws ApplicationManagementException { + IdentityServerDTO identityServerDTO = getIdentityServerFromDB(identityServerId); + if (identityServerDTO == null) { + String msg = "Identity server with the id: " + identityServerId + " does not exist"; + log.error(msg); + throw new NotFoundException(msg); } + return identityServerDTO; } - @Override - public IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException { + private IdentityServerDTO getIdentityServerFromDB(int identityServerId) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { ConnectionManagerUtil.openDBConnection(); - IdentityServerDTO identityServerDTO = spApplicationDAO.getIdentityServerById(identityServerId, tenantId); - return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO); + return spApplicationDAO.getIdentityServerById(identityServerId, tenantId); } catch (DBConnectionException e) { String msg = "Error occurred when getting database connection to get identity server with the id: " + identityServerId; log.error(msg, e); @@ -94,7 +111,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } @Override - public List getIdentityServers() throws ApplicationManagementException { + public List getIdentityServers() throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { ConnectionManagerUtil.openDBConnection(); @@ -115,16 +132,276 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } @Override - public IdentityServer createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException { + public IdentityServerResponse createIdentityServer(IdentityServerDTO identityServerDTO) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + validateIdentityServerCreateRequest(identityServerDTO); try { + ConnectionManagerUtil.beginDBTransaction(); int id = spApplicationDAO.createIdentityServer(identityServerDTO, tenantId); identityServerDTO.setId(id); + ConnectionManagerUtil.commitDBTransaction(); return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO); } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred while creating identity server " + identityServerDTO.getName(); log.error(msg, e); throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public IdentityServerResponse updateIdentityServer(IdentityServerDTO updateIdentityServerDTO, int id) + throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + IdentityServerDTO existingIdentityServerDTO = getIdentityServer(id); + validateIdentityServerUpdateRequest(updateIdentityServerDTO, existingIdentityServerDTO); + Map updatedApiParams = constructUpdatedApiParams(updateIdentityServerDTO, existingIdentityServerDTO); + updateIdentityServerDTO.setApiParams(updatedApiParams); + try { + ConnectionManagerUtil.beginDBTransaction(); + spApplicationDAO.updateIdentityServer(updateIdentityServerDTO, tenantId, id); + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while creating identity server " + updateIdentityServerDTO.getName(); + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + return getIdentityServerResponse(id); + } + + @Override + public void deleteIdentityServer(int id) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + validateIdentityServerDeleteRequest(id); + try { + ConnectionManagerUtil.beginDBTransaction(); + spApplicationDAO.deleteIdentityServer(id, tenantId); + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occurred while creating identity server with the id " + id; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + private void validateIdentityServerDeleteRequest(int identityServerId) throws ApplicationManagementException { + IdentityServerDTO identityServerDTO = getIdentityServerFromDB(identityServerId); + if (identityServerDTO == null) { + String msg = "Identity server with the id: " + identityServerId + " does not exist to delete"; + log.error(msg); + throw new BadRequestException(msg); + } + } + + private Map constructUpdatedApiParams(IdentityServerDTO updatedIdentityServerDTO, + IdentityServerDTO existingIdentityServerDTO) { + Map updatedApiParams = updatedIdentityServerDTO.getApiParams(); + Map existingApiParams = existingIdentityServerDTO.getApiParams(); + if (updatedIdentityServerDTO.getProviderName().equals(existingIdentityServerDTO.getProviderName())) { + existingApiParams.putAll(updatedApiParams); + return existingApiParams; + } + return updatedApiParams; + } + + /** + * Validate the identity server update request payload + * + * @param updateIdentityServerDTO of identity server update request + * @throws BadRequestException if any invalid payload found + */ + private void validateIdentityServerUpdateRequest(IdentityServerDTO updateIdentityServerDTO, + IdentityServerDTO existingIdentityServerDTO) throws ApplicationManagementException { + if (updateIdentityServerDTO.getProviderName() != null && + isIdentityServiceProviderNotConfigured(updateIdentityServerDTO.getProviderName())) { + String msg = "No such providers configured. Provider name: " + updateIdentityServerDTO.getProviderName(); + log.error(msg); + throw new BadRequestException(msg); + } + if (updateIdentityServerDTO.getName() != null) { + if (!updateIdentityServerDTO.getName().equalsIgnoreCase(existingIdentityServerDTO.getName()) + && isIdentityServerNameExist(updateIdentityServerDTO.getName())) { + String msg = "Identity server already exist with the given name. Identity server name: " + updateIdentityServerDTO.getName(); + log.error(msg); + throw new BadRequestException(msg); + } + } + if (updateIdentityServerDTO.getUrl() != null) { + validateIdentityServerUrl(updateIdentityServerDTO.getUrl()); + if(!updateIdentityServerDTO.getUrl().equalsIgnoreCase(existingIdentityServerDTO.getUrl()) && + isIdentityServerUrlExist(updateIdentityServerDTO.getUrl())) { + String msg = "Identity server already exist with the given url. Identity server url: " + updateIdentityServerDTO.getUrl(); + log.error(msg); + throw new BadRequestException(msg); + } + } + validateUpdateIdentityServerRequestApiParam(updateIdentityServerDTO, existingIdentityServerDTO); + } + + + /** + * Validate the identity server create request payload + * + * @param identityServerDTO of identity server create request + * @throws BadRequestException if any invalid payload found + */ + private void validateIdentityServerCreateRequest(IdentityServerDTO identityServerDTO) throws ApplicationManagementException { + if (identityServerDTO.getUsername() == null) { + String msg = "Identity server username can not be null"; + log.error(msg); + throw new BadRequestException(msg); + } + if (identityServerDTO.getPassword() == null) { + String msg = "Identity server password can not be null"; + log.error(msg); + throw new BadRequestException(msg); + } + if (identityServerDTO.getName() == null) { + String msg = "Identity server name can not be null"; + log.error(msg); + throw new BadRequestException(msg); + } + if (identityServerDTO.getUrl() == null) { + String msg = "Identity server url can not be null"; + log.error(msg); + throw new BadRequestException(msg); + } + if (isIdentityServiceProviderNotConfigured(identityServerDTO.getProviderName())) { + String msg = "No such providers configured. Provider name: " + identityServerDTO.getProviderName(); + log.error(msg); + throw new BadRequestException(msg); + } + if (isIdentityServerNameExist(identityServerDTO.getName())) { + String msg = "Identity server already exist with the given name. Identity server name: " + identityServerDTO.getName(); + log.error(msg); + throw new BadRequestException(msg); + } + if (isIdentityServerUrlExist(identityServerDTO.getUrl())) { + String msg = "Identity server already exist with the given url. Identity server url: " + identityServerDTO.getUrl(); + log.error(msg); + throw new BadRequestException(msg); + } + validateCreateIdentityServerRequestApiParams(identityServerDTO); + validateIdentityServerUrl(identityServerDTO.getUrl()); + } + + private void validateIdentityServerUrl(String url) throws BadRequestException { + String[] schemes = {"http","https"}; + UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS); + if (!urlValidator.isValid(url)) { + String msg = "Identity server url is not a valid url"; + log.error(msg); + throw new BadRequestException(msg); + } + } + + private void validateUpdateIdentityServerRequestApiParam(IdentityServerDTO identityServerUpdateDTO, + IdentityServerDTO existingIdentityServerDTO) throws ApplicationManagementException { + ISServiceProviderApplicationService serviceProviderApplicationService = + ISServiceProviderApplicationService.of(existingIdentityServerDTO.getProviderName()); + List requiredApiParams = serviceProviderApplicationService.getRequiredApiParams(); + if (!identityServerUpdateDTO.getProviderName().equals(existingIdentityServerDTO.getProviderName())) { + validateAllRequiredParamsExists(identityServerUpdateDTO, requiredApiParams); + } + validateIfAnyInvalidParamExists(identityServerUpdateDTO, requiredApiParams); + } + + private void validateCreateIdentityServerRequestApiParams(IdentityServerDTO identityServerDTO) throws ApplicationManagementException { + ISServiceProviderApplicationService serviceProviderApplicationService = + ISServiceProviderApplicationService.of(identityServerDTO.getProviderName()); + List requiredApiParams = serviceProviderApplicationService.getRequiredApiParams(); + validateAllRequiredParamsExists(identityServerDTO, requiredApiParams); + validateIfAnyInvalidParamExists(identityServerDTO, requiredApiParams); + } + + private void validateAllRequiredParamsExists(IdentityServerDTO identityServerDTO, List requiredApiParams) + throws BadRequestException { + for (String param : requiredApiParams) { + if (identityServerDTO.getApiParams().get(param) == null) { + String msg = param + " api parameter is required for " + identityServerDTO.getProviderName() + ". " + + "Required api parameters: " + StringUtils.join(requiredApiParams, ","); + log.error(msg); + throw new BadRequestException(msg); + } + } + } + + private void validateIfAnyInvalidParamExists(IdentityServerDTO identityServerDTO, List requiredApiParams) + throws BadRequestException { + for (String param : identityServerDTO.getApiParamKeys()) { + if (!requiredApiParams.contains(param)) { + String msg = "Invalid api parameter. " + param + " is not required for " + identityServerDTO.getProviderName() + ". " + + "Required api parameters: " + StringUtils.join(requiredApiParams, ","); + throw new BadRequestException(msg); + } + } + } + + private boolean isIdentityServiceProviderNotConfigured(String providerName) { + List identityServiceProviders = ConfigurationManager.getInstance().getIdentityServerConfiguration(). + getIdentityServiceProviders(); + return identityServiceProviders.stream().noneMatch(provider -> provider.getProviderName().equals(providerName)); + } + + @Override + public boolean isIdentityServerNameExist(String name) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + ConnectionManagerUtil.openDBConnection(); + return spApplicationDAO.isExistingIdentityServerName(name, tenantId); + } catch (ApplicationManagementDAOException | DBConnectionException e) { + String msg = "Error occurred while checking if identity server with the name " + name + " exists."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public boolean isIdentityServerUrlExist(String url) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + ConnectionManagerUtil.openDBConnection(); + return spApplicationDAO.isExistingIdentityServerUrl(url, tenantId); + } catch (ApplicationManagementDAOException | DBConnectionException e) { + String msg = "Error occurred while checking if identity server with the url " + url + " exists."; + log.error(msg, e); + throw new ApplicationManagementException(msg, e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public SPApplicationListResponse retrieveSPApplicationFromIdentityServer(int identityServerId, Integer offset, Integer limit) + throws ApplicationManagementException { + IdentityServerDTO identityServer = getIdentityServer(identityServerId); + ISServiceProviderApplicationService serviceProviderApplicationService = ISServiceProviderApplicationService.of(identityServer.getProviderName()); + SPApplicationListResponse spApplicationListResponse = serviceProviderApplicationService.retrieveSPApplications(identityServer, offset, limit); + addExistingApps(identityServerId, spApplicationListResponse.getApplications()); + return spApplicationListResponse; + } + + /** + * This method adds existing consumer applications of service providers to the SPApplication bean + * + * @param identityServerId identity server id of the service provider + * @param spApplications Service providers list to which the existing applications should be added + * @throws ApplicationManagementException if error occurred while adding existing applications + */ + private void addExistingApps(int identityServerId, List spApplications) throws ApplicationManagementException { + for (SPApplication spApplication : spApplications) { + List existingApplications = getSPApplications(identityServerId, spApplication.getId()); + spApplication.setExistingApplications(existingApplications); } } @@ -174,7 +451,8 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } - public void validateAttachAppsRequest(int identityServerId, List appIds) throws ApplicationManagementException { + public void validateAttachAppsRequest(int identityServerId, String serviceProviderId, List appIds) throws ApplicationManagementException { + validateServiceProviderUID(identityServerId, serviceProviderId); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { ConnectionManagerUtil.openDBConnection(); @@ -197,6 +475,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } public void validateDetachAppsRequest(int identityServerId, String spId, List appIds) throws ApplicationManagementException { + validateServiceProviderUID(identityServerId, spId); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { ConnectionManagerUtil.openDBConnection(); @@ -219,6 +498,50 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + @Override + public List getIdentityServiceProviders() throws ApplicationManagementException { + List identityServiceProviders = ConfigurationManager.getInstance(). + getIdentityServerConfiguration().getIdentityServiceProviders(); + List identityServiceProviderDTOS = new ArrayList<>(); + for (IdentityServiceProvider identityServiceProvider : identityServiceProviders) { + try { + identityServiceProviderDTOS.add(APIUtil.identityServiceProviderToDTO(identityServiceProvider)); + } catch (ApplicationManagementException e) { + String msg = "Identity service provider configuration file is invalid. Hence failed to proceed."; + log.error(msg); + throw new ApplicationManagementException(msg); + } + } + return identityServiceProviderDTOS; + } + + /** + * Responsible for validating service provider in requests + * + * @param identityServerId identity server id of the service provider + * @param spUID uid of the service provider + * @throws ApplicationManagementException if invalid service provider + */ + private void validateServiceProviderUID(int identityServerId, String spUID) throws + ApplicationManagementException { + IdentityServerDTO identityServer = getIdentityServer(identityServerId); + ISServiceProviderApplicationService serviceProviderApplicationService = ISServiceProviderApplicationService.of(identityServer.getProviderName()); + try { + boolean isSPAppExists = serviceProviderApplicationService. + isSPApplicationExist(identityServer, spUID); + if (!isSPAppExists) { + String errMsg = "Service provider with the uid " + spUID + " does not exist."; + log.error(errMsg); + throw new BadRequestException(errMsg); + } + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to validate service provider uid"; + log.error(errMsg, e); + throw new ApplicationManagementException(errMsg, e); + } + } + + public void attachSPApplications(int identityServerId, String spUID, List appIds) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { @@ -259,6 +582,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager { @Override public Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException { + validateServiceProviderUID(identityServerId, spId); ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); ApplicationDTO applicationDTO = applicationManager.uploadReleaseArtifactIfExist(app); if (log.isDebugEnabled()) { diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java index 00229f67604..e85e57dfd6e 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/APIUtil.java @@ -18,9 +18,12 @@ package io.entgra.application.mgt.core.util; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.IdentityServerResponse; import io.entgra.application.mgt.common.dto.IdentityServerDTO; -import io.entgra.application.mgt.core.config.IdentityServerDetail; +import io.entgra.application.mgt.common.dto.IdentityServiceProviderDTO; +import io.entgra.application.mgt.common.exception.InvalidConfigurationException; +import io.entgra.application.mgt.core.config.IdentityServiceProvider; +import io.entgra.application.mgt.core.identityserver.serviceprovider.ISServiceProviderApplicationService; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -366,19 +369,28 @@ public class APIUtil { return applicationReleaseDTO; } - public static IdentityServer identityServerDtoToIdentityServerResponse(IdentityServerDTO identityServerDTO) { - IdentityServer identityServer = new IdentityServer(); + public static IdentityServiceProviderDTO identityServiceProviderToDTO(IdentityServiceProvider identityServiceProvider) + throws InvalidConfigurationException { + ISServiceProviderApplicationService serviceProviderApplicationService = + ISServiceProviderApplicationService.of(identityServiceProvider.getProviderName()); + IdentityServiceProviderDTO identityServiceProviderDTO = new IdentityServiceProviderDTO(); + identityServiceProviderDTO.setName(identityServiceProvider.getProviderName()); + identityServiceProviderDTO.setRequiredApiParams(serviceProviderApplicationService.getRequiredApiParams()); + return identityServiceProviderDTO; + } + + public static IdentityServerResponse identityServerDtoToIdentityServerResponse(IdentityServerDTO identityServerDTO) { + IdentityServerResponse identityServer = new IdentityServerResponse(); identityServer.setId(identityServerDTO.getId()); identityServer.setProviderName(identityServerDTO.getProviderName()); identityServer.setName(identityServerDTO.getName()); identityServer.setDescription(identityServerDTO.getDescription()); identityServer.setUrl(identityServerDTO.getUrl()); - identityServer.setApiUrl(identityServerDTO.getApiUrl()); - identityServer.setUserName(identityServerDTO.getUserName()); - identityServer.setPassword(identityServerDTO.getPassword()); - IdentityServerDetail identityServerDetail = ConfigurationManager.getInstance().getIdentityServerConfiguration() + identityServer.setApiParamList(identityServerDTO.getApiParams()); + identityServer.setUsername(identityServerDTO.getUsername()); + IdentityServiceProvider identityServiceProvider = ConfigurationManager.getInstance().getIdentityServerConfiguration() .getIdentityServerDetailByProviderName(identityServerDTO.getProviderName()); - String serviceProviderAppsUrl = identityServerDTO.getUrl() + Constants.FORWARD_SLASH + identityServerDetail.getServiceProvidersPageUri(); + String serviceProviderAppsUrl = identityServerDTO.getUrl() + identityServiceProvider.getServiceProvidersPageUri(); identityServer.setServiceProviderAppsUrl(serviceProviderAppsUrl); return identityServer; } diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java index 4082edb492d..fd9b4577df6 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java @@ -60,6 +60,9 @@ public class Constants { public static final String IS_APP_DEFAULT_PAYMENT_CURRENCY = "$"; public static final String IS_APP_DEFAULT_VERSION = "1.0"; public static final String FORWARD_SLASH = "/"; + public static final String URI_QUERY_SEPARATOR = "?"; + public static final String QUERY_STRING_SEPARATOR = "&"; + public static final String QUERY_KEY_VALUE_SEPARATOR = "="; public static final String ANY = "ANY"; public static final String DEFAULT_PCK_NAME = "default.app.com"; public static final String ALL = "ALL"; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java index 4291d95525d..88e53bfe6b7 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/DAOUtil.java @@ -40,7 +40,9 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -207,8 +209,10 @@ public class DAOUtil { identityServerDTO.setName(rs.getString("NAME")); identityServerDTO.setDescription(rs.getString("DESCRIPTION")); identityServerDTO.setUrl(rs.getString("URL")); - identityServerDTO.setApiUrl(rs.getString("API_URI")); - identityServerDTO.setUserName(rs.getString("USERNAME")); + String apiParamsJson = rs.getString("API_PARAMS"); + Map apiParams = new Gson().fromJson(apiParamsJson, new TypeToken>() {}.getType()); + identityServerDTO.setApiParams(apiParams); + identityServerDTO.setUsername(rs.getString("USERNAME")); identityServerDTO.setPassword(rs.getString("PASSWORD")); identityServerDTOS.add(identityServerDTO); } diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java index ffaa3c7a8ab..299f44b5487 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java @@ -33,8 +33,10 @@ import io.swagger.annotations.Tag; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; +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; @@ -104,6 +106,22 @@ public interface SPApplicationService { String SCOPE = "scope"; + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/identity-servers/identity-service-providers") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "get available identity service providers", + tags = "Identity Server Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") + }) + } + ) + Response getIdentityServiceProviders(); + @GET @Produces(MediaType.APPLICATION_JSON) @Path("/identity-servers") @@ -120,6 +138,21 @@ public interface SPApplicationService { ) Response getIdentityServers(); + @Path("/identity-servers/{id}") + @DELETE + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "get identity server by id", + tags = "Identity Server Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:connect") + }) + } + ) + Response deleteIdentityServer(@PathParam("id") int id); + @GET @Produces(MediaType.APPLICATION_JSON) @Path("/identity-servers/{id}") @@ -152,6 +185,54 @@ public interface SPApplicationService { ) Response createIdentityServer(IdentityServerDTO identityServerDTO); + @PUT + @Produces(MediaType.APPLICATION_JSON) + @Path("/identity-servers/{id}") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "edit existing identity server", + tags = "Identity Server Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:connect") + }) + } + ) + Response updateIdentityServer(IdentityServerDTO identityServerDTO, @PathParam("id") int id); + + @GET + @Path("/identity-servers/identity-server-name") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Check if identity server name is already exists", + tags = "Identity Server Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") + }) + } + ) + Response isIdentityServerNameExists( + @QueryParam("identityServerName") String identityServerName); + + @GET + @Path("/identity-servers/identity-server-url") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Check if identity server url is already exists", + tags = "Identity Server Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:service-provider:view") + }) + } + ) + Response isIdentityServerUrlExists( + @QueryParam("identityServerUrl") String identityServerUrl); + /** * This method is used to register an APIM application for tenant domain. */ diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java index 0fac1122115..297805644d4 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -18,10 +18,10 @@ package io.entgra.application.mgt.publisher.api.services.impl; -import io.entgra.application.mgt.common.IdentityServer; +import io.entgra.application.mgt.common.IdentityServerResponse; import io.entgra.application.mgt.common.dto.IdentityServerDTO; -import io.entgra.application.mgt.common.IdentityServerList; import io.entgra.application.mgt.common.SPApplicationListResponse; +import io.entgra.application.mgt.common.dto.IdentityServiceProviderDTO; import io.entgra.application.mgt.common.exception.ApplicationManagementException; import io.entgra.application.mgt.common.exception.RequestValidatingException; import io.entgra.application.mgt.common.response.Application; @@ -31,13 +31,17 @@ import io.entgra.application.mgt.common.wrapper.CustomAppWrapper; import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; import io.entgra.application.mgt.common.wrapper.WebAppWrapper; import io.entgra.application.mgt.core.exception.BadRequestException; +import io.entgra.application.mgt.core.exception.NotFoundException; import io.entgra.application.mgt.core.util.APIUtil; import io.entgra.application.mgt.publisher.api.services.SPApplicationService; -import io.entgra.application.mgt.publisher.api.services.util.SPAppRequestHandlerUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; 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; @@ -49,15 +53,31 @@ import java.util.List; @Produces(MediaType.APPLICATION_JSON) @Path("/identity-server-applications") public class SPApplicationServiceImpl implements SPApplicationService { + private static final Log log = LogFactory.getLog(SPApplicationServiceImpl.class); + @Path("/identity-servers/identity-service-providers") + @GET + @Override + public Response getIdentityServiceProviders() { + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + try { + List identityServiceProviders = spAppManager.getIdentityServiceProviders(); + return Response.status(Response.Status.OK).entity(identityServiceProviders).build(); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while getting identity service providers"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } + @Path("/identity-servers") @GET @Override public Response getIdentityServers() { try { SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); - List identityServers = spAppManager.getIdentityServers(); + List identityServers = spAppManager.getIdentityServers(); return Response.status(Response.Status.OK).entity(identityServers).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; @@ -66,14 +86,37 @@ public class SPApplicationServiceImpl implements SPApplicationService { } } + @Path("/identity-servers/{id}") + @DELETE + @Override + public Response deleteIdentityServer(@PathParam("id") int id) { + try { + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + spAppManager.deleteIdentityServer(id); + return Response.status(Response.Status.OK).entity("Successfully deleted identity server").build(); + } catch (NotFoundException e) { + String msg = "Identity server with the id " + id + " does not exist."; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; + log.error(errMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build(); + } + } + @Path("/identity-servers/{id}") @GET @Override public Response getIdentityServer(@PathParam("id") int id) { try { SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); - IdentityServer identityServer = spAppManager.getIdentityServer(id); + IdentityServerResponse identityServer = spAppManager.getIdentityServerResponse(id); return Response.status(Response.Status.OK).entity(identityServer).build(); + } catch (NotFoundException e) { + String msg = "Identity server with the id " + id + " does not exist."; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; log.error(errMsg, e); @@ -81,14 +124,96 @@ public class SPApplicationServiceImpl implements SPApplicationService { } } + @Path("/identity-servers/{id}") + @PUT + @Override + public Response updateIdentityServer(IdentityServerDTO identityServerDTO, @PathParam("id") int id) { + try { + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + IdentityServerResponse identityServerResponse = spAppManager.updateIdentityServer(identityServerDTO, id); + return Response.status(Response.Status.OK).entity(identityServerResponse).build(); + } catch (NotFoundException e) { + String msg = "Identity server with the id " + id + " does not exist."; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (BadRequestException e) { + String errMsg = "Identity server request payload is invalid"; + log.error(errMsg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; + log.error(errMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build(); + } + } + + @Path("/identity-servers") @POST @Override public Response createIdentityServer(IdentityServerDTO identityServerDTO) { try { SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); - IdentityServer identityServer = spAppManager.createIdentityServer(identityServerDTO); + IdentityServerResponse identityServer = spAppManager.createIdentityServer(identityServerDTO); return Response.status(Response.Status.CREATED).entity(identityServer).build(); + } catch (BadRequestException e) { + String errMsg = "Identity server request payload is invalid"; + log.error(errMsg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; + log.error(errMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build(); + } + } + + @GET + @Path("/identity-servers/identity-server-name") + @Override + public Response isIdentityServerNameExists( + @QueryParam("identityServerName") String identityServerName) { + try { + if (identityServerName == null) { + String msg = "Invalid identity server name, identityServerName query param cannot be empty/null."; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + if (spAppManager.isIdentityServerNameExist(identityServerName)) { + return Response.status(Response.Status.CONFLICT).build(); + } + return Response.status(Response.Status.OK).build(); + } catch (BadRequestException e) { + String errMsg = "Identity server request payload is invalid"; + log.error(errMsg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); + } catch (ApplicationManagementException e) { + String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; + log.error(errMsg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errMsg).build(); + } + } + + @GET + @Path("/identity-servers/identity-server-url") + @Override + public Response isIdentityServerUrlExists( + @QueryParam("identityServerUrl") String identityServerUrl) { + try { + if (identityServerUrl == null) { + String msg = "Invalid identity server url, identityServerName query param cannot be empty/null."; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).build(); + } + SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); + if (spAppManager.isIdentityServerUrlExist(identityServerUrl)) { + return Response.status(Response.Status.CONFLICT).build(); + } + return Response.status(Response.Status.OK).build(); + } catch (BadRequestException e) { + String errMsg = "Identity server request payload is invalid"; + log.error(errMsg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; log.error(errMsg, e); @@ -99,14 +224,16 @@ public class SPApplicationServiceImpl implements SPApplicationService { @Path("/{identity-server-id}/service-providers") @GET @Override - public Response getServiceProviders(@QueryParam("limit") Integer limit, @QueryParam("offset") Integer offset, + public Response getServiceProviders(@DefaultValue("30") @QueryParam("limit") Integer limit,@DefaultValue("0") @QueryParam("offset") Integer offset, @PathParam("identity-server-id") int identityServerId) { try { SPApplicationManager spAppManager = APIUtil.getSPApplicationManager(); - SPApplicationListResponse applications = SPAppRequestHandlerUtil. - retrieveSPApplications(identityServerId, limit, offset); - spAppManager.addExistingApps(identityServerId, applications.getApplications()); + SPApplicationListResponse applications = spAppManager.retrieveSPApplicationFromIdentityServer(identityServerId, limit, offset); return Response.status(Response.Status.OK).entity(applications).build(); + } catch (NotFoundException e) { + String errMsg = "No Identity server exist with the id: " + identityServerId; + log.error(errMsg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; log.error(errMsg, e); @@ -121,9 +248,16 @@ public class SPApplicationServiceImpl implements SPApplicationService { @PathParam("service-provider-id") String serviceProviderId, List appIds) { SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); try { - validateServiceProviderUID(identityServerId, serviceProviderId); - spApplicationManager.validateAttachAppsRequest(identityServerId, appIds); + spApplicationManager.validateAttachAppsRequest(identityServerId, serviceProviderId, appIds); spApplicationManager.attachSPApplications(identityServerId, serviceProviderId, appIds); + } catch (NotFoundException e) { + String msg = "No identity server exist with the id " + identityServerId; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (BadRequestException e) { + String msg = "Invalid appIds provided"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String msg = "Error occurred while attaching apps to service provider with the id" + serviceProviderId; log.error(msg, e); @@ -139,9 +273,16 @@ public class SPApplicationServiceImpl implements SPApplicationService { @PathParam("service-provider-id") String serviceProviderId, List appIds) { SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); try { - validateServiceProviderUID(identityServerId, serviceProviderId); spApplicationManager.validateDetachAppsRequest(identityServerId, serviceProviderId, appIds); spApplicationManager.detachSPApplications(identityServerId, serviceProviderId, appIds); + } catch (NotFoundException e) { + String msg = "No identity server exist with the id " + identityServerId; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (BadRequestException e) { + String msg = "Invalid appIds provided"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String msg = "Error occurred while attaching apps to service provider with the id" + serviceProviderId; log.error(msg, e); @@ -193,10 +334,13 @@ public class SPApplicationServiceImpl implements SPApplicationService { */ private Response createSPApplication(int identityServerId, String spUID, T appWrapper) { try { - validateServiceProviderUID(identityServerId, spUID); SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); Application createdApp = spApplicationManager.createSPApplication(appWrapper, identityServerId, spUID); return Response.status(Response.Status.CREATED).entity(createdApp).build(); + } catch (NotFoundException e) { + String msg = "No identity server exist with the id " + identityServerId; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (BadRequestException e) { String msg = "Found incompatible payload with create service provider app request."; log.error(msg, e); @@ -213,28 +357,4 @@ public class SPApplicationServiceImpl implements SPApplicationService { } } - /** - * Responsible for validating service provider in requests - * - * @param identityServerId identity server id of the service provider - * @param spUID uid of the service provider - * @throws ApplicationManagementException - */ - private void validateServiceProviderUID(int identityServerId, String spUID) throws - ApplicationManagementException { - try { - boolean isSPAppExists = SPAppRequestHandlerUtil. - isSPApplicationExist(identityServerId, spUID); - if (!isSPAppExists) { - String errMsg = "Service provider with the uid " + spUID + " does not exist."; - log.error(errMsg); - throw new BadRequestException(errMsg); - } - } catch (ApplicationManagementException e) { - String errMsg = "Error occurred while trying to validate service provider uid"; - log.error(errMsg, e); - throw new ApplicationManagementException(errMsg, e); - } - } - } \ No newline at end of file diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java deleted file mode 100644 index d71b3534721..00000000000 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/util/SPAppRequestHandlerUtil.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. 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 io.entgra.application.mgt.publisher.api.services.util; - -import com.google.gson.Gson; -import io.entgra.application.mgt.common.IdentityServer; -import io.entgra.application.mgt.common.SPApplication; -import io.entgra.application.mgt.common.SPApplicationListResponse; -import io.entgra.application.mgt.common.exception.ApplicationManagementException; -import io.entgra.application.mgt.common.services.SPApplicationManager; -import io.entgra.application.mgt.core.config.ConfigurationManager; -import io.entgra.application.mgt.core.config.IdentityServerDetail; -import io.entgra.application.mgt.core.util.APIUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.wso2.carbon.device.mgt.core.common.util.HttpUtil; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.UriBuilder; -import java.io.IOException; -import java.net.URI; - -public class SPAppRequestHandlerUtil { - - private static final Log log = LogFactory.getLog(SPAppRequestHandlerUtil.class); - - /** - * Check if service provider application exists - * - * @param identityServerId id of the identity server - * @param spAppId uid of the service provider - * @return if service provider exist - * @throws ApplicationManagementException - */ - public static boolean isSPApplicationExist(int identityServerId, String spAppId) throws ApplicationManagementException { - SPApplication application = retrieveSPApplication(identityServerId, spAppId); - return application != null; - } - - /** - * Get service provider by identity server id and service provider uid - * @param identityServerId id of the identity server - * @param spAppId uid of service provider to be retrieved - * @return {@link SPApplication} - * @throws ApplicationManagementException - */ - public static SPApplication retrieveSPApplication(int identityServerId, String spAppId) - throws ApplicationManagementException { - IdentityServer identityServer = getIdentityServer(identityServerId); - HttpGet req = new HttpGet(); - URI uri = HttpUtil.createURI(getSPApplicationsAPI(identityServer)); - uri = UriBuilder.fromUri(uri).path(spAppId).build(); - req.setURI(uri); - CloseableHttpClient client = HttpClients.createDefault(); - try { - HttpResponse response = invokeISAPI(identityServer, client, req); - String responseBody = HttpUtil.getResponseString(response); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { - return new Gson().fromJson(responseBody, - SPApplication.class); - } - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - return null; - } - String msg = "Error occurred while calling SP Applications API"; - log.error(msg); - throw new ApplicationManagementException(msg); - } catch (IOException e) { - String msg = "Error occurred while calling SP Applications API"; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } finally { - try { - client.close(); - } catch (IOException e) { - log.error("Error occurred while closing http connection"); - } - } - } - - /** - * Retrieve service provider apps from identity server - * - * @param identityServerId id of the identity server - * @return {@link SPApplicationListResponse} - * @throws ApplicationManagementException - */ - public static SPApplicationListResponse retrieveSPApplications(int identityServerId, Integer limit, Integer offset) - throws ApplicationManagementException { - IdentityServer identityServer = getIdentityServer(identityServerId); - HttpGet req = new HttpGet(); - URI uri = HttpUtil.createURI(getSPApplicationsAPI(identityServer)); - UriBuilder uriBuilder = UriBuilder.fromUri(uri); - if (limit != null) { - uriBuilder = uriBuilder.queryParam(io.entgra.application.mgt.core.util.Constants.LIMIT_QUERY_PARAM, limit); - } - if (offset != null) { - uriBuilder = uriBuilder.queryParam(io.entgra.application.mgt.core.util.Constants.OFFSET_QUERY_PARAM, offset); - } - uri = uriBuilder.build(); - req.setURI(uri); - CloseableHttpClient client = HttpClients.createDefault(); - try { - HttpResponse response = invokeISAPI(identityServer, client, req); - String responseBody = HttpUtil.getResponseString(response); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { - return new Gson().fromJson(responseBody, - SPApplicationListResponse.class); - } - String msg = "Error occurred while calling SP Applications API"; - log.error(msg); - throw new ApplicationManagementException(msg); - } catch (IOException e) { - String msg = "Error occurred while calling SP Applications API"; - log.error(msg, e); - throw new ApplicationManagementException(msg, e); - } finally { - try { - client.close(); - } catch (IOException e) { - log.error("Error occurred while closing http connection"); - } - } - } - - /** - * - * @param identityServerId id of the identity server - * @return {@link IdentityServer} - * @throws ApplicationManagementException - */ - public static IdentityServer getIdentityServer(int identityServerId) throws ApplicationManagementException { - SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); - return spApplicationManager.getIdentityServer(identityServerId); - } - - private static HttpResponse invokeISAPI(IdentityServer identityServer, HttpClient client, HttpRequestBase request) throws IOException { - setBasicAuthHeader(identityServer, request); - return client.execute(request); - } - - private static void setBasicAuthHeader(IdentityServer identityServer, HttpRequestBase request) { - String basicAuthHeader = HttpUtil.getBasicAuthBase64Header(identityServer.getUserName(), - identityServer.getPassword()); - request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader); - } - - private static String getSPApplicationsAPI(IdentityServer identityServer) { - IdentityServerDetail identityServerDetail = ConfigurationManager.getInstance().getIdentityServerConfiguration(). - getIdentityServerDetailByProviderName(identityServer.getProviderName()); - return identityServer.getApiUrl() + identityServerDetail.getServiceProvidersAPIContextPath(); - } - -} \ No newline at end of file From db1aab1f3a2619909e72dde6cb16efb4db55305d Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Wed, 6 Apr 2022 01:01:22 +0530 Subject: [PATCH 09/13] Add identity service provider config --- .../application/mgt/core/util/Constants.java | 2 +- .../conf/identity-service-provider-config.xml | 30 +++++++++++++++++++ .../identity-service-provider-config.xml.j2 | 30 +++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf/identity-service-provider-config.xml create mode 100644 features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/identity-service-provider-config.xml.j2 diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java index fd9b4577df6..f4ad8013e45 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/Constants.java @@ -31,7 +31,7 @@ import java.util.Map; public class Constants { public static final String APPLICATION_CONFIG_XML_FILE = "application-mgt.xml"; - public static final String IDENTITY_SERVERS_CONFIG_XML_FILE = "identity-servers-config.xml"; + public static final String IDENTITY_SERVERS_CONFIG_XML_FILE = "identity-service-provider-config.xml"; public static final String DEFAULT_CONFIG_FILE_LOCATION = CarbonUtils.getCarbonConfigDirPath() + File.separator + Constants.APPLICATION_CONFIG_XML_FILE; diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf/identity-service-provider-config.xml b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf/identity-service-provider-config.xml new file mode 100644 index 00000000000..bee524c54a3 --- /dev/null +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf/identity-service-provider-config.xml @@ -0,0 +1,30 @@ + + + + + + + + WSO2 IAM + io.entgra.application.mgt.core.identityserver.serviceprovider.impl.WSO2IAMSPApplicationService + /carbon/application/list-service-providers.jsp + + + + diff --git a/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/identity-service-provider-config.xml.j2 b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/identity-service-provider-config.xml.j2 new file mode 100644 index 00000000000..bee524c54a3 --- /dev/null +++ b/features/application-mgt/io.entgra.application.mgt.server.feature/src/main/resources/conf_templates/templates/repository/conf/identity-service-provider-config.xml.j2 @@ -0,0 +1,30 @@ + + + + + + + + WSO2 IAM + io.entgra.application.mgt.core.identityserver.serviceprovider.impl.WSO2IAMSPApplicationService + /carbon/application/list-service-providers.jsp + + + + From daaeed52e29e8936942038c0f222d2cc005b5044 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Wed, 6 Apr 2022 11:08:33 +0530 Subject: [PATCH 10/13] Add and Change licence from WSO2 to Entgra --- .../application/mgt/common/FileDataHolder.java | 7 +++---- .../mgt/common/IdentityServerResponse.java | 7 +++---- .../application/mgt/common/SPApplication.java | 7 +++---- .../mgt/common/SPApplicationListResponse.java | 7 +++---- .../mgt/common/dto/IdentityServerDTO.java | 7 +++---- .../common/dto/IdentityServiceProviderDTO.java | 17 +++++++++++++++++ .../common/services/SPApplicationManager.java | 7 +++---- .../core/config/IdentityServiceProvider.java | 17 +++++++++++++++++ .../IdentityServiceProviderConfiguration.java | 3 ++- .../mgt/core/dao/SPApplicationDAO.java | 7 +++---- .../GenericSPApplicationDAOImpl.java | 7 +++---- .../OracleSPApplicationDAOImpl.java | 7 +++---- .../PostgreSQLSPApplicationDAOImpl.java | 7 +++---- .../SQLServerSPApplicationDAOImpl.java | 7 +++---- .../ISServiceProviderApplicationService.java | 17 +++++++++++++++++ .../impl/WSO2IAMSPApplicationService.java | 7 +++---- .../mgt/core/impl/SPApplicationManagerImpl.java | 7 +++---- .../api/services/SPApplicationService.java | 7 +++---- .../services/impl/SPApplicationServiceImpl.java | 7 +++---- .../device/mgt/core/common/Constants.java | 7 +++---- 20 files changed, 101 insertions(+), 65 deletions(-) diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java index ec59999afd1..1a3d4cfd8c6 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/FileDataHolder.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerResponse.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerResponse.java index f36883da50e..69f33f7c66d 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerResponse.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/IdentityServerResponse.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java index 50d19aca631..da4b094bfc7 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplication.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java index 576093944de..bbe1f5da7f2 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/SPApplicationListResponse.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java index 71e11c75cc3..bf1ed88fef5 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServerDTO.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServiceProviderDTO.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServiceProviderDTO.java index ad378daec2c..d9e8e2ac608 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServiceProviderDTO.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/dto/IdentityServiceProviderDTO.java @@ -1,3 +1,20 @@ +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.application.mgt.common.dto; import java.util.List; diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java index 8dfbc18fc6b..433fa5ff127 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProvider.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProvider.java index d7c82c0790e..63098fdd1b3 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProvider.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProvider.java @@ -1,3 +1,20 @@ +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.application.mgt.core.config; import javax.xml.bind.annotation.XmlElement; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProviderConfiguration.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProviderConfiguration.java index 86b1936a0d0..b8b73504137 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProviderConfiguration.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/IdentityServiceProviderConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. * * Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -15,6 +15,7 @@ * specific language governing permissions and limitations * under the License. */ + package io.entgra.application.mgt.core.config; import javax.xml.bind.annotation.XmlElement; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java index ba7f00b24ae..3d5d171585b 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/SPApplicationDAO.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java index 6641d228bfa..501c965b79b 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/GenericSPApplicationDAOImpl.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java index 6f76e115438..77dc2853755 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/OracleSPApplicationDAOImpl.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java index 87f0e1fbcfe..5e33a4c278f 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/PostgreSQLSPApplicationDAOImpl.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java index f0b676501d0..619b3214de6 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/spapplication/SQLServerSPApplicationDAOImpl.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/ISServiceProviderApplicationService.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/ISServiceProviderApplicationService.java index fe2eec16e32..2f603fae685 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/ISServiceProviderApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/ISServiceProviderApplicationService.java @@ -1,3 +1,20 @@ +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.application.mgt.core.identityserver.serviceprovider; import io.entgra.application.mgt.common.SPApplication; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java index fad3c6b5ba2..7e72576e403 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java index 802a52f4c33..3f57661640f 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java index 299f44b5487..3b521eec5c2 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java index 297805644d4..c13a12e3202 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java index 0ff71608f44..0db16ff4518 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +/* Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, + * Entgra (Pvt) Ltd. 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 From 41a0c9118ab5413929a20bd8e8635aeecbc1229d Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Tue, 12 Apr 2022 18:02:45 +0530 Subject: [PATCH 11/13] Add java doc comments Use try-with resource when using CloseableHttpClient Refactor few variable and method names --- .../IdentityServerManagementException.java | 6 + .../common/services/ApplicationManager.java | 52 ++++++++- .../impl/WSO2IAMSPApplicationService.java | 51 +++++--- .../mgt/core/impl/ApplicationManagerImpl.java | 55 +++++++-- .../core/impl/SPApplicationManagerImpl.java | 80 ++++++++++++- .../impl/SPApplicationServiceImpl.java | 6 +- .../device/mgt/core/common/util/FileUtil.java | 27 ++++- .../device/mgt/core/common/util/HttpUtil.java | 110 ++++++++++++++++-- 8 files changed, 339 insertions(+), 48 deletions(-) diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java index 602a8eddeed..f2168ec32bc 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/exception/IdentityServerManagementException.java @@ -21,6 +21,12 @@ package io.entgra.application.mgt.common.exception; * Exception that will be thrown if any error occurs while calling identity server services . */ public class IdentityServerManagementException extends ApplicationManagementException { + + public IdentityServerManagementException(String message, Throwable throwable) { + super(message, throwable); + setMessage(message); + } + public IdentityServerManagementException(String message) { super(message); setMessage(message); diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java index e59021d1e4b..00c5b4f9e96 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java @@ -100,6 +100,12 @@ public interface ApplicationManager { */ ApplicationDTO uploadReleaseArtifactIfExist(T app) throws ApplicationManagementException; + /** + * Check if public app release packageName is valid (I.E invalid if packageName already exists) + * + * @param packageName name of the application release package + * @throws ApplicationManagementException if package name is invalid + */ void validatePublicAppReleasePackageName(String packageName) throws ApplicationManagementException; /** @@ -169,6 +175,13 @@ public interface ApplicationManager { */ void deleteApplicationRelease(String releaseUuid) throws ApplicationManagementException; + /** + * Use to delete application artifact files (For example this is useful to delete application release artifacts + * (I.E screenshots) when an application is deleted) + * + * @param directoryPaths directory paths that contains release artifacts (I.E screenshots) + * @throws ApplicationManagementException if error occurred while deleting artifacts + */ void deleteApplicationArtifacts(List directoryPaths) throws ApplicationManagementException; /** @@ -220,6 +233,13 @@ public interface ApplicationManager { ApplicationType type) throws ApplicationManagementException; + /** + * Get application and all application releases associated to the application for the given application Id + * + * @param applicationId Application Id + * @return {@link ApplicationDTO} + * @throws ApplicationManagementException if error occurred application data from the database. + */ ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException; /** @@ -292,7 +312,8 @@ public interface ApplicationManager { void updateApplicationArtifact(String deviceType, String uuid, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - /*** + /** + * Use to update existing enterprise app release * * @param releaseUuid UUID of the application release. * @param entAppReleaseWrapper {@link ApplicationReleaseDTO} @@ -302,22 +323,47 @@ public interface ApplicationManager { ApplicationRelease updateEntAppRelease(String releaseUuid, EntAppReleaseWrapper entAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + + /** + * Use to update existing public app release + * + * @param releaseUuid UUID of the application release. + * @param publicAppReleaseWrapper {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @return If the application release is updated correctly True returns, otherwise retuen False + */ ApplicationRelease updatePubAppRelease(String releaseUuid, PublicAppReleaseWrapper publicAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + /** + * Use to update existing web app release + * + * @param releaseUuid UUID of the application release. + * @param webAppReleaseWrapper {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @return If the application release is updated correctly True returns, otherwise retuen False + */ ApplicationRelease updateWebAppRelease(String releaseUuid, WebAppReleaseWrapper webAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; + /** + * Use to update existing custom app release + * + * @param releaseUuid UUID of the application release. + * @param customAppReleaseWrapper {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @return If the application release is updated correctly True returns, otherwise retuen False + */ ApplicationRelease updateCustomAppRelease(String releaseUuid, CustomAppReleaseWrapper customAppReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; - /*** + /** * To validate the application creating request * */ void validateAppCreatingRequest(T param) throws ApplicationManagementException, RequestValidatingException; - /*** + /** * * @throws ApplicationManagementException throws if payload does not satisfy requirements. */ diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java index 7e72576e403..2dc5a91e27a 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/identityserver/serviceprovider/impl/WSO2IAMSPApplicationService.java @@ -65,8 +65,7 @@ public class WSO2IAMSPApplicationService implements ISServiceProviderApplication String uriString = constructAPIUrl(identityServer); uriString += Constants.FORWARD_SLASH + spAppId; req.setURI(HttpUtil.createURI(uriString)); - CloseableHttpClient client = HttpClients.createDefault(); - try { + try (CloseableHttpClient client = HttpClients.createDefault()) { HttpResponse response = invokeISAPI(identityServer, client, req); String responseBody = HttpUtil.getResponseString(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { @@ -82,16 +81,17 @@ public class WSO2IAMSPApplicationService implements ISServiceProviderApplication } catch (IOException e) { String msg = "Error occurred while calling SP Applications API. Make sure identity server is up and running"; log.error(msg, e); - throw new IdentityServerManagementException(msg); - } finally { - try { - client.close(); - } catch (IOException e) { - log.error("Error occurred while closing http connection"); - } + throw new IdentityServerManagementException(msg, e); } } + /** + * Construct error message string depending on service providers api response + * (I.E If unauthorized a different message will be returned) + * + * @param response of the service provider api call + * @return constructed error message + */ private String constructErrorMessage(HttpResponse response) { String msg = "Error occurred while calling SP Applications API"; if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { @@ -109,8 +109,7 @@ public class WSO2IAMSPApplicationService implements ISServiceProviderApplication uriString += Constants.QUERY_STRING_SEPARATOR + Constants.OFFSET_QUERY_PARAM + Constants.QUERY_KEY_VALUE_SEPARATOR + offset; req.setURI(HttpUtil.createURI(uriString)); - CloseableHttpClient client = HttpClients.createDefault(); - try { + try (CloseableHttpClient client = HttpClients.createDefault()) { HttpResponse response = invokeISAPI(identityServer, client, req); String responseBody = HttpUtil.getResponseString(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { @@ -123,27 +122,43 @@ public class WSO2IAMSPApplicationService implements ISServiceProviderApplication } catch (IOException e) { String msg = "Error occurred while calling SP Applications API. Make sure identity server is up and running"; log.error(msg, e); - throw new IdentityServerManagementException(msg); - } finally { - try { - client.close(); - } catch (IOException e) { - log.error("Error occurred while closing http connection"); - } + throw new IdentityServerManagementException(msg, e); } } + /** + * Takes essential prerequisite steps (I.E setting authorization header), + * invokes provided GET request and returns the response + * + * @param identityServer {@link IdentityServerDTO} + * @param client httpClient that should be used to invoke + * @param request GET request to be invoked + * @return response of the invoked api + */ private HttpResponse invokeISAPI(IdentityServerDTO identityServer, HttpClient client, HttpGet request) throws IOException { setBasicAuthHeader(identityServer, request); return client.execute(request); } + /** + * Add basic auth header to provided service provider api request by getting the username and password + * from identity server bean + * + * @param identityServer {@link IdentityServerDTO} + * @param request service provider api request + */ private void setBasicAuthHeader(IdentityServerDTO identityServer, HttpRequestBase request) { String basicAuthHeader = HttpUtil.getBasicAuthBase64Header(identityServer.getUsername(), identityServer.getPassword()); request.setHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader); } + /** + * Helps to construct service provider api base url + * + * @param identityServer {@link IdentityServerDTO} + * @return constructed service providers api url + */ private String constructAPIUrl(IdentityServerDTO identityServer) { String identityServerUrl = identityServer.getUrl(); // add "/" at the end, if the server url doesn't contain "/" at the end diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java index ffdd342c785..fc928a1e977 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java @@ -341,6 +341,14 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + /** + * Use to upload/save web app release artifacts (I.E icon) + * + * @param releaseDTO {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @return constructed {@link ApplicationReleaseDTO} with upload details + * @throws ResourceManagementException if error occurred while uploading + */ private ApplicationReleaseDTO uploadWebAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact) throws ResourceManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); @@ -350,6 +358,15 @@ public class ApplicationManagerImpl implements ApplicationManager { return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); } + /** + * Use to upload/save public app release artifacts (I.E icon) + * + * @param releaseDTO {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @param deviceType Device Type name + * @return constructed {@link ApplicationReleaseDTO} with upload details + * @throws ResourceManagementException if error occurred while uploading + */ private ApplicationReleaseDTO uploadPubAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, String deviceType) throws ResourceManagementException { @@ -384,6 +401,15 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + /** + * Use to upload/save public app release artifacts (I.E icon) + * + * @param releaseDTO {@link ApplicationReleaseDTO} + * @param applicationArtifact {@link ApplicationArtifact} + * @param deviceType Device Type name + * @return constructed {@link ApplicationReleaseDTO} with upload details + * @throws ResourceManagementException if error occurred while uploading + */ private ApplicationReleaseDTO uploadCustomAppReleaseArtifacts(ApplicationReleaseDTO releaseDTO, ApplicationArtifact applicationArtifact, String deviceType) throws ResourceManagementException, ApplicationManagementException { @@ -402,7 +428,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } catch (IOException e) { String msg = "Error occurred when uploading release artifact into the server"; log.error(msg); - throw new ApplicationManagementException(msg); + throw new ApplicationManagementException(msg, e); } return addImageArtifacts(releaseDTO, applicationArtifact, tenantId); } @@ -436,16 +462,32 @@ public class ApplicationManagerImpl implements ApplicationManager { } } + /** + * Helps to byte content of release binary file of application artifact + * This method can be useful when uploading application release binary file or when generating md5hex of release binary + * + * @param artifact {@link ApplicationArtifact} + * @return byte content of application release binary file + * @throws ApplicationManagementException if error occurred while getting byte content + */ private byte[] getByteContentOfApp(ApplicationArtifact artifact) throws ApplicationManagementException{ try { return IOUtils.toByteArray(artifact.getInstallerStream()); } catch (IOException e) { String msg = "Error occurred while getting byte content of app binary artifact"; log.error(msg); - throw new ApplicationManagementException(msg); + throw new ApplicationManagementException(msg, e); } } + /** + * Useful to generate md5hex string of application release + * + * @param applicationArtifact {@link ApplicationArtifact} + * @param content byte array content of application release binary file + * @return Generated md5hex string + * @throws ApplicationManagementException if any error occurred while generating md5hex string + */ private String generateMD5OfApp(ApplicationArtifact applicationArtifact, byte[] content) throws ApplicationManagementException { try { String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content)); @@ -458,7 +500,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } catch( ApplicationStorageManagementException e) { String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName(); log.error(msg); - throw new ApplicationManagementException(msg); + throw new ApplicationManagementException(msg, e); } } @@ -1197,13 +1239,6 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - /** - * Get Application and all application releases associated to the application that has given application Id - * - * @param applicationId Application Id - * @return {@link ApplicationDTO} - * @throws ApplicationManagementException if error occurred application data from the databse. - */ @Override public ApplicationDTO getApplication(int applicationId) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java index 3f57661640f..6f8fd98198a 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -80,6 +80,13 @@ public class SPApplicationManagerImpl implements SPApplicationManager { return APIUtil.identityServerDtoToIdentityServerResponse(identityServerDTO); } + /** + * This is similar to getIdentityServerFromDB method except throws {@link NotFoundException} if identity server + * does not exist for the given id + * + * @param identityServerId id of identity server + * @return {@link IdentityServerDTO} + */ private IdentityServerDTO getIdentityServer(int identityServerId) throws ApplicationManagementException { IdentityServerDTO identityServerDTO = getIdentityServerFromDB(identityServerId); if (identityServerDTO == null) { @@ -90,6 +97,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { return identityServerDTO; } + /** + * Use to get {@link IdentityServerDTO} bean from database. Returns null if does not exist + * + * @param identityServerId id of identity server + * @return {@link IdentityServerDTO} + */ private IdentityServerDTO getIdentityServerFromDB(int identityServerId) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { @@ -191,6 +204,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + /** + * Validate the identity server delete request + * + * @param identityServerId identity server id + * @throws BadRequestException if provided identity server id is invalid + */ private void validateIdentityServerDeleteRequest(int identityServerId) throws ApplicationManagementException { IdentityServerDTO identityServerDTO = getIdentityServerFromDB(identityServerId); if (identityServerDTO == null) { @@ -200,6 +219,15 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + /** + * This method is useful to re-construct the api params Map using updated identity server bean {@link IdentityServerDTO} + * For example updated identity server bean may contain only updated api param, in which case the existing api param values + * should be re-added to updated identity server bean + * + * @param updatedIdentityServerDTO updated identity server request payload + * @param existingIdentityServerDTO corresponding existing identity server of updated identity server + * @return Constructed api param map + */ private Map constructUpdatedApiParams(IdentityServerDTO updatedIdentityServerDTO, IdentityServerDTO existingIdentityServerDTO) { Map updatedApiParams = updatedIdentityServerDTO.getApiParams(); @@ -292,6 +320,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { validateIdentityServerUrl(identityServerDTO.getUrl()); } + /** + * Validate provided identity server url (For example make sure it uses http/https protocol) + * + * @param url url of the identity server + * @throws BadRequestException if url is invalid + */ private void validateIdentityServerUrl(String url) throws BadRequestException { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS); @@ -302,17 +336,32 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } - private void validateUpdateIdentityServerRequestApiParam(IdentityServerDTO identityServerUpdateDTO, + /** + * Validate provided api params map in a identity server updated request + * For example the updated api param map may not contain all the required api params + * + * @param updatedIdentityServerDto Identity server update request payload bean + * @param existingIdentityServerDTO Corresponding existing identity server bean of the updated identity server + * @throws ApplicationManagementException if any api param is invalid + */ + private void validateUpdateIdentityServerRequestApiParam(IdentityServerDTO updatedIdentityServerDto, IdentityServerDTO existingIdentityServerDTO) throws ApplicationManagementException { ISServiceProviderApplicationService serviceProviderApplicationService = ISServiceProviderApplicationService.of(existingIdentityServerDTO.getProviderName()); List requiredApiParams = serviceProviderApplicationService.getRequiredApiParams(); - if (!identityServerUpdateDTO.getProviderName().equals(existingIdentityServerDTO.getProviderName())) { - validateAllRequiredParamsExists(identityServerUpdateDTO, requiredApiParams); + if (!updatedIdentityServerDto.getProviderName().equals(existingIdentityServerDTO.getProviderName())) { + validateAllRequiredParamsExists(updatedIdentityServerDto, requiredApiParams); } - validateIfAnyInvalidParamExists(identityServerUpdateDTO, requiredApiParams); + validateIfAnyInvalidParamExists(updatedIdentityServerDto, requiredApiParams); } + /** + * Validate api params map of identity server create request payload + * For example the api param map may not contain all the required api params + * + * @param identityServerDTO {@link IdentityServerDTO} + * @throws ApplicationManagementException if any api param is invalid + */ private void validateCreateIdentityServerRequestApiParams(IdentityServerDTO identityServerDTO) throws ApplicationManagementException { ISServiceProviderApplicationService serviceProviderApplicationService = ISServiceProviderApplicationService.of(identityServerDTO.getProviderName()); @@ -321,6 +370,13 @@ public class SPApplicationManagerImpl implements SPApplicationManager { validateIfAnyInvalidParamExists(identityServerDTO, requiredApiParams); } + /** + * Make sure if all required api params exists for the given identity server bean + * + * @param identityServerDTO {@link IdentityServerDTO} + * @param requiredApiParams all mandatory api params + * @throws BadRequestException if a required api param does not exist + */ private void validateAllRequiredParamsExists(IdentityServerDTO identityServerDTO, List requiredApiParams) throws BadRequestException { for (String param : requiredApiParams) { @@ -333,6 +389,14 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + /** + * Make sure if all api params are valid + * For example it may contain an unwanted api param + * + * @param identityServerDTO {@link IdentityServerDTO} + * @param requiredApiParams all required api params + * @throws BadRequestException if an unwanted api param exist + */ private void validateIfAnyInvalidParamExists(IdentityServerDTO identityServerDTO, List requiredApiParams) throws BadRequestException { for (String param : identityServerDTO.getApiParamKeys()) { @@ -344,6 +408,12 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } } + /** + * If the given providerName does not exist in the identity server config file + * + * @param providerName Name of the identity service provider + * @return if provider name exist in identity server config + */ private boolean isIdentityServiceProviderNotConfigured(String providerName) { List identityServiceProviders = ConfigurationManager.getInstance().getIdentityServerConfiguration(). getIdentityServiceProviders(); @@ -508,7 +578,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } catch (ApplicationManagementException e) { String msg = "Identity service provider configuration file is invalid. Hence failed to proceed."; log.error(msg); - throw new ApplicationManagementException(msg); + throw new ApplicationManagementException(msg, e); } } return identityServiceProviderDTOS; diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java index c13a12e3202..cceefb6c18d 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -95,7 +95,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).entity("Successfully deleted identity server").build(); } catch (NotFoundException e) { String msg = "Identity server with the id " + id + " does not exist."; - log.error(msg); + log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; @@ -114,7 +114,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).entity(identityServer).build(); } catch (NotFoundException e) { String msg = "Identity server with the id " + id + " does not exist."; - log.error(msg); + log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (ApplicationManagementException e) { String errMsg = "Error occurred while trying to merge identity server apps with existing apps"; @@ -133,7 +133,7 @@ public class SPApplicationServiceImpl implements SPApplicationService { return Response.status(Response.Status.OK).entity(identityServerResponse).build(); } catch (NotFoundException e) { String msg = "Identity server with the id " + id + " does not exist."; - log.error(msg); + log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } catch (BadRequestException e) { String errMsg = "Identity server request payload is invalid"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java index dc9ce7cc588..d90e586412c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java @@ -24,6 +24,12 @@ import java.util.Base64; public class FileUtil { + /** + * Useful to remove path separator string "," from base64 string + * + * @param base64String base64 string + * @return base64 string without path separator + */ public static String removePathSeparatorFromBase64String(String base64String) { String partSeparator = ","; if (base64String.contains(partSeparator)) { @@ -32,6 +38,12 @@ public class FileUtil { return base64String; } + /** + * Useful to convert base64 string to input stream + * + * @param base64 base64 string to be converted + * @return {@link InputStream} of the provided base64 string + */ public static InputStream base64ToInputStream(String base64) { base64 = FileUtil.removePathSeparatorFromBase64String(base64); byte[] base64Bytes = Base64.getDecoder().decode(base64); @@ -72,13 +84,24 @@ public class FileUtil { return suffix; } + /** + * Use to extract file extension from file name + * + * @param fileName name of the file + * @return extension of the file + */ private static String extractFileExtension(String fileName) { return fileName.substring(fileName.lastIndexOf('.') + 1); } + /** + * Use to extract the file name without the extension + * For example if you provide "main.java" as the fileName this will return main + * + * @param fileName name of the file + * @return file name without file extension + */ private static String extractFileNameWithoutExtension(String fileName) { return fileName.substring(0, fileName.lastIndexOf('.')); } - - } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java index 05db183b2a0..afd8ad5f44c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java @@ -32,20 +32,47 @@ import java.util.Map; public class HttpUtil { + /** + * Use to create {@link URI} from string + * This does encoding of the provided uri string before creating the URI + * + * @param uriString uri string to be used to create the URI + * @return created URI + */ public static URI createURI(String uriString) { uriString = uriString.replace(" ", "%20"); return URI.create(uriString); } + /** + * Use to create basic auth header string for provided credentials + * + * @param userName username credential + * @param password password credential + * @return Basic auth header + */ public static String getBasicAuthBase64Header(String userName, String password) { return Constants.BASIC_AUTH_HEADER_PREFIX + getBase64Encode(userName, password); } + /** + * Use to get the base64 encoded string of key value pair. + * For example this can be useful when creating basic auth header + * + * @return base64 encoded string of provided key and value + */ public static String getBase64Encode(String key, String value) { return new String(Base64.encodeBase64((key + ":" + value).getBytes())); } - public static String getRequestSubPathFromEnd(URI requestUri, int position) { + /** + * Useful to get the sub path in a position from the given uri starting from end of the uri + * + * @param requestUri {@link URI} + * @param position of which the sub path is needed + * @return Sub path of the uri + */ + public static String extractRequestSubPathFromEnd(URI requestUri, int position) { if (requestUri.getPath() != null) { String[] pathList = requestUri.getPath().split("/"); if (pathList.length - 1 >= position) { @@ -55,8 +82,15 @@ public class HttpUtil { return null; } - public static String getRequestSubPath(String fullPath, int position) { - String[] pathList = fullPath.split("/"); + /** + * Useful to get the sub path in a position from the given uri + * + * @param uri uri string from which the sub path should be extracted + * @param position of which the sub path is needed + * @return Sub path of the uri + */ + public static String extractRequestSubPath(String uri, int position) { + String[] pathList = uri.split("/"); if (pathList.length - 1 > position) { String path = pathList[position + 1]; if(path.contains(Constants.URI_QUERY_SEPARATOR)) { @@ -67,14 +101,37 @@ public class HttpUtil { return null; } + /** + * This returns the response body as string + * + * @param response {@link HttpResponse} + * @return Response body string + * @throws IOException if errors while converting response body to string + */ public static String getResponseString(HttpResponse response) throws IOException { return EntityUtils.toString(response.getEntity()); } - public static boolean isQueryParamExist(String param, URI request) { - Map> queryMap = getQueryMap(request); + /** + * Useful to check if a given query param exists in uri + * + * @param param query param to be checked + * @param uri in which query param should be checked + * @return if the provided query parameter exists in uri + */ + public static boolean isQueryParamExist(String param, URI uri) { + Map> queryMap = getQueryMap(uri); return queryMap.containsKey(param); } + + /** + * This is useful to get first query parameter value from a query map. + * For example a query parameter may have multiple values. + * + * @param param query parameter of which the value is needed + * @param queryMap query map which contains query paramters and it's values + * @return First value of provided query parameter + */ public static String getFirstQueryValue(String param, Map> queryMap) { List valueList = queryMap.get(param); String firstValue = null; @@ -83,6 +140,20 @@ public class HttpUtil { } return firstValue; } + + /** + * This constructs a key/value Map from query string of the provided uri. + * In other words this will create a map with query parameters as keys and their + * values as values. + * + * For example if the uri contains "?bar=1&foo=2" this will return a map + * with bar and foo as keys and 1 and 2 as their values + * + * This is similar to getQueryMap(URI uri) method except that this accepts uri string + * + * @param uri of which the query map to be created + * @return Query map of the provided uri + */ public static Map> getQueryMap(String uri) { String query = getQueryFromURIPath(uri); Map> map = new HashMap<>(); @@ -103,8 +174,20 @@ public class HttpUtil { } return map; } - public static Map> getQueryMap(URI request) { - String query = request.getQuery(); + + /** + * This constructs a key/value Map from query string of the provided uri. + * In other words this will create a map with query parameters as keys and their + * values as values. + * + * For example if the uri contains "?bar=1&foo=2" this will return a map + * with bar and foo as keys and 1 and 2 as their values + * + * @param uri of which the query map to be created + * @return Query map of the provided uri + */ + public static Map> getQueryMap(URI uri) { + String query = uri.getQuery(); Map> map = new HashMap<>(); if (query != null) { String[] params = query.split("&"); @@ -123,6 +206,13 @@ public class HttpUtil { } return map; } + + /** + * Get query string from uri path. Return null if no query string exists + * + * @param uri of which query string should be taken + * @return Query string of the provided uri + */ public static String getQueryFromURIPath(String uri) { String query = null; if (uri.length() > "?".length() && uri.contains("?")) { @@ -134,6 +224,12 @@ public class HttpUtil { return query; } + /** + * Get content type of http response + * + * @param response {@link HttpResponse} + * @return Content type + */ public static String getContentType(HttpResponse response) { ContentType contentType = ContentType.getOrDefault(response.getEntity()); return contentType.getMimeType(); From 9df320dd3be4ad754278f6b91c8e7fe296c384e6 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Mon, 18 Apr 2022 14:30:12 +0530 Subject: [PATCH 12/13] Resolve merge conflict --- .../common/services/ApplicationManager.java | 21 ++++--- .../common/services/SPApplicationManager.java | 3 +- .../mgt/core/impl/ApplicationManagerImpl.java | 59 ++++++++++++------- .../core/impl/SPApplicationManagerImpl.java | 4 +- .../management/ApplicationManagementTest.java | 2 +- .../ApplicationManagementPublisherAPI.java | 56 +++++++++++++++--- .../api/services/SPApplicationService.java | 29 +++++++-- ...ApplicationManagementPublisherAPIImpl.java | 37 ++++++------ .../impl/SPApplicationServiceImpl.java | 24 ++++---- 9 files changed, 164 insertions(+), 71 deletions(-) diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java index 12346507da7..82e78096b14 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java @@ -50,10 +50,11 @@ public interface ApplicationManager { * * @param appId application id of the application to which the release should be created * @param releaseWrapper {@link EntAppReleaseWrapper} of the release to be created + * @param isPublished If the app should be added in PUBLISHED state instead of initial state * @return Created application release bean * @throws ApplicationManagementException if any error occurred while creating the application */ - ApplicationRelease createEntAppRelease(int appId, EntAppReleaseWrapper releaseWrapper) + ApplicationRelease createEntAppRelease(int appId, EntAppReleaseWrapper releaseWrapper, boolean isPublished) throws ApplicationManagementException; /** @@ -61,10 +62,11 @@ public interface ApplicationManager { * * @param appId application id of the application to which the release should be created * @param releaseWrapper {@link WebAppReleaseWrapper} of the release to be created + * @param isPublished If the app should be added in PUBLISHED state instead of initial state * @return Created application release bean * @throws ApplicationManagementException if any error occurred while creating the application */ - ApplicationRelease createWebAppRelease(int appId, WebAppReleaseWrapper releaseWrapper) + ApplicationRelease createWebAppRelease(int appId, WebAppReleaseWrapper releaseWrapper, boolean isPublished) throws ApplicationManagementException, ResourceManagementException; /** @@ -72,10 +74,11 @@ public interface ApplicationManager { * * @param appId application id of the application to which the release should be created * @param releaseWrapper {@link PublicAppReleaseWrapper} of the release to be created + * @param isPublished If the app should be added in PUBLISHED state instead of initial state * @return Created application release bean * @throws ApplicationManagementException if any error occurred while creating the application */ - ApplicationRelease createPubAppRelease(int appId, PublicAppReleaseWrapper releaseWrapper) + ApplicationRelease createPubAppRelease(int appId, PublicAppReleaseWrapper releaseWrapper, boolean isPublished) throws ApplicationManagementException, ResourceManagementException; /** @@ -83,10 +86,11 @@ public interface ApplicationManager { * * @param appId application id of the application to which the release should be created * @param releaseWrapper {@link CustomAppReleaseWrapper} of the release to be created + * @param isPublished If the app should be added in PUBLISHED state instead of initial state * @return Created application release bean * @throws ApplicationManagementException if any error occurred while creating the application */ - ApplicationRelease createCustomAppRelease(int appId, CustomAppReleaseWrapper releaseWrapper) + ApplicationRelease createCustomAppRelease(int appId, CustomAppReleaseWrapper releaseWrapper, boolean isPublished) throws ResourceManagementException, ApplicationManagementException; /** @@ -113,21 +117,23 @@ public interface ApplicationManager { * required to do the validation of request and check the existence of application releaseDTO. * * @param applicationDTO Application DTO object. + * @param isPublished Wether the app should be added in PUBLISHED state instead of initial state * @return {@link Application} * @throws ApplicationManagementException which throws if error occurs while during application management. */ - Application addAppDataIntoDB(ApplicationDTO applicationDTO) throws + Application addAppDataIntoDB(ApplicationDTO applicationDTO, boolean isPublished) throws ApplicationManagementException; /** * This method is responsible for handling application creation * * @param app Application wrapper object which depends on the application type + * @param isPublished If the app should be created in PUBLISHED state * @param Application wrapper class which depends on the application type * @return Created application bean * @throws ApplicationManagementException if any error occurred while creating the application */ - Application createApplication(T app) throws ApplicationManagementException; + Application createApplication(T app, boolean isPublished) throws ApplicationManagementException; /** * Add an application to favourites * @param appId id of the application @@ -249,10 +255,11 @@ public interface ApplicationManager { * @param applicationDTO ApplicationDTO of the release * @param applicationReleaseDTO ApplicatonRelease that need to be be created. * @param type {@link ApplicationType} + * @param isPublished if the app should be added in PUBLISHED state instead of initial state * @return the unique id of the application release, if the application release succeeded else -1 */ ApplicationRelease createRelease(ApplicationDTO applicationDTO, ApplicationReleaseDTO applicationReleaseDTO, - ApplicationType type) + ApplicationType type, boolean isPublished) throws ApplicationManagementException; /** diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java index 433fa5ff127..bd4b1dd0150 100644 --- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/SPApplicationManager.java @@ -131,11 +131,12 @@ public interface SPApplicationManager { * @param identityServerId id of the identity server to which the created application should be mapped * @param spId uid of the service provder to which the created application should be mapped * @param Application wrapper class which depends on application type (PUBLIC, ENTERPRISE & etc) + * @param isPublished If the app should be added in PUBLISHED state instead of initial state * @return Application bean of the created application * @throws ApplicationManagementException if errors while creating and mapping the application * @throws RequestValidatingException if app contains any invalid payload */ - Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException, RequestValidatingException; + Application createSPApplication(T app, int identityServerId, String spId, boolean isPublished) throws ApplicationManagementException, RequestValidatingException; /** * Validates application ids of the applications that should be attached diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java index 375924a0366..b7fce45b1a0 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java @@ -138,11 +138,11 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public Application createApplication(T app) throws ApplicationManagementException { + public Application createApplication(T app, boolean isPublished) throws ApplicationManagementException { ApplicationDTO applicationDTO = uploadReleaseArtifactIfExist(app); try { ConnectionManagerUtil.beginDBTransaction(); - Application application = addAppDataIntoDB(applicationDTO); + Application application = addAppDataIntoDB(applicationDTO, isPublished); ConnectionManagerUtil.commitDBTransaction(); return application; } catch (DBConnectionException e) { @@ -167,7 +167,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public ApplicationRelease createEntAppRelease(int appId, EntAppReleaseWrapper releaseWrapper) + public ApplicationRelease createEntAppRelease(int appId, EntAppReleaseWrapper releaseWrapper, boolean isPublished) throws ApplicationManagementException { ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationArtifact artifact = ApplicationManagementUtil.constructApplicationArtifact(releaseWrapper.getIcon(), releaseWrapper.getScreenshots(), @@ -177,7 +177,7 @@ public class ApplicationManagerImpl implements ApplicationManager { ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); releaseDTO = uploadEntAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName(), true); try { - return createRelease(applicationDTO, releaseDTO, ApplicationType.ENTERPRISE); + return createRelease(applicationDTO, releaseDTO, ApplicationType.ENTERPRISE, isPublished); } catch (ApplicationManagementException e) { String msg = "Error occurred while creating ent app release for application with the name: " + applicationDTO.getName(); log.error(msg, e); @@ -187,7 +187,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public ApplicationRelease createWebAppRelease(int appId, WebAppReleaseWrapper releaseWrapper) + public ApplicationRelease createWebAppRelease(int appId, WebAppReleaseWrapper releaseWrapper, boolean isPublished) throws ApplicationManagementException, ResourceManagementException { ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationDTO applicationDTO = applicationManager.getApplication(appId); @@ -196,7 +196,7 @@ public class ApplicationManagerImpl implements ApplicationManager { ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); releaseDTO = uploadWebAppReleaseArtifacts(releaseDTO, artifact); try { - return createRelease(applicationDTO, releaseDTO, ApplicationType.WEB_CLIP); + return createRelease(applicationDTO, releaseDTO, ApplicationType.WEB_CLIP, isPublished); } catch (ApplicationManagementException e) { String msg = "Error occurred while creating web app release for application with the name: " + applicationDTO.getName(); log.error(msg, e); @@ -206,7 +206,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public ApplicationRelease createPubAppRelease(int appId, PublicAppReleaseWrapper releaseWrapper) throws + public ApplicationRelease createPubAppRelease(int appId, PublicAppReleaseWrapper releaseWrapper, boolean isPublished) throws ResourceManagementException, ApplicationManagementException { ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationDTO applicationDTO = applicationManager.getApplication(appId); @@ -216,7 +216,7 @@ public class ApplicationManagerImpl implements ApplicationManager { ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); releaseDTO = uploadPubAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName()); try { - return createRelease(applicationDTO, releaseDTO, ApplicationType.PUBLIC); + return createRelease(applicationDTO, releaseDTO, ApplicationType.PUBLIC, isPublished); } catch (ApplicationManagementException e) { String msg = "Error occurred while creating ent public release for application with the name: " + applicationDTO.getName(); log.error(msg, e); @@ -226,7 +226,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public ApplicationRelease createCustomAppRelease(int appId, CustomAppReleaseWrapper releaseWrapper) + public ApplicationRelease createCustomAppRelease(int appId, CustomAppReleaseWrapper releaseWrapper, boolean isPublished) throws ResourceManagementException, ApplicationManagementException { ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationDTO applicationDTO = applicationManager.getApplication(appId); @@ -236,7 +236,7 @@ public class ApplicationManagerImpl implements ApplicationManager { ApplicationReleaseDTO releaseDTO = APIUtil.releaseWrapperToReleaseDTO(releaseWrapper); releaseDTO = uploadCustomAppReleaseArtifacts(releaseDTO, artifact, deviceType.getName()); try { - return createRelease(applicationDTO, releaseDTO, ApplicationType.CUSTOM); + return createRelease(applicationDTO, releaseDTO, ApplicationType.CUSTOM, isPublished); } catch (ApplicationManagementException e) { String msg = "Error occurred while creating custom app release for application with the name: " + applicationDTO.getName(); log.error(msg, e); @@ -1192,7 +1192,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public Application addAppDataIntoDB(ApplicationDTO applicationDTO) throws + public Application addAppDataIntoDB(ApplicationDTO applicationDTO, boolean isPublished) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationReleaseDTO applicationReleaseDTO = null; @@ -1258,12 +1258,21 @@ public class ApplicationManagerImpl implements ApplicationManager { } List applicationReleaseEntities = new ArrayList<>(); if (applicationReleaseDTO != null) { - String initialLifecycleState = lifecycleStateManager.getInitialState(); - applicationReleaseDTO.setCurrentState(initialLifecycleState); - applicationReleaseDTO = this.applicationReleaseDAO - .createRelease(applicationReleaseDTO, appId, tenantId); - LifecycleState lifecycleState = getLifecycleStateInstance(initialLifecycleState, initialLifecycleState); + String lifeCycleState = lifecycleStateManager.getInitialState(); + String[] publishStates= {"IN-REVIEW", "APPROVED", "PUBLISHED"}; + + applicationReleaseDTO.setCurrentState(lifeCycleState); + applicationReleaseDTO = this.applicationReleaseDAO.createRelease(applicationReleaseDTO, appId, tenantId); + LifecycleState lifecycleState = getLifecycleStateInstance(lifeCycleState, lifeCycleState); this.lifecycleStateDAO.addLifecycleState(lifecycleState, applicationReleaseDTO.getId(), tenantId); + if(isPublished){ + for (String state: publishStates) { + LifecycleChanger lifecycleChanger = new LifecycleChanger(); + lifecycleChanger.setAction(state); + lifecycleChanger.setReason("Updated to " + state); + this.changeLifecycleState(applicationReleaseDTO, lifecycleChanger); + } + } applicationReleaseEntities.add(applicationReleaseDTO); } applicationDTO.setId(appId); @@ -1296,7 +1305,7 @@ public class ApplicationManagerImpl implements ApplicationManager { @Override public ApplicationRelease createRelease(ApplicationDTO applicationDTO, ApplicationReleaseDTO applicationReleaseDTO, - ApplicationType type) + ApplicationType type, boolean isPublished) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); if (log.isDebugEnabled()) { @@ -1322,13 +1331,23 @@ public class ApplicationManagerImpl implements ApplicationManager { try { ConnectionManagerUtil.beginDBTransaction(); - String initialState = lifecycleStateManager.getInitialState(); - applicationReleaseDTO.setCurrentState(initialState); - LifecycleState lifecycleState = getLifecycleStateInstance(initialState, initialState); + String lifeCycleState = lifecycleStateManager.getInitialState(); + String[] publishStates = {"IN-REVIEW", "APPROVED", "PUBLISHED"}; + + applicationReleaseDTO.setCurrentState(lifeCycleState); + LifecycleState lifecycleState = getLifecycleStateInstance(lifeCycleState, lifeCycleState); applicationReleaseDTO = this.applicationReleaseDAO .createRelease(applicationReleaseDTO, applicationDTO.getId(), tenantId); this.lifecycleStateDAO .addLifecycleState(lifecycleState, applicationReleaseDTO.getId(), tenantId); + if(isPublished){ + for (String state: publishStates) { + LifecycleChanger lifecycleChanger = new LifecycleChanger(); + lifecycleChanger.setAction(state); + lifecycleChanger.setReason("Updated to " + state); + this.changeLifecycleState(applicationReleaseDTO, lifecycleChanger); + } + } ApplicationRelease applicationRelease = APIUtil.releaseDtoToRelease(applicationReleaseDTO); ConnectionManagerUtil.commitDBTransaction(); return applicationRelease; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java index 6f8fd98198a..8382f428b59 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java @@ -650,7 +650,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } @Override - public Application createSPApplication(T app, int identityServerId, String spId) throws ApplicationManagementException { + public Application createSPApplication(T app, int identityServerId, String spId, boolean isPublished) throws ApplicationManagementException { validateServiceProviderUID(identityServerId, spId); ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance(); ApplicationDTO applicationDTO = applicationManager.uploadReleaseArtifactIfExist(app); @@ -660,7 +660,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager { } try { ConnectionManagerUtil.beginDBTransaction(); - Application createdApp = applicationManager.addAppDataIntoDB(applicationDTO); + Application createdApp = applicationManager.addAppDataIntoDB(applicationDTO, isPublished); attachCreatedSPApplication(createdApp, identityServerId, spId); ConnectionManagerUtil.commitDBTransaction(); return createdApp; diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java index 9d51887beb7..5d9f59bd21b 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java @@ -121,7 +121,7 @@ public class ApplicationManagementTest extends BaseTestCase { applicationArtifact.setScreenshots(screenshots); ApplicationManager manager = new ApplicationManagerImpl(); - manager.createApplication(applicationWrapper); + manager.createApplication(applicationWrapper, false); } @DataProvider(name = "applicationIdDataProvider") diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java index 23ca981b00b..5abce176c63 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java @@ -317,7 +317,12 @@ public interface ApplicationManagementPublisherAPI { name = "application", value = "The application that need to be created.", required = true) - ApplicationWrapper application); + ApplicationWrapper application, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished); @POST @Path("/web-app") @@ -356,7 +361,12 @@ public interface ApplicationManagementPublisherAPI { name = "webapp", value = "The web app that need to be created.", required = true) - WebAppWrapper webAppWrapper + WebAppWrapper webAppWrapper, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished ); @POST @@ -396,7 +406,12 @@ public interface ApplicationManagementPublisherAPI { name = "public-app", value = "The public app that need to be created.", required = true) - PublicAppWrapper publicAppWrapper + PublicAppWrapper publicAppWrapper, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished ); @POST @@ -436,7 +451,12 @@ public interface ApplicationManagementPublisherAPI { name = "application", value = "The application that need to be created.", required = true) - CustomAppWrapper customAppWrapper + CustomAppWrapper customAppWrapper, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished ); @POST @@ -486,7 +506,12 @@ public interface ApplicationManagementPublisherAPI { name = "applicationRelease", value = "The application release that need to be created.", required = true) - EntAppReleaseWrapper entAppReleaseWrapper + EntAppReleaseWrapper entAppReleaseWrapper, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished ); @POST @@ -536,7 +561,12 @@ public interface ApplicationManagementPublisherAPI { name = "applicationRelease", value = "The application release that need to be created.", required = true) - PublicAppReleaseWrapper publicAppReleaseWrapper + PublicAppReleaseWrapper publicAppReleaseWrapper, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished ); @POST @@ -581,7 +611,12 @@ public interface ApplicationManagementPublisherAPI { name = "applicationRelease", value = "The application release that need to be created.", required = true) - WebAppReleaseWrapper webAppReleaseWrapper + WebAppReleaseWrapper webAppReleaseWrapper, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished ); @POST @@ -631,7 +666,12 @@ public interface ApplicationManagementPublisherAPI { name = "applicationRelease", value = "The application release that need to be created.", required = true) - CustomAppReleaseWrapper customAppReleaseWrapper + CustomAppReleaseWrapper customAppReleaseWrapper, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished ); @PUT diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java index 3b521eec5c2..995c892aa51 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/SPApplicationService.java @@ -24,6 +24,7 @@ import io.entgra.application.mgt.common.wrapper.PublicAppWrapper; import io.entgra.application.mgt.common.wrapper.WebAppWrapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.Info; @@ -311,7 +312,12 @@ public interface SPApplicationService { } ) Response createEntApp(@PathParam("identity-server-id") int identityServerId, - @PathParam("service-provider-id") String serviceProviderId, ApplicationWrapper app); + @PathParam("service-provider-id") String serviceProviderId, ApplicationWrapper app, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished); /** * This method is used to register an APIM application for tenant domain. @@ -332,7 +338,12 @@ public interface SPApplicationService { } ) Response createPubApp(@PathParam("identity-server-id") int identityServerId, - @PathParam("service-provider-id") String serviceProviderId, PublicAppWrapper app); + @PathParam("service-provider-id") String serviceProviderId, PublicAppWrapper app, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished); @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/web-app") @POST @@ -350,7 +361,12 @@ public interface SPApplicationService { } ) Response createWebApp(@PathParam("identity-server-id") int identityServerId, - @PathParam("service-provider-id") String serviceProviderId, WebAppWrapper app); + @PathParam("service-provider-id") String serviceProviderId, WebAppWrapper app, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished); @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/custom-app") @POST @@ -368,5 +384,10 @@ public interface SPApplicationService { } ) Response createCustomApp(@PathParam("identity-server-id") int identityServerId, - @PathParam("service-provider-id") String serviceProviderId, CustomAppWrapper app); + @PathParam("service-provider-id") String serviceProviderId, CustomAppWrapper app, + @ApiParam( + name = "isPublished", + value = "Published state of the application" + ) + @QueryParam("isPublished") boolean isPublished); } diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java index f17e2e973de..078af292d99 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java @@ -169,9 +169,9 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Consumes(MediaType.APPLICATION_JSON) @Path("/ent-app") public Response createEntApp( - ApplicationWrapper applicationWrapper) { + ApplicationWrapper applicationWrapper, @QueryParam("is-published") boolean isPublished) { try { - return createApplication(applicationWrapper); + return createApplication(applicationWrapper, isPublished); } catch (BadRequestException e) { String msg = "Found incompatible payload with ent. app creating request."; log.error(msg, e); @@ -191,9 +191,9 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Consumes(MediaType.APPLICATION_JSON) @Path("/web-app") public Response createWebApp( - WebAppWrapper webAppWrapper) { + WebAppWrapper webAppWrapper, @QueryParam("is-published") boolean isPublished) { try { - return createApplication(webAppWrapper); + return createApplication(webAppWrapper, isPublished); } catch (BadRequestException e) { String msg = "Found incompatible payload with web app creating request."; log.error(msg, e); @@ -213,9 +213,9 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Consumes(MediaType.APPLICATION_JSON) @Path("/public-app") public Response createPubApp( - PublicAppWrapper publicAppWrapper) { + PublicAppWrapper publicAppWrapper, @QueryParam("is-published") boolean isPublished) { try { - return createApplication(publicAppWrapper); + return createApplication(publicAppWrapper, isPublished); } catch (BadRequestException e) { String msg = "Found incompatible payload with pub app creating request."; log.error(msg, e); @@ -235,9 +235,9 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Consumes(MediaType.APPLICATION_JSON) @Path("/custom-app") public Response createCustomApp( - CustomAppWrapper customAppWrapper) { + CustomAppWrapper customAppWrapper, @QueryParam("is-published") boolean isPublished) { try { - return createApplication(customAppWrapper); + return createApplication(customAppWrapper, isPublished); } catch (BadRequestException e) { String msg = "Found incompatible payload with custom app creating request."; log.error(msg, e); @@ -259,11 +259,12 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem public Response createEntAppRelease( @PathParam("deviceType") String deviceTypeName, @PathParam("appId") int appId, - EntAppReleaseWrapper entAppReleaseWrapper) { + EntAppReleaseWrapper entAppReleaseWrapper, + @QueryParam("isPublished") boolean isPublished) { try { ApplicationManager applicationManager = APIUtil.getApplicationManager(); applicationManager.validateEntAppReleaseCreatingRequest(entAppReleaseWrapper, deviceTypeName); - ApplicationRelease release = applicationManager.createEntAppRelease(appId, entAppReleaseWrapper); + ApplicationRelease release = applicationManager.createEntAppRelease(appId, entAppReleaseWrapper, isPublished); return Response.status(Response.Status.CREATED).entity(release).build(); } catch (RequestValidatingException e) { String msg = "Error occurred while validating binaryArtifact"; @@ -283,12 +284,12 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem public Response createPubAppRelease( @PathParam("deviceType") String deviceTypeName, @PathParam("appId") int appId, - PublicAppReleaseWrapper publicAppReleaseWrapper) { + PublicAppReleaseWrapper publicAppReleaseWrapper, @QueryParam("isPublished") boolean isPublished) { try { ApplicationManager applicationManager = APIUtil.getApplicationManager(); applicationManager.validatePublicAppReleaseCreatingRequest(publicAppReleaseWrapper, deviceTypeName); - ApplicationRelease applicationRelease = applicationManager.createPubAppRelease(appId, publicAppReleaseWrapper); + ApplicationRelease applicationRelease = applicationManager.createPubAppRelease(appId, publicAppReleaseWrapper, isPublished); return Response.status(Response.Status.CREATED).entity(applicationRelease).build(); } catch (ApplicationManagementException e) { String msg = "Error occurred while creating application release for the application with the id " + appId; @@ -311,11 +312,11 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem @Override public Response createWebAppRelease( @PathParam("appId") int appId, - WebAppReleaseWrapper webAppReleaseWrapper) { + WebAppReleaseWrapper webAppReleaseWrapper, @QueryParam("isPublished") boolean isPublished) { try { ApplicationManager applicationManager = APIUtil.getApplicationManager(); applicationManager.validateWebAppReleaseCreatingRequest(webAppReleaseWrapper); - ApplicationRelease applicationRelease= applicationManager.createWebAppRelease(appId, webAppReleaseWrapper); + ApplicationRelease applicationRelease= applicationManager.createWebAppRelease(appId, webAppReleaseWrapper, isPublished); return Response.status(Response.Status.CREATED).entity(applicationRelease).build(); } catch (ResourceManagementException e) { String msg = "Error occurred while uploading application release artifacts"; @@ -339,11 +340,11 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem public Response createCustomAppRelease( @PathParam("deviceType") String deviceTypeName, @PathParam("appId") int appId, - CustomAppReleaseWrapper customAppReleaseWrapper) { + CustomAppReleaseWrapper customAppReleaseWrapper, @QueryParam("isPublished") boolean isPublished) { try { ApplicationManager applicationManager = APIUtil.getApplicationManager(); applicationManager.validateCustomAppReleaseCreatingRequest(customAppReleaseWrapper, deviceTypeName); - ApplicationRelease release = applicationManager.createCustomAppRelease(appId, customAppReleaseWrapper); + ApplicationRelease release = applicationManager.createCustomAppRelease(appId, customAppReleaseWrapper, isPublished); return Response.status(Response.Status.CREATED).entity(release).build(); } catch (RequestValidatingException e) { String msg = "Error occurred while validating binaryArtifact"; @@ -864,10 +865,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem } } - public Response createApplication(T appWrapper) throws ApplicationManagementException, RequestValidatingException { + public Response createApplication(T appWrapper, boolean isPublished) throws ApplicationManagementException, RequestValidatingException { ApplicationManager applicationManager = APIUtil.getApplicationManager(); applicationManager.validateAppCreatingRequest(appWrapper); - Application application = applicationManager.createApplication(appWrapper); + Application application = applicationManager.createApplication(appWrapper, isPublished); if (application != null) { return Response.status(Response.Status.CREATED).entity(application).build(); } else { diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java index cceefb6c18d..ec197dd47f8 100644 --- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java +++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java @@ -294,32 +294,36 @@ public class SPApplicationServiceImpl implements SPApplicationService { @POST @Override public Response createEntApp(@PathParam("identity-server-id") int identityServerId, - @PathParam("service-provider-id") String serviceProviderId, ApplicationWrapper app) { - return createSPApplication(identityServerId, serviceProviderId, app); + @PathParam("service-provider-id") String serviceProviderId, ApplicationWrapper app, + @QueryParam("isPublished") boolean isPublished) { + return createSPApplication(identityServerId, serviceProviderId, app, isPublished); } @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/public-app") @POST @Override public Response createPubApp(@PathParam("identity-server-id") int identityServerId, - @PathParam("service-provider-id") String serviceProviderId, PublicAppWrapper app) { - return createSPApplication(identityServerId, serviceProviderId, app); + @PathParam("service-provider-id") String serviceProviderId, PublicAppWrapper app, + @QueryParam("isPublished") boolean isPublished) { + return createSPApplication(identityServerId, serviceProviderId, app, isPublished); } @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/web-app") @POST @Override public Response createWebApp(@PathParam("identity-server-id") int identityServerId, - @PathParam("service-provider-id") String serviceProviderId, WebAppWrapper app) { - return createSPApplication(identityServerId, serviceProviderId, app); + @PathParam("service-provider-id") String serviceProviderId, WebAppWrapper app, + @QueryParam("isPublished") boolean isPublished) { + return createSPApplication(identityServerId, serviceProviderId, app, isPublished); } @Path("/{identity-server-id}/service-provider/{service-provider-id}/create/custom-app") @POST @Override public Response createCustomApp(@PathParam("identity-server-id") int identityServerId, - @PathParam("service-provider-id") String serviceProviderId, CustomAppWrapper app) { - return createSPApplication(identityServerId, serviceProviderId, app); + @PathParam("service-provider-id") String serviceProviderId, CustomAppWrapper app, + @QueryParam("isPublished") boolean isPublished) { + return createSPApplication(identityServerId, serviceProviderId, app, isPublished); } /** @@ -331,10 +335,10 @@ public class SPApplicationServiceImpl implements SPApplicationService { * @param application wrapper class * @return Response */ - private Response createSPApplication(int identityServerId, String spUID, T appWrapper) { + private Response createSPApplication(int identityServerId, String spUID, T appWrapper, boolean isPublished) { try { SPApplicationManager spApplicationManager = APIUtil.getSPApplicationManager(); - Application createdApp = spApplicationManager.createSPApplication(appWrapper, identityServerId, spUID); + Application createdApp = spApplicationManager.createSPApplication(appWrapper, identityServerId, spUID, isPublished); return Response.status(Response.Status.CREATED).entity(createdApp).build(); } catch (NotFoundException e) { String msg = "No identity server exist with the id " + identityServerId; From c66fa5bd6090add58bb0b2d80089f9aff2579087 Mon Sep 17 00:00:00 2001 From: Mohamed Rashd Date: Mon, 18 Apr 2022 19:06:26 +0530 Subject: [PATCH 13/13] Fix application conf error message --- .../application/mgt/core/config/ConfigurationManager.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java index 898ef114213..f0753a09420 100644 --- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java +++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/ConfigurationManager.java @@ -103,8 +103,7 @@ public class ConfigurationManager { this.identityServiceProviderConfiguration = (IdentityServiceProviderConfiguration) identityServerConfigUnmarshaller.unmarshal(new File(identityServerConfigPath)); } catch (Exception e) { log.error(e); - throw new InvalidConfigurationException("Error occurred while initializing application config: " - + configPath, e); + throw new InvalidConfigurationException("Error occurred while initializing application managements configs: ", e); } }