diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/dto/ApplicationDTO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/dto/ApplicationDTO.java index 484dc4c2557..83813c3af37 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/dto/ApplicationDTO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/dto/ApplicationDTO.java @@ -95,10 +95,10 @@ public class ApplicationDTO { example = "REMOVED, ACTIVE") private String status; - @ApiModelProperty(name = "applicationReleases", + @ApiModelProperty(name = "applicationReleaseDTOs", value = "List of application releases", required = true) - private List applicationReleases; + private List applicationReleaseDTOs; public int getId() { return id; @@ -152,12 +152,12 @@ public class ApplicationDTO { this.paymentCurrency = paymentCurrency; } - public List getApplicationReleases() { - return applicationReleases; + public List getApplicationReleaseDTOs() { + return applicationReleaseDTOs; } - public void setApplicationReleases(List applicationReleases) { - this.applicationReleases = applicationReleases; + public void setApplicationReleaseDTOs(List applicationReleaseDTOs) { + this.applicationReleaseDTOs = applicationReleaseDTOs; } public List getUnrestrictedRoles() { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java index 5cca6efd570..b364512ffe7 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java @@ -28,6 +28,7 @@ import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.response.Application; +import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper; @@ -52,12 +53,12 @@ public interface ApplicationManager { /** * Updates an already existing application. * - * @param application Application that need to be updated. + * @param applicationWrapper Application that need to be updated. * @param applicationId ID of the application * @return Updated Application * @throws ApplicationManagementException ApplicationDTO Management Exception */ - ApplicationDTO updateApplication(int applicationId, ApplicationDTO application) throws ApplicationManagementException; + void updateApplication(int applicationId, ApplicationWrapper applicationWrapper) throws ApplicationManagementException; /** * Delete an application identified by the unique ID. @@ -93,7 +94,7 @@ public interface ApplicationManager { * @return the ApplicationDTO identified by the ID * @throws ApplicationManagementException ApplicationDTO Management Exception. */ - ApplicationDTO getApplicationById(int id, String state) throws ApplicationManagementException; + Application getApplicationById(int id, String state) throws ApplicationManagementException; /** * To get the ApplicationDTO for given application relase UUID. @@ -138,38 +139,34 @@ public interface ApplicationManager { /** * To update release images such as icons, banner and screenshots. * - * @param appId ID of the ApplicationDTO * @param uuid uuid of the ApplicationDTO - * @param iconFileStream icon file of the release - * @param bannerFileStream bannerFileStream of the release. - * @param attachments screenshot attachments of the release + * @param applicationArtifact Application artifact that contains names and input streams of the application artifacts. * @throws ApplicationManagementException ApplicationDTO Management Exception. */ - void updateApplicationImageArtifact(int appId, String uuid, InputStream iconFileStream, InputStream - bannerFileStream, List attachments) throws ApplicationManagementException; + void updateApplicationImageArtifact(String uuid, ApplicationArtifact applicationArtifact) throws ApplicationManagementException; /** * To update release images. * - * @param appId ID of the ApplicationDTO - * @param deviceType Applicable device type of the application + * @param deviceType Application artifact compatible device type name. + * @param appType Type of the application. * @param uuid uuid of the ApplicationDTO - * @param binaryFile binaryFile of the release. + * @param applicationArtifact Application artifact that contains names and input streams of the application artifacts. * @throws ApplicationManagementException ApplicationDTO Management Exception. */ - void updateApplicationArtifact(int appId, String deviceType, String uuid, InputStream binaryFile) - throws ApplicationManagementException; + void updateApplicationArtifact(String deviceType, String appType, String uuid, + ApplicationArtifact applicationArtifact) throws ApplicationManagementException; /** * To create an application release for an ApplicationDTO. * * @param applicationId ID of the ApplicationDTO - * @param applicationRelease ApplicatonRelease that need to be be created. + * @param applicationReleaseWrapper ApplicatonRelease that need to be be created. * @return the unique id of the application release, if the application release succeeded else -1 */ - ApplicationReleaseDTO createRelease(int applicationId, ApplicationReleaseDTO applicationRelease) - throws ApplicationManagementException; + ApplicationRelease createRelease(int applicationId, ApplicationReleaseWrapper applicationReleaseWrapper, + ApplicationArtifact applicationArtifact) throws ApplicationManagementException; /*** * @@ -201,20 +198,20 @@ public interface ApplicationManager { * @param applicationType Type of the application * @throws RequestValidatingException throws if payload does not satisfy requrements. */ - void validateReleaseCreatingRequest(ApplicationReleaseWrapper applicationReleaseWrapper, - String applicationType) throws RequestValidatingException; + void validateReleaseCreatingRequest(ApplicationReleaseWrapper applicationReleaseWrapper, String applicationType) + throws RequestValidatingException; /*** * - * @param binaryFile Uploading binary fila. i.e .apk or .ipa * @param iconFile Icon file for the application. * @param bannerFile Banner file for the application. * @param attachmentList Screenshot list. - * @param applicationType Type of the application. * @throws RequestValidatingException If request doesn't contains required attachments. */ - void isValidAttachmentSet(Attachment binaryFile, Attachment iconFile, Attachment bannerFile, - List attachmentList, String applicationType) throws RequestValidatingException; + void validateImageArtifacts(Attachment iconFile, Attachment bannerFile, List attachmentList) + throws RequestValidatingException; + + void validateBinaryArtifact(Attachment binaryFile, String applicationType) throws RequestValidatingException; void addAplicationCategories(List categories) throws ApplicationManagementException; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationStorageManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationStorageManager.java index ba4dde5ca55..8403d20c9cf 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationStorageManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationStorageManager.java @@ -47,13 +47,9 @@ public interface ApplicationStorageManager { * To upload image artifacts related with an ApplicationDTO. * * @param applicationRelease Release of the application - * @param iconFile Icon File input stream - * @param bannerFile Banner File input stream - * @param screenshots Input Streams of screenshots * @throws ResourceManagementException Resource Management Exception. */ - ApplicationReleaseDTO updateImageArtifacts(ApplicationReleaseDTO applicationRelease, InputStream iconFile, - InputStream bannerFile, List screenshots) throws ResourceManagementException; + void deleteImageArtifacts(ApplicationReleaseDTO applicationRelease) throws ResourceManagementException; ApplicationInstaller getAppInstallerData(InputStream binaryFile, String deviceType) throws ApplicationStorageManagementException; @@ -74,14 +70,12 @@ public interface ApplicationStorageManager { /** * To upload release artifacts for an ApplicationDTO. * - * @param applicationRelease applicationRelease ApplicationDTO release of a particular application. - * @param appType Type of the application. - * @param deviceType Compatible device tipe of the application. - * @param binaryFile Binary File for the release. + * @param applicationReleaseDTO applicationRelease ApplicationDTO release of a particular application. + * @param deletingAppHashValue Hash value of the deleting application release. * @throws ApplicationStorageManagementException Resource Management Exception. */ - ApplicationReleaseDTO updateReleaseArtifacts(ApplicationReleaseDTO applicationRelease, String appType, String deviceType, - InputStream binaryFile) throws ApplicationStorageManagementException, RequestValidatingException; + void copyImageArtifactsAndDeleteInstaller(String deletingAppHashValue, + ApplicationReleaseDTO applicationReleaseDTO) throws ApplicationStorageManagementException; /** * To delete the artifacts related with particular ApplicationDTO Release. diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java index feaa04b72c9..2d63e013106 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java @@ -24,6 +24,7 @@ import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; import org.wso2.carbon.device.application.mgt.common.dto.CategoryDTO; import org.wso2.carbon.device.application.mgt.common.dto.TagDTO; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; + import java.util.List; /** @@ -115,8 +116,7 @@ public interface ApplicationDAO { * @return the application * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. */ - ApplicationDTO getApplicationById(String id, int tenantId) throws - ApplicationManagementDAOException; + ApplicationDTO getApplicationById(String id, int tenantId) throws ApplicationManagementDAOException; /** * To get the application with the given id @@ -149,15 +149,16 @@ public interface ApplicationDAO { boolean verifyApplicationExistenceById(int appId, int tenantId) throws ApplicationManagementDAOException; /** - * To get the application id of the application specified by the UUID + * Verify whether application exist for given application name and device type. Because a name and device type is + * unique for an application. * * @param appName name of the application. - * @param appType type of the application. + * @param deviceTypeId ID of the device type. * @param tenantId ID of the tenant. * @return ID of the ApplicationDTO. - * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. + * @throws ApplicationManagementDAOException Application Management DAO Exception. */ - int getApplicationId(String appName, String appType, int tenantId) throws ApplicationManagementDAOException; + boolean isValidAppName(String appName, int deviceTypeId, int tenantId) throws ApplicationManagementDAOException; /** * To edit the given application. diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java index a954c34ae43..2bdb113c74f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java @@ -82,12 +82,11 @@ public interface ApplicationReleaseDAO { * To update an ApplicationDTO release. * * @param applicationRelease ApplicationReleaseDTO that need to be updated. - * @param applicationId Id of the application. * @param tenantId Id of the tenant * @return the updated ApplicationDTO Release * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception */ - ApplicationReleaseDTO updateRelease(int applicationId, ApplicationReleaseDTO applicationRelease, int tenantId) throws + ApplicationReleaseDTO updateRelease(ApplicationReleaseDTO applicationRelease, int tenantId) throws ApplicationManagementDAOException; /** @@ -129,6 +128,8 @@ public interface ApplicationReleaseDAO { ApplicationReleaseDTO getReleaseByIds(int applicationId, String releaseUuid, int tenantId) throws ApplicationManagementDAOException; + ApplicationReleaseDTO getReleaseByUUID(String uuid, int tenantId) throws ApplicationManagementDAOException; + /** * To verify whether application release exist or not. * @@ -142,12 +143,11 @@ public interface ApplicationReleaseDAO { /** * To verify whether application release exist or not for the given app release version. * - * @param appId ID of the application. * @param hashVal Hash value of the application release. * @param tenantId Tenant Id * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. */ - boolean verifyReleaseExistenceByHash(int appId, String hashVal, int tenantId) + boolean verifyReleaseExistenceByHash(String hashVal, int tenantId) throws ApplicationManagementDAOException; /** @@ -177,6 +177,6 @@ public interface ApplicationReleaseDAO { * @return True if application release package name already exist in the IoT server, Otherwise returns False. * @throws ApplicationManagementDAOException Application Management DAO Exception. */ - boolean isActiveReleaseExisitForPackageName(String packageName, int tenantId) throws ApplicationManagementDAOException; + boolean isActiveReleaseExisitForPackageName(String packageName, int tenantId, String inactiveState) throws ApplicationManagementDAOException; } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java index 8386301900d..08d7738b14f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java @@ -32,6 +32,7 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorage import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.core.config.Configuration; import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; +import org.wso2.carbon.device.application.mgt.core.exception.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import java.sql.PreparedStatement; @@ -47,66 +48,6 @@ public class Util { private static final Log log = LogFactory.getLog(Util.class); -// /** -// * 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 loadApplications(ResultSet rs) throws SQLException, JSONException { -// -// List applications = new ArrayList<>(); -// ApplicationDTO application = null; -// int applicationId = -1; -// boolean hasNext = rs.next(); -// -// while (hasNext) { -// if (applicationId != rs.getInt("APP_ID")) { -// if (application != null) { -// applications.add(application); -// } -// applicationId = rs.getInt("APP_ID"); -// application = new ApplicationDTO(); -// application.setTags(new ArrayList<>()); -// application.setUnrestrictedRoles(new ArrayList<>()); -// application.setId(applicationId); -// application.setName(rs.getString("APP_NAME")); -// application.setType(rs.getString("APP_TYPE")); -// application.setAppCategories(rs.getString("APP_CATEGORY")); -// application.setSubType(rs.getString("SUB_TYPE")); -// application.setPaymentCurrency(rs.getString("CURRENCY")); -// application.setIsRestricted(rs.getBoolean("RESTRICTED")); -// application.setStatus(rs.getString("STATUS")); -// String tag = rs.getString("APP_TAG"); -// String unrestrictedRole = rs.getString("ROLE"); -// if (tag != null) { -// application.getTags().add(tag); -// } -// if (unrestrictedRole != null) { -// application.getUnrestrictedRoles().add(unrestrictedRole); -// } -// } else { -// String tag = rs.getString("APP_TAG"); -// String unrestrictedRole = rs.getString("ROLE"); -// if (application != null) { -// if (tag != null && !application.getTags().contains(tag)) { -// application.getTags().add(tag); -// } -// if (unrestrictedRole != null && !application.getUnrestrictedRoles().contains(unrestrictedRole)) { -// application.getUnrestrictedRoles().add(unrestrictedRole); -// } -// } -// } -// hasNext = rs.next(); -// if (!hasNext) { -// applications.add(application); -// } -// } -// return applications; -// } - /** * To create application object from the result set retrieved from the Database. * @@ -128,7 +69,7 @@ public class Util { applications.add(application); } application = new ApplicationDTO(); - application.setApplicationReleases(new ArrayList<>()); + application.setApplicationReleaseDTOs(new ArrayList<>()); applicationId = rs.getInt("APP_ID"); application.setId(applicationId); application.setName(rs.getString("APP_NAME")); @@ -139,10 +80,10 @@ public class Util { application.setStatus(rs.getString("APP_STATUS")); application.setAppRating(rs.getInt("APP_RATING")); application.setDeviceTypeId(rs.getInt("APP_DEVICE_TYPE_ID")); - application.getApplicationReleases().add(loadAppRelease(rs)); + application.getApplicationReleaseDTOs().add(loadAppRelease(rs)); } else { - if (application != null && application.getApplicationReleases() != null) { - application.getApplicationReleases().add(loadAppRelease(rs)); + if (application != null && application.getApplicationReleaseDTOs() != null) { + application.getApplicationReleaseDTOs().add(loadAppRelease(rs)); } } hasNext = rs.next(); @@ -167,10 +108,12 @@ public class Util { 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("AP_RELEASE_SC1"); - appRelease.setScreenshotName2("AP_RELEASE_SC2"); - appRelease.setScreenshotName3("AP_RELEASE_SC3"); + 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.setSupportedOsVersions(rs.getString("RELEASE_SUP_OS_VERSIONS")); @@ -189,41 +132,18 @@ public class Util { * @throws SQLException SQL Exception * @throws JSONException JSONException. */ - public static ApplicationDTO loadApplication(ResultSet rs) throws SQLException, JSONException { - - ApplicationDTO application = null; - int applicatioId; - int iteration = 0; - if (rs != null) { - while (rs.next()) { - if (iteration == 0) { - application = new ApplicationDTO(); - application.setTags(new ArrayList<>()); - application.setUnrestrictedRoles(new ArrayList<>()); - applicatioId = rs.getInt("APP_ID"); - application.setId(applicatioId); - application.setName(rs.getString("APP_NAME")); - application.setType(rs.getString("APP_TYPE")); - application.setAppCategory(rs.getString("APP_CATEGORY")); - application.setSubType(rs.getString("SUB_TYPE")); - application.setPaymentCurrency(rs.getString("CURRENCY")); -// application.setIsRestricted(rs.getBoolean("RESTRICTED")); - application.setDeviceTypeId(rs.getInt("DEVICE_TYPE_ID")); - } - - String tag = rs.getString("APP_TAG"); - String unrestrictedRole = rs.getString("ROLE"); - if (tag != null && !application.getTags().contains(tag)) { - application.getTags().add(tag); - } - if (unrestrictedRole != null && !application.getUnrestrictedRoles().contains(unrestrictedRole)) { - application.getUnrestrictedRoles().add(unrestrictedRole); - } - iteration++; - } + public static ApplicationDTO loadApplication(ResultSet rs) + throws SQLException, JSONException, UnexpectedServerErrorException { + List applicationDTOs = loadApplications(rs); + if (applicationDTOs.isEmpty()) { + return null; } - return application; - + if (applicationDTOs.size() > 1) { + String msg = "Internal server error. Found more than one application for requested application ID"; + log.error(msg); + throw new UnexpectedServerErrorException(msg); + } + return applicationDTOs.get(0); } /** diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java index 7d2327f115d..eb716719712 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -24,17 +24,16 @@ import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.wso2.carbon.device.application.mgt.common.AppLifecycleState; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO; -import org.wso2.carbon.device.application.mgt.common.ApplicationList; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; import org.wso2.carbon.device.application.mgt.common.dto.CategoryDTO; import org.wso2.carbon.device.application.mgt.common.Filter; -import org.wso2.carbon.device.application.mgt.common.Pagination; import org.wso2.carbon.device.application.mgt.common.dto.TagDTO; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO; import org.wso2.carbon.device.application.mgt.core.dao.common.Util; import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.exception.UnexpectedServerErrorException; import java.sql.Connection; import java.sql.PreparedStatement; @@ -150,10 +149,12 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic + "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.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " @@ -163,8 +164,8 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic + "FROM AP_APP " + "INNER JOIN AP_APP_RELEASE ON " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID AND " - + "AP_APP.TENANT_ID = ? AND " - + "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID"; + + "AP_APP.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + + "WHERE AP_APP.TENANT_ID = ?"; if (filter == null) { throw new ApplicationManagementDAOException("Filter need to be instantiated"); @@ -381,14 +382,15 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); } catch (DBConnectionException e) { throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (UnexpectedServerErrorException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); } finally { Util.cleanupResources(stmt, rs); } } @Override - public ApplicationDTO getApplicationById(String id, int tenantId) throws - ApplicationManagementDAOException { + public ApplicationDTO getApplicationById(String id, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { log.debug("Getting application with the id:" + id); } @@ -423,14 +425,16 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); } catch (DBConnectionException e) { throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (UnexpectedServerErrorException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); } finally { Util.cleanupResources(stmt, rs); } } @Override - public ApplicationDTO getApplicationByUUID(String releaseUuid, int tenantId) throws - ApplicationManagementDAOException { + public ApplicationDTO getApplicationByUUID(String releaseUuid, int tenantId) + throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { log.debug("Getting application with the release UUID: " + releaseUuid + " from the database"); } @@ -470,14 +474,16 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); } catch (DBConnectionException e) { throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (UnexpectedServerErrorException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); } finally { Util.cleanupResources(stmt, rs); } } @Override - public ApplicationDTO getApplicationById(int applicationId, int tenantId) throws - ApplicationManagementDAOException { + public ApplicationDTO getApplicationById(int applicationId, int tenantId) + throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { log.debug("Getting application with the id (" + applicationId + ") from the database"); } @@ -486,28 +492,48 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic ResultSet rs = null; try { conn = this.getDBConnection(); - String sql = - "SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY " - + "AS APP_CATEGORY, AP_APP.SUB_TYPE AS SUB_TYPE, AP_APP.CURRENCY AS CURRENCY, " - + "AP_APP.RESTRICTED AS RESTRICTED, AP_APP.DEVICE_TYPE_ID AS DEVICE_TYPE_ID, " - + "AP_APP_TAG.TAG AS APP_TAG, AP_UNRESTRICTED_ROLE.ROLE AS ROLE FROM " - + "((AP_APP LEFT JOIN AP_APP_TAG ON AP_APP.ID = AP_APP_TAG.AP_APP_ID) " - + "LEFT JOIN AP_UNRESTRICTED_ROLE ON AP_APP.ID = AP_UNRESTRICTED_ROLE.AP_APP_ID) WHERE " - + "AP_APP.ID = ? AND AP_APP.TENANT_ID = ? AND AP_APP.STATUS != ?"; + 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.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.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_PRICE AS RELEASE_PRICE, " + + "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, " + + "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 " + + "INNER 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 " + + "AP_APP.ID =? AND " + + "AP_APP.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, applicationId); stmt.setInt(2, tenantId); - stmt.setString(3, AppLifecycleState.REMOVED.toString()); rs = stmt.executeQuery(); - if (log.isDebugEnabled()) { log.debug("Successfully retrieved basic details of the application with the id " + applicationId); } - return Util.loadApplication(rs); - } catch (SQLException e) { throw new ApplicationManagementDAOException( "Error occurred while getting application details with app id " + applicationId + @@ -516,6 +542,8 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); } catch (DBConnectionException e) { throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (UnexpectedServerErrorException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); } finally { Util.cleanupResources(stmt, rs); } @@ -555,10 +583,12 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } @Override - public ApplicationDTO editApplication(ApplicationDTO application, int tenantId) throws ApplicationManagementDAOException { + public ApplicationDTO editApplication(ApplicationDTO application, int tenantId) + throws ApplicationManagementDAOException { int paramIndex = 1; Connection conn; PreparedStatement stmt = null; + //todo this is wrong ApplicationDTO existingApplication = this.getApplicationById(application.getId(), tenantId); if (existingApplication == null) { @@ -883,7 +913,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic + "FROM " + "AP_APP_TAG tag INNER JOIN AP_APP_TAG_MAPPING tag_map ON tag.ID = tag_map.AP_APP_TAG_ID " + "INNER JOIN AP_APP app ON tag_map.AP_APP_ID = app.ID " - + "WHERE app.ID = ? and app.TENANT_ID = ?"; + + "WHERE app.ID = ? AND app.TENANT_ID = ?"; try { conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)){ @@ -915,7 +945,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic + "FROM " + "AP_APP_CATEGORY cat INNER JOIN AP_APP_CATEGORY_MAPPING cat_map ON cat.ID = cat_map.AP_APP_CATEGORY_ID " + "INNER JOIN AP_APP app ON cat_map.AP_APP_ID = app.ID " - + "WHERE app.ID = ? and app.TENANT_ID = ?"; + + "WHERE app.ID = ? AND app.TENANT_ID = ?"; try { conn = this.getDBConnection(); try (PreparedStatement stmt = conn.prepareStatement(sql)){ @@ -1019,7 +1049,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic List applicationReleaseList = new ArrayList<>(); applicationReleaseList.add(appRelease); - application.setApplicationReleases(applicationReleaseList); + application.setApplicationReleaseDTOs(applicationReleaseList); } return application; } catch (SQLException e) { @@ -1035,23 +1065,25 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } @Override - public int getApplicationId(String appName, String appType, int tenantId) throws ApplicationManagementDAOException { + public boolean isValidAppName(String appName, int deviceTypeId, int tenantId) throws ApplicationManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; String sql; - int id = -1; try { conn = this.getDBConnection(); - sql = "SELECT ID FROM AP_APP WHERE NAME = ? AND TYPE = ? AND TENANT_ID = ?"; + sql = "SELECT AP_APP.ID AS ID " + + "FROM AP_APP " + + "WHERE " + + "AP_APP.NAME = ? AND " + + "AP_APP.DEVICE_TYPE_ID = ? AND " + + "AP_APP.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, appName); - stmt.setString(2, appType); + stmt.setInt(2, deviceTypeId); stmt.setInt(3, tenantId); rs = stmt.executeQuery(); - if (rs.next()) { - id = rs.getInt(1); - } + return rs.next(); } catch (DBConnectionException e) { throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); } catch (SQLException e) { @@ -1059,6 +1091,5 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic } finally { Util.cleanupResources(stmt, rs); } - return id; } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java index 732c3b6e407..cef49374030 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java @@ -222,6 +222,52 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements } } + @Override + public ApplicationReleaseDTO getReleaseByUUID( String uuid, int tenantId) throws ApplicationManagementDAOException { + Connection connection; + String sql = + "SELECT AR.DESCRIPTION AS RELEASE_DESCRIPTION, " + + "AR.VERSION AS RELEASE_VERSION, " + + "AR.UUID AS RELEASE_UUID, " + + "AR.RELEASE_TYPE AS RELEASE_TYPE, " + + "AR.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, " + + "AR.ICON_LOCATION AS AP_RELEASE_ICON_LOC, " + + "AR.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, " + + "AR.SC_1_LOCATION AS AP_RELEASE_SC1, " + + "AR.SC_2_LOCATION AS AP_RELEASE_SC2, " + + "AR.SC_3_LOCATION AS AP_RELEASE_SC3, " + + "AR.APP_HASH_VALUE AS RELEASE_HASH_VALUE, " + + "AR.APP_PRICE AS RELEASE_PRICE, " + + "AR.APP_META_INFO AS RELEASE_META_INFO, " + + "AR.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + + "AR.RATING AS RELEASE_RATING, " + + "AR.CURRENT_STATE AS RELEASE_CURRENT_STATE, AR.RATED_USERS AS RATED_USER_COUNT " + + "FROM AP_APP_RELEASE AS AR " + + "WHERE AR.UUID = ? AND AR.TENAT_ID = ?"; + + try { + connection = this.getDBConnection(); + try (PreparedStatement statement = connection.prepareStatement(sql)) { + statement.setString(1, uuid); + statement.setInt(2, tenantId); + try (ResultSet resultSet = statement.executeQuery()) { + if (resultSet.next()) { + return Util.loadAppRelease(resultSet); + } + return null; + } + } + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException( + "Database connection exception while trying to get the release details of the UUID of the application release: " + + uuid, e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "Error while getting release details of the UUID of the application " + "release: " + uuid + + " , while executing the query " + sql, e); + } + } + /** * To insert the application release properties. * @@ -378,39 +424,56 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements /** * To insert the application release properties. * - * @param applicationRelease ApplicationDTO Release the properties of which that need to be inserted. + * @param applicationReleaseDTO ApplicationDTO Release the properties of which that need to be inserted. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. */ @Override - public ApplicationReleaseDTO updateRelease(int applicationId, ApplicationReleaseDTO applicationRelease, int tenantId) + public ApplicationReleaseDTO updateRelease(ApplicationReleaseDTO applicationReleaseDTO, int tenantId) throws ApplicationManagementDAOException { Connection connection; PreparedStatement statement = null; - String sql = "UPDATE AP_APP_RELEASE SET VERSION = ?, UUID = ?, RELEASE_TYPE = ?, PACKAGE_NAME = ?," - + " APP_PRICE = ?, STORED_LOCATION = ?, BANNER_LOCATION = ?, ICON_LOCATION =?, SC_1_LOCATION = ?, " + - "SC_2_LOCATION = ?," - + " SC_3_LOCATION = ?, APP_HASH_VALUE = ?, SHARED_WITH_ALL_TENANTS = ?, APP_META_INFO = ? " - + "WHERE AP_APP_ID = ? AND TENANT_ID = ? AND ID = ?;"; + String sql = "UPDATE AP_APP_RELEASE " + + "SET " + + "DESCRIPTION = ?, " + + "VERSION = ?, " + + "UUID = ?, " + + "RELEASE_TYPE = ?, " + + "PACKAGE_NAME = ?, " + + "APP_PRICE = ?, " + + "INSTALLER_LOCATION = ?, " + + "BANNER_LOCATION = ?, " + + "ICON_LOCATION = ?, " + + "SC_1_LOCATION = ?, " + + "SC_2_LOCATION = ?, " + + "SC_3_LOCATION = ?, " + + "APP_HASH_VALUE = ?, " + + "SHARED_WITH_ALL_TENANTS = ?, " + + "APP_META_INFO = ?, " + + "SUPPORTED_OS_VERSIONS = ?, " + + "CURRENT_STATE = ? " + + "WHERE ID = ? AND TENANT_ID = ? "; try { connection = this.getDBConnection(); statement = connection.prepareStatement(sql); - statement.setString(1, applicationRelease.getVersion()); - statement.setString(2, applicationRelease.getUuid()); - statement.setString(3, applicationRelease.getReleaseType()); - statement.setString(4, applicationRelease.getPackageName()); - statement.setDouble(5, applicationRelease.getPrice()); - statement.setString(6, applicationRelease.getInstallerName()); - statement.setString(7, applicationRelease.getBannerName()); - statement.setString(8, applicationRelease.getIconName()); - statement.setString(9, applicationRelease.getScreenshotName1()); - statement.setString(10, applicationRelease.getScreenshotName2()); - statement.setString(11, applicationRelease.getScreenshotName3()); - statement.setString(12, applicationRelease.getAppHashValue()); - statement.setBoolean(13, applicationRelease.getIsSharedWithAllTenants()); - statement.setString(14, applicationRelease.getMetaData()); - statement.setInt(15, applicationId); - statement.setInt(16, tenantId); - statement.setInt(17, applicationRelease.getId()); + statement.setString(1, applicationReleaseDTO.getDescription()); + statement.setString(2, applicationReleaseDTO.getVersion()); + statement.setString(3, applicationReleaseDTO.getUuid()); + statement.setString(4, applicationReleaseDTO.getReleaseType()); + statement.setString(5, applicationReleaseDTO.getPackageName()); + statement.setDouble(6, applicationReleaseDTO.getPrice()); + statement.setString(7, applicationReleaseDTO.getInstallerName()); + statement.setString(8, applicationReleaseDTO.getBannerName()); + statement.setString(9, applicationReleaseDTO.getIconName()); + statement.setString(10, applicationReleaseDTO.getScreenshotName1()); + statement.setString(11, applicationReleaseDTO.getScreenshotName2()); + statement.setString(12, applicationReleaseDTO.getScreenshotName3()); + statement.setString(13, applicationReleaseDTO.getAppHashValue()); + statement.setBoolean(14, applicationReleaseDTO.getIsSharedWithAllTenants()); + statement.setString(15, applicationReleaseDTO.getMetaData()); + statement.setString(16, applicationReleaseDTO.getSupportedOsVersions()); + statement.setString(17, applicationReleaseDTO.getCurrentState()); + statement.setInt(18, tenantId); + statement.setInt(19, applicationReleaseDTO.getId()); if (statement.executeUpdate() == 0) { return null; } @@ -423,7 +486,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements } finally { Util.cleanupResources(statement, null); } - return applicationRelease; + return applicationReleaseDTO; } /** @@ -456,35 +519,27 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements } @Override - public boolean verifyReleaseExistenceByHash(int appId, String hashVal, int tenantId) throws ApplicationManagementDAOException { + public boolean verifyReleaseExistenceByHash(String hashVal, int tenantId) throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { - log.debug("Verifying application release existence by application id:" + appId - + " and application hash value: " + hashVal); + log.debug("Verifying application release existence by application hash value: " + hashVal); } Connection conn; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.getDBConnection(); - String sql = - "SELECT AR.ID AS RELEASE_ID FROM AP_APP_RELEASE AS AR WHERE AR.AP_APP_ID = ? AND " - + "AR.APP_HASH_VALUE = ? AND AR.TENANT_ID = ?;"; + String sql = "SELECT AR.ID AS RELEASE_ID FROM AP_APP_RELEASE AS AR WHERE AR.APP_HASH_VALUE = ? AND " + + "AR.TENANT_ID = ?;"; stmt = conn.prepareStatement(sql); - stmt.setInt(1, appId); - stmt.setString(2, hashVal); - stmt.setInt(3, tenantId); + stmt.setString(1, hashVal); + stmt.setInt(2, tenantId); rs = stmt.executeQuery(); - - if (log.isDebugEnabled()) { - log.debug("Successfully retrieved basic details of the application release with the application ID " - + appId + " ApplicationDTO release hash value: " + hashVal); - } return rs.next(); } catch (SQLException e) { throw new ApplicationManagementDAOException( - "Error occurred while getting application release details with app ID: " + appId - + " App release hash value: " + hashVal + " While executing query ", e); + "Error occurred while getting application release details for application release hash value: " + + hashVal + " While executing query ", e); } catch (DBConnectionException e) { throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); } finally { @@ -658,7 +713,8 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements } @Override - public boolean isActiveReleaseExisitForPackageName(String packageName, int tenantId) throws ApplicationManagementDAOException { + public boolean isActiveReleaseExisitForPackageName(String packageName, int tenantId, String inactiveState) + throws ApplicationManagementDAOException { if (log.isDebugEnabled()) { log.debug("Verifying application release existence for package name:" + packageName); } @@ -671,7 +727,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setString(1, packageName); - stmt.setString(2, AppLifecycleState.REMOVED.toString()); + stmt.setString(2, inactiveState); stmt.setInt(3, tenantId); try (ResultSet rs = stmt.executeQuery()) { return rs.next(); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java index 1047c0f6e9e..8fdaa315b23 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java @@ -67,12 +67,12 @@ import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException; import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.exception.UnexpectedServerErrorException; -import org.wso2.carbon.device.application.mgt.core.exception.ValidationException; import org.wso2.carbon.device.application.mgt.core.exception.VisibilityManagementDAOException; import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManager; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.Constants; +import org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -141,8 +141,13 @@ public class ApplicationManagerImpl implements ApplicationManager { + userName); } try { - applicationDTO = addApplicationReleaseArtifacts(appWrapperToAppDTO(applicationWrapper), - applicationArtifact); + applicationDTO = appWrapperToAppDTO(applicationWrapper); + ApplicationReleaseDTO initialApplicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); + applicationDTO.getApplicationReleaseDTOs().clear(); + + ApplicationReleaseDTO applicationReleaseDTO = addApplicationReleaseArtifacts(applicationDTO.getType(), applicationDTO.getDeviceTypeName(), + initialApplicationReleaseDTO, applicationArtifact); + applicationDTO.getApplicationReleaseDTOs().add(addImageArtifacts(applicationReleaseDTO, applicationArtifact)); } catch (UnexpectedServerErrorException e) { String msg = "Error occurred when getting Device Type data."; log.error(msg); @@ -156,8 +161,8 @@ public class ApplicationManagerImpl implements ApplicationManager { try { List applicationReleaseEntities = new ArrayList<>(); ApplicationReleaseDTO applicationReleaseDTO; - Filter filter = new Filter(); + Filter filter = new Filter(); filter.setFullMatch(true); filter.setAppName(applicationDTO.getName().trim()); filter.setOffset(0); @@ -188,10 +193,20 @@ public class ApplicationManagerImpl implements ApplicationManager { List unrestrictedRoles = applicationWrapper.getUnrestrictedRoles(); if (!unrestrictedRoles.isEmpty()) { if (!isValidRestrictedRole(unrestrictedRoles)) { + ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Unrestricted role list contain role/roles which are not in the user store."; log.error(msg); throw new ApplicationManagementException(msg); } + + if (!hasUserRole(unrestrictedRoles, userName)){ + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = + "You are trying to restrict the visibility of the application for a role set, but in order to perform the action at least one role should be assigned to user: " + + userName; + log.error(msg); + throw new BadRequestException(msg); + } this.visibilityDAO.addUnrestrictedRoles(unrestrictedRoles, appId, tenantId); if (log.isDebugEnabled()) { log.debug("New restricted roles to app ID mapping added to AP_UNRESTRICTED_ROLE table." @@ -246,7 +261,6 @@ public class ApplicationManagerImpl implements ApplicationManager { } tagIds = this.applicationDAO.getTagIdsForTagNames(tags, tenantId); } else { - for (TagDTO tagDTO : registeredTags) { for (String tagName : tags) { if (tagName.equals(tagDTO.getTagName())) { @@ -263,7 +277,7 @@ public class ApplicationManagerImpl implements ApplicationManager { log.debug("Creating a new release. App Id:" + appId); } String initialLifecycleState = lifecycleStateManager.getInitialState(); - applicationReleaseDTO = applicationDTO.getApplicationReleases().get(0); + applicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); applicationReleaseDTO.setCurrentState(initialLifecycleState); applicationReleaseDTO = this.applicationReleaseDAO.createRelease(applicationReleaseDTO, appId, tenantId); LifecycleStateDTO lifecycleStateDTO = getLifecycleStateInstance(initialLifecycleState, @@ -271,7 +285,7 @@ public class ApplicationManagerImpl implements ApplicationManager { this.lifecycleStateDAO .addLifecycleState(lifecycleStateDTO, appId, applicationReleaseDTO.getUuid(), tenantId); applicationReleaseEntities.add(applicationReleaseDTO); - applicationDTO.setApplicationReleases(applicationReleaseEntities); + applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); application = appDtoToAppResponse(applicationDTO); ConnectionManagerUtil.commitDBTransaction(); } @@ -318,20 +332,17 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - private ApplicationDTO addApplicationReleaseArtifacts(ApplicationDTO applicationDTO, - ApplicationArtifact applicationArtifact) throws ResourceManagementException, - ApplicationManagementException { + private ApplicationReleaseDTO addApplicationReleaseArtifacts(String applicationType, String deviceType, + ApplicationReleaseDTO applicationReleaseDTO, ApplicationArtifact applicationArtifact) + throws ResourceManagementException, ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager(); - List applicationReleaseEntities = new ArrayList<>(); - ApplicationReleaseDTO applicationReleaseDTO; - applicationReleaseDTO = applicationDTO.getApplicationReleases().get(0); String uuid = UUID.randomUUID().toString(); applicationReleaseDTO.setUuid(uuid); // The application executable artifacts such as apks are uploaded. - if (ApplicationType.ENTERPRISE.toString().equals(applicationDTO.getType())) { + if (ApplicationType.ENTERPRISE.toString().equals(applicationType)) { try { byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream()); @@ -339,11 +350,12 @@ public class ApplicationManagerImpl implements ApplicationManager { try (ByteArrayInputStream binary = new ByteArrayInputStream(content)) { ApplicationInstaller applicationInstaller = applicationStorageManager - .getAppInstallerData(binary, applicationDTO.getDeviceTypeName()); + .getAppInstallerData(binary, deviceType); String packagename = applicationInstaller.getPackageName(); ConnectionManagerUtil.getDBConnection(); - if (applicationReleaseDAO.isActiveReleaseExisitForPackageName(packagename, tenantId)) { + if (applicationReleaseDAO.isActiveReleaseExisitForPackageName(packagename, tenantId, + lifecycleStateManager.getEndState())) { String msg = "Application release is already exist for the package name: " + packagename + ". Either you can delete all application releases for package " + packagename + " or " + "you can add this app release as an new application release, under the existing " @@ -353,10 +365,27 @@ public class ApplicationManagerImpl implements ApplicationManager { } applicationReleaseDTO.setVersion(applicationInstaller.getVersion()); applicationReleaseDTO.setPackageName(packagename); + + String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content)); + if (md5OfApp == null) { + String msg = "Error occurred while md5sum value retrieving process: application UUID " + + applicationReleaseDTO.getUuid(); + log.error(msg); + throw new ApplicationStorageManagementException(msg); + } + if (this.applicationReleaseDAO + .verifyReleaseExistenceByHash(md5OfApp, tenantId)) { + throw new BadRequestException( + "Application release exists for the uploaded binary file. Application Type: " + + applicationType + " Device Tyep: " + deviceType); + } + + applicationReleaseDTO.setAppHashValue(md5OfApp); + try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) { applicationReleaseDTO = applicationStorageManager - .uploadReleaseArtifact(applicationReleaseDTO, applicationDTO.getType(), - applicationDTO.getDeviceTypeName(), binaryDuplicate); + .uploadReleaseArtifact(applicationReleaseDTO,applicationType, + deviceType, binaryDuplicate); } } } catch (IOException e) { @@ -377,12 +406,18 @@ public class ApplicationManagerImpl implements ApplicationManager { } finally { ConnectionManagerUtil.closeDBConnection(); } - } else if (ApplicationType.WEB_CLIP.toString().equals(applicationDTO.getType())) { + } else if (ApplicationType.WEB_CLIP.toString().equals(applicationType)) { applicationReleaseDTO.setVersion(Constants.DEFAULT_VERSION); applicationReleaseDTO.setInstallerName(applicationReleaseDTO.getUrl()); // Since WEB CLIP doesn't have an installer, set uuid as has value for WEB CLIP applicationReleaseDTO.setAppHashValue(uuid); } + return applicationReleaseDTO; + } + + private ApplicationReleaseDTO addImageArtifacts(ApplicationReleaseDTO applicationReleaseDTO, + ApplicationArtifact applicationArtifact) throws ResourceManagementException { + ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager(); applicationReleaseDTO.setIconName(applicationArtifact.getIconName()); applicationReleaseDTO.setBannerName(applicationArtifact.getBannerName()); @@ -407,9 +442,7 @@ public class ApplicationManagerImpl implements ApplicationManager { applicationReleaseDTO = applicationStorageManager .uploadImageArtifacts(applicationReleaseDTO, applicationArtifact.getIconStream(), applicationArtifact.getBannerStream(), new ArrayList<>(screenshots.values())); - applicationReleaseEntities.add(applicationReleaseDTO); - applicationDTO.setApplicationReleases(applicationReleaseEntities); - return applicationDTO; + return applicationReleaseDTO; } @Override @@ -423,8 +456,6 @@ public class ApplicationManagerImpl implements ApplicationManager { DeviceType deviceType = null; try { - validateFilter(filter); - //set default values if (StringUtils.isEmpty(filter.getSortBy())) { filter.setSortBy("ASC"); @@ -438,6 +469,8 @@ public class ApplicationManagerImpl implements ApplicationManager { } ConnectionManagerUtil.openDBConnection(); + + validateFilter(filter); if (deviceType == null) { appDTOs = applicationDAO.getApplications(filter, 0, tenantId); } else { @@ -446,62 +479,46 @@ public class ApplicationManagerImpl implements ApplicationManager { for (ApplicationDTO app : appDTOs) { boolean isSearchingApp = true; - List tags = filter.getTags(); - List categories = filter.getAppCategories(); - List unrestrictedRoles = filter.getUnrestrictedRoles(); + List filteringTags = filter.getTags(); + List filteringCategories = filter.getAppCategories(); + List filteringUnrestrictedRoles = filter.getUnrestrictedRoles(); - if (lifecycleStateManager.getEndState().equals(app.getStatus())) { - isSearchingApp = false; - } - if (unrestrictedRoles != null && !unrestrictedRoles.isEmpty()) { - - if (!isRoleExists(unrestrictedRoles, userName)) { - String msg = "At least one filtering role is not assigned for the user: " + userName - + ". Hence user " + userName - + " Can't filter applications by giving these unrestriced role list"; - log.error(msg); - throw new BadRequestException(msg); - } + if (!lifecycleStateManager.getEndState().equals(app.getStatus())) { List appUnrestrictedRoles = visibilityDAO.getUnrestrictedRoles(app.getId(), tenantId); - boolean isUnrestrictedRoleExistForApp = false; - for (String role : unrestrictedRoles) { - if (appUnrestrictedRoles.contains(role)) { - isUnrestrictedRoleExistForApp = true; - break; + if ((appUnrestrictedRoles.isEmpty() || hasUserRole(appUnrestrictedRoles, userName)) && ( + filteringUnrestrictedRoles == null || filteringUnrestrictedRoles.isEmpty() + || hasAppUnrestrictedRole(appUnrestrictedRoles, filteringUnrestrictedRoles, + userName))) { + if (filteringCategories != null && !filteringCategories.isEmpty()) { + List appTagList = applicationDAO.getAppCategories(app.getId(), tenantId); + boolean isAppCategory = false; + for (String category : filteringCategories) { + if (appTagList.contains(category)) { + isAppCategory = true; + break; + } + } + if (!isAppCategory) { + isSearchingApp = false; + } } - } - if (!isUnrestrictedRoleExistForApp) { - isSearchingApp = false; - } - } - if (tags != null && !tags.isEmpty()) { - List appTagList = applicationDAO.getAppTags(app.getId(), tenantId); - boolean isTagExistForApp = false; - for (String tag : tags) { - if (appTagList.contains(tag)) { - isTagExistForApp = true; - break; + if (filteringTags != null && !filteringTags.isEmpty()) { + List appTagList = applicationDAO.getAppTags(app.getId(), tenantId); + boolean isAppTag = false; + for (String tag : filteringTags) { + if (appTagList.contains(tag)) { + isAppTag = true; + break; + } + } + if (!isAppTag) { + isSearchingApp = false; + } } - } - if (!isTagExistForApp) { - isSearchingApp = false; - } - } - if (categories != null && !categories.isEmpty()) { - List appTagList = applicationDAO.getAppCategories(app.getId(), tenantId); - boolean isCategoryExistForApp = false; - for (String category : categories) { - if (appTagList.contains(category)) { - isCategoryExistForApp = true; - break; + if (isSearchingApp) { + filteredApplications.add(app); } } - if (!isCategoryExistForApp) { - isSearchingApp = false; - } - } - if (isSearchingApp) { - filteredApplications.add(app); } } @@ -528,50 +545,56 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - @Override public ApplicationReleaseDTO createRelease(int applicationId, ApplicationReleaseDTO applicationRelease) + private boolean hasAppUnrestrictedRole(List appUnrestrictedRoles, List filteringUnrestrictedRoles, + String userName) throws BadRequestException, UserStoreException { + if (!haveAllUserRoles(filteringUnrestrictedRoles, userName)) { + String msg = + "At least one filtering role is not assigned for the user: " + userName + ". Hence user " + userName + + " Can't filter applications by giving these unrestriced role list"; + log.error(msg); + throw new BadRequestException(msg); + } + if (!appUnrestrictedRoles.isEmpty()) { + for (String role : filteringUnrestrictedRoles) { + if (appUnrestrictedRoles.contains(role)) { + return true; + } + } + } + return false; + } + + @Override + public ApplicationRelease createRelease(int applicationId, + ApplicationReleaseWrapper applicationReleaseWrapper, ApplicationArtifact applicationArtifact) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); - String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); -// validateAppReleasePayload(applicationRelease); + ApplicationRelease applicationRelease; if (log.isDebugEnabled()) { log.debug("ApplicationDTO release request is received for the application id: " + applicationId); } + try { ConnectionManagerUtil.beginDBTransaction(); - ApplicationDTO existingApplication = this.applicationDAO.getApplicationById(applicationId, tenantId); - if (existingApplication == null) { - throw new NotFoundException("Couldn't find application for the application Id: " + applicationId); + ApplicationDTO applicationDTO = this.applicationDAO.getApplicationById(applicationId, tenantId); + if (applicationDTO == null) { + String msg = "Couldn't find application for the application Id: " + applicationId; + log.error(msg); + throw new NotFoundException(msg); } + ApplicationReleaseDTO applicationReleaseDTO = addApplicationReleaseArtifacts(applicationDTO.getType(), + applicationDTO.getDeviceTypeName(), releaseWrapperToReleaseDTO(applicationReleaseWrapper), + applicationArtifact); + applicationReleaseDTO = addImageArtifacts(applicationReleaseDTO, applicationArtifact); - // todo check whether admin or app creator. - if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { - String msg = "You don't have permission to create application release for the application id: " - + applicationId - + ". In order to create ann new application realse, you should be either ADMIN user or the application created user."; - throw new ForbiddenException(msg); - } - if (!existingApplication.getUnrestrictedRoles().isEmpty() && !isRoleExists( - existingApplication.getUnrestrictedRoles(), userName)) { - String msg = "ApplicationDTO is visible to limited roles and those roles are not assigned to " + userName; - throw new ApplicationManagementException(msg); - } - if (this.applicationReleaseDAO - .verifyReleaseExistenceByHash(applicationId, applicationRelease.getAppHashValue(), tenantId)) { - throw new BadRequestException("ApplicationDTO release exists for the application Id: " + applicationId - + " and uploaded binary file"); - } - String packageName = this.applicationReleaseDAO.getPackageName(applicationId, tenantId); - if (packageName != null && !packageName.equals(applicationRelease.getPackageName())) { - throw new BadRequestException( - "Package name in the payload is different from the existing package name of other application" + - " releases."); - } - applicationRelease = this.applicationReleaseDAO - .createRelease(applicationRelease, existingApplication.getId(), tenantId); - LifecycleStateDTO lifecycleState = getLifecycleStateInstance(AppLifecycleState.CREATED.toString(), - AppLifecycleState.CREATED.toString()); + String initialstate = lifecycleStateManager.getInitialState(); + applicationReleaseDTO.setCurrentState(initialstate); + LifecycleStateDTO lifecycleState = getLifecycleStateInstance(initialstate, initialstate); this.lifecycleStateDAO - .addLifecycleState(lifecycleState, applicationId, applicationRelease.getUuid(), tenantId); + .addLifecycleState(lifecycleState, applicationId, applicationReleaseDTO.getUuid(), tenantId); + applicationReleaseDTO = this.applicationReleaseDAO + .createRelease(applicationReleaseDTO, applicationDTO.getId(), tenantId); + applicationRelease = releaseDtoToRelease(applicationReleaseDTO); ConnectionManagerUtil.commitDBTransaction(); return applicationRelease; } catch (TransactionManagementException e) { @@ -592,48 +615,65 @@ public class ApplicationManagerImpl implements ApplicationManager { ConnectionManagerUtil.rollbackDBTransaction(); throw new ApplicationManagementException( "Error occurred while adding new application release for application " + applicationId, e); - } catch (UserStoreException e) { + } catch (ResourceManagementException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "Error occurred whecn checking whether user is admin user or not. ApplicationDTO release: " - + applicationId, e); + String msg = + "Error occurred while uploading application release artifacts. Application ID: " + applicationId; + throw new ApplicationManagementException(msg, e); } finally { ConnectionManagerUtil.closeDBConnection(); } } - @Override public ApplicationDTO getApplicationById(int appId, String state) throws ApplicationManagementException { + @Override + public Application getApplicationById(int appId, String state) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - ApplicationDTO application; - boolean isAppAllowed = false; - List applicationReleases; + ApplicationDTO applicationDTO; + List filteredApplicationReleaseDTOs; + boolean isVisibleApp = false; try { ConnectionManagerUtil.openDBConnection(); - application = this.applicationDAO.getApplicationById(appId, tenantId); - if (application == null) { + applicationDTO = this.applicationDAO.getApplicationById(appId, tenantId); + if (applicationDTO == null) { throw new NotFoundException("Couldn't find an application for application Id: " + appId); } + + filteredApplicationReleaseDTOs = applicationDTO.getApplicationReleaseDTOs().stream() + .filter(applicationReleaseDTO -> applicationReleaseDTO.getCurrentState().equals(state)) + .collect(Collectors.toList()); + applicationDTO.setApplicationReleaseDTOs(filteredApplicationReleaseDTOs); + if (applicationDTO.getApplicationReleaseDTOs().isEmpty()){ + return null; + } + + List tags = this.applicationDAO.getAppTags(appId, tenantId); + List categories = this.applicationDAO.getAppCategories(appId, tenantId); + applicationDTO.setTags(tags); + //todo when support to add multiple categories this has to be changed + if (!categories.isEmpty()){ + applicationDTO.setAppCategory(categories.get(0)); + } if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { - applicationReleases = getReleases(application, state); - application.setApplicationReleases(applicationReleases); - return application; + return appDtoToAppResponse(applicationDTO); } - if (!application.getUnrestrictedRoles().isEmpty()) { - if (isRoleExists(application.getUnrestrictedRoles(), userName)) { - isAppAllowed = true; + List unrestrictedRoles = this.visibilityDAO.getUnrestrictedRoles(appId, tenantId); + if (!unrestrictedRoles.isEmpty()) { + if (hasUserRole(unrestrictedRoles, userName)) { + isVisibleApp = true; } } else { - isAppAllowed = true; + isVisibleApp = true; } - if (!isAppAllowed) { - return null; + if (!isVisibleApp) { + String msg = "You are trying to access visibility restricted application. You don't have required " + + "roles to view this application,"; + log.error(msg); + throw new ForbiddenException(msg); } - applicationReleases = getReleases(application, state); - application.setApplicationReleases(applicationReleases); - return application; + return appDtoToAppResponse(applicationDTO); } catch (UserStoreException e) { throw new ApplicationManagementException( "User-store exception while getting application with the application id " + appId); @@ -657,12 +697,12 @@ public class ApplicationManagerImpl implements ApplicationManager { } if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { applicationReleases = getReleases(application, state); - application.setApplicationReleases(applicationReleases); + application.setApplicationReleaseDTOs(applicationReleases); return application; } if (!application.getUnrestrictedRoles().isEmpty()) { - if (isRoleExists(application.getUnrestrictedRoles(), userName)) { + if (hasUserRole(application.getUnrestrictedRoles(), userName)) { isAppAllowed = true; } } else { @@ -673,7 +713,7 @@ public class ApplicationManagerImpl implements ApplicationManager { return null; } applicationReleases = getReleases(application, state); - application.setApplicationReleases(applicationReleases); + application.setApplicationReleaseDTOs(applicationReleases); return application; } catch (UserStoreException e) { throw new ApplicationManagementException( @@ -683,7 +723,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } } - private boolean isRoleExists(Collection unrestrictedRoleList, String userName) throws UserStoreException { + private boolean hasUserRole(Collection unrestrictedRoleList, String userName) throws UserStoreException { String[] roleList; roleList = getRolesOfUser(userName); for (String unrestrictedRole : unrestrictedRoleList) { @@ -696,6 +736,20 @@ public class ApplicationManagerImpl implements ApplicationManager { return false; } + private boolean haveAllUserRoles(Collection unrestrictedRoleList, String userName) + throws UserStoreException { + String[] roleList; + roleList = getRolesOfUser(userName); + for (String unrestrictedRole : unrestrictedRoleList) { + for (String role : roleList) { + if (!unrestrictedRole.equals(role)) { + return false; + } + } + } + return true; + } + private boolean isValidRestrictedRole(Collection unrestrictedRoleList) throws UserStoreException { List roleList = new ArrayList<>(Arrays.asList(getRoleNames())); return roleList.containsAll(unrestrictedRoleList); @@ -737,12 +791,12 @@ public class ApplicationManagerImpl implements ApplicationManager { application = this.applicationDAO.getApplication(appName, appType, tenantId); if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { applicationReleases = getReleases(application, null); - application.setApplicationReleases(applicationReleases); + application.setApplicationReleaseDTOs(applicationReleases); return application; } if (!application.getUnrestrictedRoles().isEmpty()) { - if (isRoleExists(application.getUnrestrictedRoles(), userName)) { + if (hasUserRole(application.getUnrestrictedRoles(), userName)) { isAppAllowed = true; } } else { @@ -754,7 +808,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } applicationReleases = getReleases(application, null); - application.setApplicationReleases(applicationReleases); + application.setApplicationReleaseDTOs(applicationReleases); return application; } catch (UserStoreException e) { throw new ApplicationManagementException( @@ -772,7 +826,7 @@ public class ApplicationManagerImpl implements ApplicationManager { ConnectionManagerUtil.openDBConnection(); application = this.applicationDAO.getApplicationByRelease(appReleaseUUID, tenantId); - if (application.getUnrestrictedRoles().isEmpty() || isRoleExists(application.getUnrestrictedRoles(), + if (application.getUnrestrictedRoles().isEmpty() || hasUserRole(application.getUnrestrictedRoles(), userName)) { return application; } @@ -855,7 +909,7 @@ public class ApplicationManagerImpl implements ApplicationManager { } if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION) && !application - .getUnrestrictedRoles().isEmpty() && isRoleExists(application.getUnrestrictedRoles(), userName)) { + .getUnrestrictedRoles().isEmpty() && hasUserRole(application.getUnrestrictedRoles(), userName)) { throw new ForbiddenException( "You don't have permission to delete this application. In order to delete an application you " + "need to have required permission. ApplicationDTO ID: " + applicationId); @@ -976,7 +1030,7 @@ public class ApplicationManagerImpl implements ApplicationManager { throw new NotFoundException("Couldn't find an application for application ID: " + applicationId); } if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION) && !application - .getUnrestrictedRoles().isEmpty() && isRoleExists(application.getUnrestrictedRoles(), userName)) { + .getUnrestrictedRoles().isEmpty() && hasUserRole(application.getUnrestrictedRoles(), userName)) { throw new ForbiddenException( "You don't have permission for deleting application release. ApplicationDTO id: " + applicationId + " and release UUID: " + releaseUuid); @@ -1082,77 +1136,76 @@ public class ApplicationManagerImpl implements ApplicationManager { return false; } - //todo check whether user is whether admin user or application owner, otherwise throw an exception @Override - public void updateApplicationImageArtifact(int appId, String uuid, InputStream iconFileStream, - InputStream bannerFileStream, List attachments) throws ApplicationManagementException { + //todo with this implementation user has to provide all image artifacts in order to update one image artifact as + // well. Therefore enhance this later. + public void updateApplicationImageArtifact(String uuid, ApplicationArtifact applicationArtifact) + throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager(); - ApplicationReleaseDTO applicationRelease; + ApplicationReleaseDTO applicationReleaseDTO; try { - if (appId <= 0) { - throw new ValidationException( - "ApplicationDTO id could,t be a negative integer. Hence please add valid application id."); - } + ConnectionManagerUtil.beginDBTransaction(); - applicationRelease = this.applicationReleaseDAO.getReleaseByIds(appId, uuid, tenantId); - if (applicationRelease == null) { - throw new NotFoundException( - "Doesn't exist a application release for application ID: " + appId + "and application UUID: " - + uuid); - } - LifecycleStateDTO lifecycleState = this.lifecycleStateDAO - .getLatestLifeCycleState(appId, applicationRelease.getUuid()); - if (AppLifecycleState.PUBLISHED.toString().equals(lifecycleState.getCurrentState()) - || AppLifecycleState.DEPRECATED.toString().equals(lifecycleState.getCurrentState())) { - throw new ForbiddenException("Can't Update the application release in PUBLISHED or DEPRECATED state. " - + "Hence please demote the application and update the application release"); - } - applicationRelease = applicationStorageManager - .updateImageArtifacts(applicationRelease, iconFileStream, bannerFileStream, attachments); - applicationRelease = this.applicationReleaseDAO.updateRelease(appId, applicationRelease, tenantId); - if (applicationRelease == null) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "ApplicationDTO release updating count is 0. ApplicationDTO id: " + appId - + " ApplicationDTO release UUID: " + uuid); + applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId); + if (applicationReleaseDTO == null) { + String msg = "Application release image artifact uploading is failed. Doesn't exist a application " + + "release for application ID: application UUID: " + uuid; + log.error(msg); + throw new NotFoundException(msg); + } + + String currentState = applicationReleaseDTO.getCurrentState(); + if (!lifecycleStateManager.isUpdatableState(currentState)){ + throw new ForbiddenException( + "Can't Update the application release. Application release is in " + currentState + + " and it is not an release updatable state. Hence please move the application release" + + " into updatable state and retry the operation."); + } + applicationStorageManager.deleteImageArtifacts(applicationReleaseDTO); + applicationReleaseDTO = this.applicationReleaseDAO + .updateRelease(addImageArtifacts(applicationReleaseDTO, applicationArtifact), tenantId); + if (applicationReleaseDTO == null) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "ApplicationDTO release updating count is 0. ApplicationDTO release UUID is " + uuid; + log.error(msg); + throw new ApplicationManagementException(msg); } ConnectionManagerUtil.commitDBTransaction(); } catch (DBConnectionException e) { - throw new ApplicationManagementException( - "Error occured when getting DB connection to update image artifacts of the application, appid: " - + appId + " and uuid " + uuid + ".", e); + String msg = + "Error occured when getting DB connection to update image artifacts of the application release of haveing uuid " + + uuid + "."; + log.error(msg); + throw new ApplicationManagementException(msg, e); } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "Error occured while getting application release data for updating image artifacts of the application, appid: " - + appId + " and uuid " + uuid + ".", e); - } catch (LifeCycleManagementDAOException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "Error occured while getting latest lifecycle state for updating image artifacts of the application, appid: " - + appId + " and uuid " + uuid + ".", e); + String msg = + "Error occured while getting application release data for updating image artifacts of the application release uuid " + + uuid + "."; + log.error(msg); + throw new ApplicationManagementException(msg, e); } catch (ResourceManagementException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "Error occured while updating image artifacts of the application, appid: " + appId + " and uuid " - + uuid + " to the system.", e); + String msg = "Error occured while updating image artifacts of the application release uuid " + uuid + "."; + log.error(msg); + throw new ApplicationManagementException(msg , e); } finally { ConnectionManagerUtil.closeDBConnection(); } } - //todo check whether package names are same @Override - public void updateApplicationArtifact(int appId, String deviceType, String uuid, InputStream binaryFile) - throws ApplicationManagementException { + public void updateApplicationArtifact(String deviceType, String appType, String uuid, + ApplicationArtifact applicationArtifact) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager(); - ApplicationReleaseDTO applicationRelease; + boolean isValidDeviceType = false; + List deviceTypes; try { - boolean isValidDeviceType = false; - List deviceTypes = Util.getDeviceManagementService().getDeviceTypes(); + deviceTypes = Util.getDeviceManagementService().getDeviceTypes(); + for (DeviceType dt : deviceTypes) { if (dt.getName().equals(deviceType)) { isValidDeviceType = true; @@ -1160,59 +1213,64 @@ public class ApplicationManagerImpl implements ApplicationManager { } } if (!isValidDeviceType) { - throw new ValidationException( - "Invalid request to update application release artifact, invalid application type: " - + deviceType + " for ApplicationDTO id: " + appId + " application release uuid: " + uuid); - } - if (appId <= 0) { - throw new ValidationException( - "ApplicationDTO id could,t be a negative integer. Hence please add valid application id. application type: " - + deviceType + " ApplicationDTO id: " + appId + " UUID: " + uuid); + String msg = "Invalid request to update application release artifact, invalid application type: " + + deviceType + " for application release uuid: " + uuid; + log.error(msg); + throw new BadRequestException(msg); } + } catch (DeviceManagementException e) { + String msg = "Error occured while getting supported device types in IoTS"; + log.error(msg); + throw new ApplicationManagementException(msg, e); + } + try { ConnectionManagerUtil.beginDBTransaction(); - ApplicationDTO application = this.applicationDAO.getApplicationById(appId, tenantId); - if (application == null) { - throw new NotFoundException("Doesn't exist a application for the application ID: " + appId); - } - applicationRelease = this.applicationReleaseDAO.getReleaseByIds(appId, uuid, tenantId); - if (applicationRelease == null) { - throw new NotFoundException( - "Doesn't exist a application release for application ID: " + appId + "and application UUID: " - + uuid); + ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId); + if (applicationReleaseDTO == null) { + String msg = "Couldn't found an application release for UUID: " + uuid; + log.error(msg); + throw new NotFoundException(msg); } - applicationRelease = applicationStorageManager - .updateReleaseArtifacts(applicationRelease, application.getType(), application.getDeviceTypeName(), - binaryFile); - applicationRelease = this.applicationReleaseDAO.updateRelease(appId, applicationRelease, tenantId); - if (applicationRelease == null) { + + String deletingAppHashValue = applicationReleaseDTO.getAppHashValue(); + applicationReleaseDTO = addApplicationReleaseArtifacts(appType, deviceType, applicationReleaseDTO, + applicationArtifact); + applicationStorageManager.copyImageArtifactsAndDeleteInstaller(deletingAppHashValue, applicationReleaseDTO); + applicationReleaseDTO = this.applicationReleaseDAO.updateRelease(applicationReleaseDTO, tenantId); + if (applicationReleaseDTO == null) { ConnectionManagerUtil.rollbackDBTransaction(); throw new ApplicationManagementException( - "ApplicationDTO release updating count is 0. ApplicationDTO id: " + appId - + " ApplicationDTO release UUID: " + uuid); + "ApplicationDTO release updating count is 0. ApplicationDTO release UUID: " + uuid); } ConnectionManagerUtil.commitDBTransaction(); } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException("Error occured while getting/updating APPM DB.", e); + String msg = "Error occured while getting/updating APPM DB for updating application Installer."; + log.error(msg); + throw new ApplicationManagementException(msg, e); } catch (TransactionManagementException e) { - throw new ApplicationManagementException( - "Error occured while starting the transaction to update application release artifact of the application, appid: " - + appId + " and uuid " + uuid + ".", e); - } catch (RequestValidatingException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException("Error occured while updating application artifact.", e); - } catch (DeviceManagementException e) { - throw new ApplicationManagementException("Error occured while getting supported device types in IoTS", e); + String msg = + "Error occured while starting the transaction to update application release artifact of the application uuid " + + uuid + "."; + log.error(msg); + throw new ApplicationManagementException(msg, e); } catch (DBConnectionException e) { - throw new ApplicationManagementException( - "Error occured when getting DB connection to update application release artifact of the application, appid: " - + appId + " and uuid " + uuid + ".", e); + String msg = + "Error occured when getting DB connection to update application release artifact of the application release uuid " + + uuid + "."; + log.error(msg); + throw new ApplicationManagementException(msg, e); } catch (ApplicationStorageManagementException e) { ConnectionManagerUtil.rollbackDBTransaction(); throw new ApplicationManagementException("In order to update the artifact, couldn't find it in the system", e); + } catch (ResourceManagementException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + String msg = "Error occured when updating application installer."; + log.error(msg); + throw new ApplicationManagementException(msg, e); } finally { ConnectionManagerUtil.closeDBConnection(); } @@ -1234,7 +1292,7 @@ public class ApplicationManagerImpl implements ApplicationManager { // unRestrictedApplications.add(application); // } else { // try { -// if (isRoleExists(application.getUnrestrictedRoles(), userName)) { +// if (hasUserRole(application.getUnrestrictedRoles(), userName)) { // unRestrictedApplications.add(application); // } // } catch (UserStoreException e) { @@ -1354,82 +1412,137 @@ public class ApplicationManagerImpl implements ApplicationManager { } @Override - public ApplicationDTO updateApplication(int applicationId, ApplicationDTO application) + public void updateApplication(int applicationId, ApplicationWrapper applicationWrapper) throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - ApplicationDTO existingApplication; - boolean isExistingAppRestricted = false; - List addingRoleList; - List removingRoleList; - List addingTags; - List removingTags; + ApplicationDTO applicationDTO; try { ConnectionManagerUtil.beginDBTransaction(); - existingApplication = this.applicationDAO.getApplicationById(applicationId, tenantId); - if (existingApplication == null) { + applicationDTO = this.applicationDAO.getApplicationById(applicationId, tenantId); + if (applicationDTO == null) { ConnectionManagerUtil.rollbackDBTransaction(); - throw new NotFoundException("Tried to update ApplicationDTO which is not in the publisher, " - + "Please verify application details"); - } - if (!existingApplication.getUnrestrictedRoles().isEmpty()) { - isExistingAppRestricted = true; - } - - if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION) && !( - isExistingAppRestricted && isRoleExists(existingApplication.getUnrestrictedRoles(), userName))) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ForbiddenException("You are not authorized user to update application"); + String msg = "Tried to update Application which is not in the publisher. Please verify " + + "application details"; + log.error(msg); + throw new NotFoundException(msg); } - if (!existingApplication.getType().equals(application.getType())) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException("You are trying to change the application type and it is not " + if (!StringUtils.isEmpty(applicationWrapper.getType()) && !applicationDTO.getType() + .equals(applicationWrapper.getType())) { + String msg = "You are trying to change the application type and it is not " + "possible after you create an application. Therefore please remove this application and " - + "publish new application with type: " + application.getType()); + + "publish new application with type: " + applicationWrapper.getType(); + log.error(msg); + throw new BadRequestException(msg); } - if (!existingApplication.getSubType().equals(application.getSubType())) { - if (ApplicationSubscriptionType.PAID.toString().equals(existingApplication.getSubType()) && ( - !"".equals(application.getPaymentCurrency()) || application.getPaymentCurrency() != null)) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException("If you are going to change Non-Free app as Free app, " - + "currency attribute in the application updating payload should be null or \"\""); - } else if (ApplicationSubscriptionType.FREE.toString().equals(existingApplication.getSubType()) && ( - application.getPaymentCurrency() == null || "".equals(application.getPaymentCurrency()))) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException("If you are going to change Free app as Non-Free app, " - + "currency attribute in the application payload should not be null or \"\""); + if (!StringUtils.isEmpty(applicationWrapper.getDeviceType()) && !applicationDTO.getDeviceTypeName() + .equals(applicationWrapper.getDeviceType())) { + String msg = "You are trying to change the compatible device type of the application type and it is not " + + "possible after you create an application for device type. " + + applicationWrapper.getDeviceType() + "Therefore please remove this application and publish " + + "new application with device type: " + applicationWrapper.getDeviceType(); + log.error(msg); + throw new BadRequestException(msg); + } + if (!StringUtils.isEmpty(applicationWrapper.getSubType()) && !applicationDTO.getSubType() + .equals(applicationWrapper.getSubType())) { + if (!ApplicationSubscriptionType.PAID.toString().equals(applicationWrapper.getSubType()) + && !ApplicationSubscriptionType.FREE.toString().equals(applicationWrapper.getSubType())) { + String msg = "Invalid application subscription type is found with application updating request " + + applicationWrapper.getSubType(); + log.error(msg); + throw new BadRequestException(msg); + + } else if (ApplicationSubscriptionType.FREE.toString().equals(applicationWrapper.getSubType()) && !StringUtils + .isEmpty(applicationWrapper.getPaymentCurrency())) { + String msg = "If you are going to change Non-Free app as Free app, " + + "currency attribute in the application updating payload should be null or \"\""; + log.error(msg); + throw new ApplicationManagementException(msg); + } else if (ApplicationSubscriptionType.PAID.toString().equals(applicationWrapper.getSubType()) + && StringUtils.isEmpty(applicationWrapper.getPaymentCurrency()) ){ + String msg = "If you are going to change Free app as Non-Free app, " + + "currency attribute in the application payload should not be null or \"\""; + log.error(msg); + throw new ApplicationManagementException(msg); + } + + applicationDTO.setSubType(applicationWrapper.getSubType()); + applicationDTO.setPaymentCurrency(applicationWrapper.getPaymentCurrency()); + } + if (!StringUtils.isEmpty(applicationWrapper.getName())){ + Filter filter = new Filter(); + filter.setFullMatch(true); + filter.setAppName(applicationWrapper.getName().trim()); + filter.setOffset(0); + filter.setLimit(1); + + List applicationList = applicationDAO + .getApplications(filter, applicationDTO.getDeviceTypeId(), tenantId); + if (!applicationList.isEmpty()) { + String msg = "Already an application registered with same name " + applicationWrapper.getName() + + ". Hence you can't update the application name from " + applicationDTO.getName() + " to " + + applicationWrapper.getName(); + log.error(msg); + throw new BadRequestException(msg); } + applicationDTO.setName(applicationWrapper.getName()); } - if (isExistingAppRestricted && application.getUnrestrictedRoles().isEmpty()) { - visibilityDAO.deleteUnrestrictedRoles(existingApplication.getUnrestrictedRoles(), application.getId(), - tenantId); - } else if (!isExistingAppRestricted && !application.getUnrestrictedRoles().isEmpty()) { - visibilityDAO.addUnrestrictedRoles(application.getUnrestrictedRoles(), application.getId(), tenantId); - } else if (isExistingAppRestricted && !application.getUnrestrictedRoles().isEmpty()) { - addingRoleList = getDifference(application.getUnrestrictedRoles(), - existingApplication.getUnrestrictedRoles()); - removingRoleList = getDifference(existingApplication.getUnrestrictedRoles(), - application.getUnrestrictedRoles()); - if (!addingRoleList.isEmpty()) { - visibilityDAO.addUnrestrictedRoles(addingRoleList, application.getId(), tenantId); + if (!StringUtils.isEmpty(applicationWrapper.getDescription())){ + applicationDTO.setDescription(applicationWrapper.getDescription()); + } + + List appUnrestrictedRoles = this.visibilityDAO.getUnrestrictedRoles(applicationId, tenantId); + List appCategories = this.applicationDAO.getAppCategories(applicationId, tenantId); + + boolean isExistingAppRestricted = !appUnrestrictedRoles.isEmpty(); + boolean isUpdatingAppRestricted = !applicationWrapper.getUnrestrictedRoles().isEmpty(); + + if (isExistingAppRestricted && !isUpdatingAppRestricted) { + visibilityDAO.deleteUnrestrictedRoles(appUnrestrictedRoles, applicationId, tenantId); + } else if (isUpdatingAppRestricted) { + if (!hasUserRole(applicationWrapper.getUnrestrictedRoles(), userName)) { + String msg = + "You are trying to restrict the visibility of visible application.But you are trying to " + + "restrict the visibility to roles that there isn't at least one role is assigned " + + "to user: " + userName + ". Therefore, it is not allowed and you should have " + + "added at least one role that assigned to " + userName + " user into " + + "restricting role set."; + log.error(msg); + throw new BadRequestException(msg); } - if (!removingRoleList.isEmpty()) { - visibilityDAO.deleteUnrestrictedRoles(removingRoleList, application.getId(), tenantId); + + if (!isExistingAppRestricted) { + visibilityDAO + .addUnrestrictedRoles(applicationWrapper.getUnrestrictedRoles(), applicationId, tenantId); + } else { + List addingRoleList = getDifference(applicationWrapper.getUnrestrictedRoles(), + applicationDTO.getUnrestrictedRoles()); + List removingRoleList = getDifference(applicationDTO.getUnrestrictedRoles(), + applicationWrapper.getUnrestrictedRoles()); + if (!addingRoleList.isEmpty()) { + visibilityDAO.addUnrestrictedRoles(addingRoleList, applicationId, tenantId); + } + if (!removingRoleList.isEmpty()) { + visibilityDAO.deleteUnrestrictedRoles(removingRoleList, applicationId, tenantId); + } } } + applicationDTO.setUnrestrictedRoles(applicationWrapper.getUnrestrictedRoles()); - addingTags = getDifference(existingApplication.getTags(), application.getTags()); - removingTags = getDifference(application.getTags(), existingApplication.getTags()); - if (!addingTags.isEmpty()) { + List appTags = this.applicationDAO.getAppTags(applicationId, tenantId); + List addingTagList = getDifference(appTags, applicationWrapper.getTags()); + List removingTagList = getDifference(applicationWrapper.getTags(), appTags); + if (!addingTagList.isEmpty()) { // applicationDAO.addTags(addingTags, application.getId(), tenantId); } - if (!removingTags.isEmpty()) { - applicationDAO.deleteTags(removingTags, application.getId(), tenantId); + if (!removingTagList.isEmpty()) { + applicationDAO.deleteTags(removingTagList, applicationId, tenantId); } - return applicationDAO.editApplication(application, tenantId); + applicationDAO.editApplication(applicationDTO, tenantId); } catch (UserStoreException e) { ConnectionManagerUtil.rollbackDBTransaction(); throw new ApplicationManagementException( @@ -1601,7 +1714,7 @@ public class ApplicationManagerImpl implements ApplicationManager { String applicationReleaseCreatedUser = lifecycleStateDAO .getAppReleaseCreatedUsername(applicationId, releaseUuid, tenantId); - if (!isAdminUser && !(!unrestrictedRoles.isEmpty() && isRoleExists(unrestrictedRoles, userName)) + if (!isAdminUser && !(!unrestrictedRoles.isEmpty() && hasUserRole(unrestrictedRoles, userName)) && !userName.equals(applicationReleaseCreatedUser)) { ConnectionManagerUtil.rollbackDBTransaction(); throw new ForbiddenException("You are not authorized user to update application"); @@ -1618,11 +1731,11 @@ public class ApplicationManagerImpl implements ApplicationManager { + " State"); } - release = applicationStorageManager - .updateImageArtifacts(release, iconFileStream, bannerFileStream, attachments); - release = applicationStorageManager - .updateReleaseArtifacts(release, app.getType(), deviceType, binaryFileStram); - return applicationReleaseDAO.updateRelease(applicationId, release, tenantId) != null; +// release = applicationStorageManager +// .deleteImageArtifacts(release, iconFileStream, bannerFileStream, attachments); +// release = applicationStorageManager +// .copyImageArtifactsAndDeleteInstaller(release, app.getType(), deviceType, binaryFileStram); + return applicationReleaseDAO.updateRelease(release, tenantId) != null; } catch (DeviceManagementException e) { throw new ApplicationManagementException("Error occured when validating the device type " + deviceType, e); } catch (UserStoreException e) { @@ -1639,31 +1752,32 @@ public class ApplicationManagerImpl implements ApplicationManager { throw new ApplicationManagementException( "Error occured when updating ApplicationDTO release. ApplicationDTO ID " + applicationId + " ApplicationDTO Release UUID: " + releaseUuid, e); - } catch (ApplicationStorageManagementException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "Error occured when updating application release artifact. ApplicationDTO ID " + applicationId - + " ApplicationDTO release UUID: " + releaseUuid, e); - } catch (ResourceManagementException e) { - // updating images - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "Error occured when updating image artifact of the application release. ApplicationDTO ID: " - + applicationId + " ApplicationDTO release UUID: " + releaseUuid, e); - } catch (RequestValidatingException e) { - ConnectionManagerUtil.rollbackDBTransaction(); - throw new ApplicationManagementException( - "Error occured when validating application release artifact for device type " + deviceType - + " And application type " + app.getType() + ". Applicationn ID: " + applicationId - + " ApplicationDTO release UUID: " + releaseUuid); } +// catch (ApplicationStorageManagementException e) { +// ConnectionManagerUtil.rollbackDBTransaction(); +// throw new ApplicationManagementException( +// "Error occured when updating application release artifact. ApplicationDTO ID " + applicationId +// + " ApplicationDTO release UUID: " + releaseUuid, e); +// } +// catch (ResourceManagementException e) { +// // updating images +// ConnectionManagerUtil.rollbackDBTransaction(); +// throw new ApplicationManagementException( +// "Error occured when updating image artifact of the application release. ApplicationDTO ID: " +// + applicationId + " ApplicationDTO release UUID: " + releaseUuid, e); +// } catch (RequestValidatingException e) { +// ConnectionManagerUtil.rollbackDBTransaction(); +// throw new ApplicationManagementException( +// "Error occured when validating application release artifact for device type " + deviceType +// + " And application type " + app.getType() + ". Applicationn ID: " + applicationId +// + " ApplicationDTO release UUID: " + releaseUuid); +// } } @Override public void validateAppCreatingRequest(ApplicationWrapper applicationWrapper) throws RequestValidatingException { - boolean isValidApplicationType; String applicationType = applicationWrapper.getType(); if (StringUtils.isEmpty(applicationWrapper.getName())) { @@ -1687,13 +1801,6 @@ public class ApplicationManagerImpl implements ApplicationManager { throw new RequestValidatingException(msg); } - isValidApplicationType = isValidAppType(applicationWrapper.getType()); - if (!isValidApplicationType) { - String msg = "App Type contains in the application creating payload doesn't match with supported app types."; - log.error(msg); - throw new RequestValidatingException(msg); - } - List applicationReleaseWrappers; applicationReleaseWrappers = applicationWrapper.getApplicationReleaseWrappers(); @@ -1713,6 +1820,12 @@ public class ApplicationManagerImpl implements ApplicationManager { public void validateReleaseCreatingRequest(ApplicationReleaseWrapper applicationReleaseWrapper, String applicationType) throws RequestValidatingException { + if (applicationReleaseWrapper == null){ + String msg = "Application Release shouldn't be null."; + log.error(msg); + throw new RequestValidatingException(msg); + } + if (ApplicationType.WEB_CLIP.toString().equals(applicationType)) { UrlValidator urlValidator = new UrlValidator(); if (StringUtils @@ -1736,8 +1849,8 @@ public class ApplicationManagerImpl implements ApplicationManager { @Override - public void isValidAttachmentSet(Attachment binaryFile, Attachment iconFile, Attachment bannerFile, - List attachmentList, String applicationType) throws RequestValidatingException { + public void validateImageArtifacts(Attachment iconFile, Attachment bannerFile, + List attachmentList) throws RequestValidatingException { if (iconFile == null) { String msg = "Icon file is not found with the application release creating request."; log.error(msg); @@ -1753,8 +1866,18 @@ public class ApplicationManagerImpl implements ApplicationManager { log.error(msg); throw new RequestValidatingException(msg); } - if (StringUtils.isEmpty(applicationType)){ - String msg = "Application type is empty and it cannot be empty"; + } + + @Override + public void validateBinaryArtifact(Attachment binaryFile, String applicationType) throws RequestValidatingException { + + if (StringUtils.isEmpty(applicationType)) { + String msg = "Application type can't be empty."; + log.error(msg); + throw new RequestValidatingException(msg); + } + if (!isValidAppType(applicationType)) { + String msg = "App Type contains in the application creating payload doesn't match with supported app types."; log.error(msg); throw new RequestValidatingException(msg); } @@ -1784,7 +1907,7 @@ public class ApplicationManagerImpl implements ApplicationManager { applicationDTO.setDeviceTypeName(deviceType.getName()); List applicationReleaseEntities = applicationWrapper.getApplicationReleaseWrappers() .stream().map(this::releaseWrapperToReleaseDTO).collect(Collectors.toList()); - applicationDTO.setApplicationReleases(applicationReleaseEntities); + applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); return applicationDTO; } @@ -1813,7 +1936,7 @@ public class ApplicationManagerImpl implements ApplicationManager { application.setTags(applicationDTO.getTags()); application.setUnrestrictedRoles(applicationDTO.getUnrestrictedRoles()); application.setDeviceType(applicationDTO.getDeviceTypeName()); - List applicationReleases = applicationDTO.getApplicationReleases() + List applicationReleases = applicationDTO.getApplicationReleaseDTOs() .stream().map(this::releaseDtoToRelease).collect(Collectors.toList()); application.setApplicationReleases(applicationReleases); return application; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationStorageManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationStorageManagerImpl.java index 1961f78e91c..b695405bc10 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationStorageManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationStorageManagerImpl.java @@ -24,18 +24,14 @@ import com.dd.plist.NSString; import com.dd.plist.PropertyListFormatException; import com.dd.plist.PropertyListParser; import net.dongliu.apk.parser.bean.ApkMeta; -import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; 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 org.wso2.carbon.device.application.mgt.common.ApplicationInstaller; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; -import org.wso2.carbon.device.application.mgt.common.ApplicationType; import org.wso2.carbon.device.application.mgt.common.DeviceTypes; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; -import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; import org.wso2.carbon.device.application.mgt.core.exception.ParsingException; @@ -46,6 +42,7 @@ import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.*; +import java.nio.file.Files; import java.text.ParseException; import java.util.HashMap; import java.util.List; @@ -54,7 +51,7 @@ import java.util.Objects; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.deleteDir; +import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.delete; import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.saveFile; /** @@ -88,7 +85,6 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager String scStoredLocation = null; try { - // todo handle WEB CLIP and save data in different folder (uuid) artifactDirectoryPath = storagePath + applicationRelease.getAppHashValue(); StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath); iconStoredLocation = artifactDirectoryPath + File.separator + applicationRelease.getIconName(); @@ -135,43 +131,42 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager @Override - public ApplicationReleaseDTO updateImageArtifacts(ApplicationReleaseDTO applicationRelease, InputStream - iconFileStream, InputStream bannerFileStream, List screenShotStreams) + public void deleteImageArtifacts(ApplicationReleaseDTO applicationReleaseDTO) throws ResourceManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); try { - if (iconFileStream != null) { - deleteApplicationReleaseArtifacts(applicationRelease.getIconName()); + String iconName = applicationReleaseDTO.getIconName(); + String bannerName = applicationReleaseDTO.getBannerName(); + String sc1 = applicationReleaseDTO.getScreenshotName1(); + String sc2 = applicationReleaseDTO.getScreenshotName2(); + String sc3 = applicationReleaseDTO.getScreenshotName3(); + String hashValue = applicationReleaseDTO.getAppHashValue(); + if (iconName != null) { + deleteApplicationReleaseArtifacts( + storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + iconName); } - if (bannerFileStream != null) { - deleteApplicationReleaseArtifacts(applicationRelease.getBannerName()); + if (bannerName != null) { + deleteApplicationReleaseArtifacts( + storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + bannerName); } - if (!screenShotStreams.isEmpty()) { - if (screenShotStreams.size() > screenShotMaxCount) { - throw new ApplicationStorageManagementException("Maximum limit for the screen-shot exceeds"); - } - int count = 1; - while (count < screenShotStreams.size()) { - if (count == 1) { - deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotName1()); - } - if (count == 2) { - deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotName2()); - } - if (count == 3) { - deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotName3()); - } - count++; - } + + if (sc1 != null) { + deleteApplicationReleaseArtifacts( + storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc1); + } + if (sc2 != null) { + deleteApplicationReleaseArtifacts( + storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc2); + } + if (sc3 != null) { + deleteApplicationReleaseArtifacts( + storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc3); } - applicationRelease = uploadImageArtifacts(applicationRelease, iconFileStream, bannerFileStream, - screenShotStreams); - return applicationRelease; } catch (ApplicationStorageManagementException e) { throw new ApplicationStorageManagementException("ApplicationDTO Storage exception while trying to" - + " update the screen-shot count for the application Release " + applicationRelease.getUuid() + + + " update the screen-shot count for the application Release " + applicationReleaseDTO.getUuid() + " for the tenant " + tenantId, e); } } @@ -208,22 +203,13 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager String deviceType, InputStream binaryFile) throws ResourceManagementException { try { String artifactDirectoryPath; - String md5OfApp; String artifactPath; byte [] content = IOUtils.toByteArray(binaryFile); - md5OfApp = getMD5(new ByteArrayInputStream(content)); - if (md5OfApp == null) { - String msg = "Error occurred while md5sum value retrieving process: application UUID " - + applicationReleaseDTO.getUuid(); - log.error(msg); - throw new ApplicationStorageManagementException(msg); - } - artifactDirectoryPath = storagePath + md5OfApp; + artifactDirectoryPath = storagePath + applicationReleaseDTO.getAppHashValue(); StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath); artifactPath = artifactDirectoryPath + File.separator + applicationReleaseDTO.getInstallerName(); saveFile(new ByteArrayInputStream(content), artifactPath); - applicationReleaseDTO.setAppHashValue(md5OfApp); } catch (IOException e) { String msg = "IO Exception while saving the release artifacts in the server for the application UUID " + applicationReleaseDTO.getUuid(); @@ -234,27 +220,53 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager } @Override - public ApplicationReleaseDTO updateReleaseArtifacts(ApplicationReleaseDTO applicationRelease, - String appType, String deviceType, InputStream binaryFile) throws ApplicationStorageManagementException { + public void copyImageArtifactsAndDeleteInstaller(String deletingAppHashValue, + ApplicationReleaseDTO applicationReleaseDTO) throws ApplicationStorageManagementException { try { - deleteApplicationReleaseArtifacts(applicationRelease.getInstallerName()); - applicationRelease = uploadReleaseArtifact(applicationRelease, appType, deviceType, binaryFile); - } catch (ApplicationStorageManagementException e) { - throw new ApplicationStorageManagementException("ApplicationDTO Artifact doesn't contains in the System", e); - } catch (ResourceManagementException e) { - throw new ApplicationStorageManagementException("ApplicationDTO Artifact Updating failed", e); + String basePath = storagePath + Constants.FORWARD_SLASH; + String appHashValue = applicationReleaseDTO.getAppHashValue(); + String bannerName = applicationReleaseDTO.getBannerName(); + String iconName = applicationReleaseDTO.getIconName(); + String screenshot1 = applicationReleaseDTO.getScreenshotName1(); + String screenshot2 = applicationReleaseDTO.getScreenshotName2(); + String screenshot3 = applicationReleaseDTO.getScreenshotName3(); + + if (bannerName != null) { + StorageManagementUtil + .copy(basePath + deletingAppHashValue + bannerName, basePath + appHashValue + bannerName); + } + if (iconName != null) { + StorageManagementUtil + .copy(basePath + deletingAppHashValue + iconName, basePath + appHashValue + iconName); + } + if (screenshot1 != null) { + StorageManagementUtil + .copy(basePath + deletingAppHashValue + screenshot1, basePath + appHashValue + screenshot1); + } + if (screenshot2 != null) { + StorageManagementUtil + .copy(basePath + deletingAppHashValue + screenshot2, basePath + appHashValue + screenshot2); + } + if (screenshot3 != null) { + StorageManagementUtil + .copy(basePath + deletingAppHashValue + screenshot3, basePath + appHashValue + screenshot3); + } + deleteApplicationReleaseArtifacts( basePath + deletingAppHashValue); + } catch (IOException e) { + String msg = "Application installer updating is failed because of I/O issue"; + log.error(msg); + throw new ApplicationStorageManagementException(msg, e); } - return applicationRelease; } @Override - public void deleteApplicationReleaseArtifacts(String directoryPath) throws ApplicationStorageManagementException { - File artifact = new File(directoryPath); + public void deleteApplicationReleaseArtifacts(String artifactPath) throws ApplicationStorageManagementException { + File artifact = new File(artifactPath); if (artifact.exists()) { try { - StorageManagementUtil.deleteDir(artifact); + StorageManagementUtil.delete(artifact); } catch (IOException e) { throw new ApplicationStorageManagementException( "Error occured while deleting application release artifacts", e); @@ -283,17 +295,6 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager } } - private String getMD5(InputStream binaryFile) throws ApplicationStorageManagementException { - String md5; - try { - md5 = DigestUtils.md5Hex(binaryFile); - } catch (IOException e) { - throw new ApplicationStorageManagementException - ("IO Exception while trying to get the md5sum value of application"); - } - return md5; - } - private synchronized Map getIPAInfo(File ipaFile) throws ApplicationStorageManagementException { Map ipaInfo = new HashMap<>(); @@ -303,7 +304,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager ipaDirectory = new File(ipaAbsPath).getParent(); if (new File(ipaDirectory + File.separator + Constants.PAYLOAD).exists()) { - deleteDir(new File(ipaDirectory + File.separator + Constants.PAYLOAD)); + delete(new File(ipaDirectory + File.separator + Constants.PAYLOAD)); } // unzip ipa zip file @@ -333,7 +334,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager if (ipaDirectory != null) { // remove unzip folder - deleteDir(new File(ipaDirectory + File.separator + Constants.PAYLOAD)); + delete(new File(ipaDirectory + File.separator + Constants.PAYLOAD)); } } catch (ParseException e) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java index e5fa42ab12c..cc228f9d1f5 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java @@ -103,7 +103,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - int applicationReleaseId = application.getApplicationReleases().get(0).getId(); + int applicationReleaseId = application.getApplicationReleaseDTOs().get(0).getId(); try { ConnectionManagerUtil.openDBConnection(); @@ -144,7 +144,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - int applicationReleaseId = application.getApplicationReleases().get(0).getId(); + int applicationReleaseId = application.getApplicationReleaseDTOs().get(0).getId(); try { ConnectionManagerUtil.openDBConnection(); @@ -188,7 +188,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - int applicationReleaseId = application.getApplicationReleases().get(0).getId(); + int applicationReleaseId = application.getApplicationReleaseDTOs().get(0).getId(); try { ConnectionManagerUtil.openDBConnection(); @@ -239,7 +239,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); String subscriber = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); - int applicationReleaseId = application.getApplicationReleases().get(0).getId(); + int applicationReleaseId = application.getApplicationReleaseDTOs().get(0).getId(); try { ConnectionManagerUtil.openDBConnection(); List deviceList = new ArrayList<>(); @@ -266,8 +266,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager { //todo: generate operation payload correctly for all types of devices. operation.setPayLoad( - "{'type':'enterprise', 'url':'" + application.getApplicationReleases().get(0).getInstallerName() - + "', 'app':'" + application.getApplicationReleases().get(0).getUuid() + "'}"); + "{'type':'enterprise', 'url':'" + application.getApplicationReleaseDTOs().get(0).getInstallerName() + + "', 'app':'" + application.getApplicationReleaseDTOs().get(0).getUuid() + "'}"); return operation; } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManager.java index 139e8367ede..140383fb02e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/lifecycle/LifecycleStateManager.java @@ -133,7 +133,7 @@ public class LifecycleStateManager { return null; } - public boolean isUpdatable(String state) throws LifecycleManagementException { + public boolean isUpdatableState(String state) throws LifecycleManagementException { State currentState = getMatchingState(state); if (currentState != null) { return currentState.isAppUpdatable(); @@ -144,7 +144,7 @@ public class LifecycleStateManager { } } - public boolean isInstallable(String state) throws LifecycleManagementException { + public boolean isInstallableState(String state) throws LifecycleManagementException { State currentState = getMatchingState(state); if (currentState != null) { return currentState.isAppInstallable(); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/StorageManagementUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/StorageManagementUtil.java index 0aae14620a1..45c43a8d57f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/StorageManagementUtil.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/StorageManagementUtil.java @@ -19,10 +19,12 @@ package org.wso2.carbon.device.application.mgt.core.util; import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.application.mgt.common.ImageArtifact; +import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; import java.io.File; @@ -61,16 +63,28 @@ public class StorageManagementUtil { * * @param artifactDirectory Artifact Directory that need to be deleted. */ - public static void deleteDir(File artifactDirectory) throws IOException { + public static void delete(File artifactDirectory) throws IOException { File[] contents = artifactDirectory.listFiles(); if (contents != null) { for (File file : contents) { - deleteDir(file); + delete(file); } } Files.delete(artifactDirectory.toPath()); } + public static void copy(String source, String destination) throws IOException { + File sourceFile = new File(source); + File destinationFile = new File(destination); + if (sourceFile.exists() && destinationFile.exists()) { + Files.copy(sourceFile.toPath(), destinationFile.toPath()); + } else { + String msg = "Source file " + source + " or destination file " + destination + " doesn't exist"; + log.error(msg); + throw new IOException(msg); + } + } + /** * To save a file in a given location. * @@ -120,4 +134,15 @@ public class StorageManagementUtil { throw new IOException(msg); } } + + public static String getMD5(InputStream binaryFile) throws ApplicationStorageManagementException { + String md5; + try { + md5 = DigestUtils.md5Hex(binaryFile); + } catch (IOException e) { + throw new ApplicationStorageManagementException + ("IO Exception while trying to get the md5sum value of application"); + } + return md5; + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/LifecycleManagementTest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/LifecycleManagementTest.java index 254ccf6d168..db7bdd2c6fb 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/LifecycleManagementTest.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/LifecycleManagementTest.java @@ -51,27 +51,27 @@ public class LifecycleManagementTest { // @Test // public void CheckUpdatableState() { -// boolean isUpdatable = lifecycleStateManager.isUpdatable(UPDATABLE_STATE); -// System.out.println(isUpdatable); -// Assert.assertTrue("Updatable state: " + UPDATABLE_STATE, isUpdatable); +// boolean isUpdatableState = lifecycleStateManager.isUpdatableState(UPDATABLE_STATE); +// System.out.println(isUpdatableState); +// Assert.assertTrue("Updatable state: " + UPDATABLE_STATE, isUpdatableState); // } // // @Test // public void CheckNonUpdatableState() { -// boolean isUpdatable = lifecycleStateManager.isUpdatable(NON_UPDATABLE_STATE); -// Assert.assertFalse("Non Updatable state: " + NON_UPDATABLE_STATE, isUpdatable); +// boolean isUpdatableState = lifecycleStateManager.isUpdatableState(NON_UPDATABLE_STATE); +// Assert.assertFalse("Non Updatable state: " + NON_UPDATABLE_STATE, isUpdatableState); // } // // @Test // public void CheckInstallableState() { -// boolean isInstallable = lifecycleStateManager.isInstallable(INSTALLABLE_STATE); -// Assert.assertTrue("Installable state: " + INSTALLABLE_STATE, isInstallable); +// boolean isInstallableState = lifecycleStateManager.isInstallableState(INSTALLABLE_STATE); +// Assert.assertTrue("Installable state: " + INSTALLABLE_STATE, isInstallableState); // } // // @Test // public void CheckUnInstallableState() { -// boolean isInstallable = lifecycleStateManager.isInstallable(UNINSTALlABLE_STATE); -// Assert.assertFalse("UnInstallable state: " + UNINSTALlABLE_STATE, isInstallable); +// boolean isInstallableState = lifecycleStateManager.isInstallableState(UNINSTALlABLE_STATE); +// Assert.assertFalse("UnInstallable state: " + UNINSTALlABLE_STATE, isInstallableState); // } // // @Test diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/StorageManagementUtilTest.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/StorageManagementUtilTest.java index 68817849cfb..96a498b5a06 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/StorageManagementUtilTest.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/java/org.wso2.carbon.device.application.mgt.core/StorageManagementUtilTest.java @@ -39,7 +39,7 @@ public class StorageManagementUtilTest { public void before() throws IOException { File file = new File(TEMP_FOLDER); if (file.exists()) { - StorageManagementUtil.deleteDir(file); + StorageManagementUtil.delete(file); } } @@ -67,7 +67,7 @@ public class StorageManagementUtilTest { @AfterMethod public void deleteFileTest() throws IOException, ResourceManagementException { File file = new File(TEMP_FOLDER); - StorageManagementUtil.deleteDir(file); + StorageManagementUtil.delete(file); if (file.exists()) { Assert.fail("File deleting failed."); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.handler/src/main/java/org/wso2/carbon/device/application/mgt/handler/util/HandlerConstants.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.handler/src/main/java/org/wso2/carbon/device/application/mgt/handler/util/HandlerConstants.java index fcfd53c9265..2dfd677e037 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.handler/src/main/java/org/wso2/carbon/device/application/mgt/handler/util/HandlerConstants.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.handler/src/main/java/org/wso2/carbon/device/application/mgt/handler/util/HandlerConstants.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.application.mgt.handler.util; public class HandlerConstants { public static final String PUBLISHER_APPLICATION_NAME = "application-mgt-publisher"; public static final String APP_REG_ENDPOINT = "/api-application-registration/register"; - public static final String UI_CONFIG_ENDPOINT = "/api/application-mgt/v1.0/app-mgt/ui-config"; + public static final String UI_CONFIG_ENDPOINT = "/api/application-mgt/v1.0/config/ui-config"; public static final String TOKEN_ENDPOINT = "/oauth2/token"; public static final String AUTHORIZATION = "Authorization"; public static final String BASIC = "Basic "; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/ApplicationManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/ApplicationManagementAPI.java index 7808f5ee084..69715b59989 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/ApplicationManagementAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/ApplicationManagementAPI.java @@ -36,6 +36,8 @@ import org.wso2.carbon.device.application.mgt.common.*; import org.wso2.carbon.device.application.mgt.common.ErrorResponse; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; +import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease; +import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper; import java.util.List; @@ -155,9 +157,12 @@ public interface ApplicationManagementAPI { code = 200, message = "OK. \n Successfully retrieved relevant application.", response = ApplicationDTO.class), + @ApiResponse( + code = 403, + message = "Don't have permission to access the application"), @ApiResponse( code = 404, - message = "ApplicationDTO not found"), + message = "Application not found"), @ApiResponse( code = 500, message = "Internal Server Error. \n Error occurred while getting relevant application.", @@ -218,7 +223,7 @@ public interface ApplicationManagementAPI { name = "application", value = "The application that need to be edited.", required = true) - @Valid ApplicationDTO application + @Valid ApplicationWrapper applicationWrapper ); @POST @@ -290,78 +295,85 @@ public interface ApplicationManagementAPI { @Multipart(value = "screenshot3") Attachment screenshot3 ); -// @POST -// @Produces(MediaType.APPLICATION_JSON) -// @Consumes("multipart/mixed") -// @Path("/{deviceType}/{appType}/{appId}") -// @ApiOperation( -// consumes = MediaType.APPLICATION_JSON, -// produces = MediaType.APPLICATION_JSON, -// httpMethod = "POST", -// value = "Create an application", -// notes = "This will create a new application", -// 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 = Application.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 createRelease( -// @PathParam("deviceType") String deviceType, -// @PathParam("appId") String appType, -// @PathParam("appId") int appId, -// @ApiParam( -// name = "applicationRelease", -// value = "The application release that need to be created.", -// required = true) -// @Multipart("applicationRelease") ApplicationReleaseDTO applicationRelease, -// @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", -// required = true) -// @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") + @Path("/{appType}/{appId}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "POST", + value = "Create an application", + notes = "This will create a new application", + 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 createRelease( + @ApiParam( + name = "appType", + value = "Application Type.", + required = true) + @PathParam("appType") String appType, + @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") ApplicationReleaseWrapper applicationReleaseWrapper, + @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", + required = true) + @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 + ); @DELETE @Consumes("application/json") @@ -399,7 +411,7 @@ public interface ApplicationManagementAPI { ); @PUT - @Path("/image-artifacts/{appId}/{uuid}") + @Path("/image-artifacts/{uuid}") @Produces(MediaType.APPLICATION_JSON) @Consumes("multipart/mixed") @ApiOperation( @@ -437,11 +449,6 @@ public interface ApplicationManagementAPI { response = ErrorResponse.class) }) Response updateApplicationImageArtifacts( - @ApiParam( - name = "appId", - value = "ID of the application", - required = true) - @PathParam("appId") int applicatioId, @ApiParam( name = "uuid", value = "UUID of the application", @@ -509,13 +516,20 @@ public interface ApplicationManagementAPI { response = ErrorResponse.class) }) Response updateApplicationArtifact( - @ApiParam(name = "deviceType", value = "Type of the device i.e Android, IOS etc", required = true) + @ApiParam( + name = "deviceType", + value = "Type of the device i.e Android, IOS etc", + required = true) @PathParam("deviceType") String deviceType, - @ApiParam(name = "appType", value = "Type of the application i.e Mobile, WEB, WEB-CLIP etc", required = true) + @ApiParam( + name = "appType", + value = "Type of the application i.e ENTERPRISE, PUBLIC, WEB, WEB-CLIP etc", + required = true) @PathParam("appType") String appType, - @ApiParam(name = "appId", value = "Id of the application", required = true) - @PathParam("appId") int applicationId, - @ApiParam(name = "uuid", value = "UUID of the application", required = true) + @ApiParam( + name = "uuid", + value = "UUID of the application", + required = true) @PathParam("uuid") String applicationUUID, @Multipart("binaryFile") Attachment binaryFile ); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementAPIImpl.java index 196339caf90..e1a71cc6731 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/services/impl/ApplicationManagementAPIImpl.java @@ -29,6 +29,8 @@ import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.response.Application; +import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease; +import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper; import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException; import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException; @@ -103,13 +105,24 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { @DefaultValue("PUBLISHED") @QueryParam("state") String state) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); try { - ApplicationDTO application = applicationManager.getApplicationById(appId, state); + Application application = applicationManager.getApplicationById(appId, state); + if (application == null){ + String msg = "Couldn't found an application release which is in " + state + " state for application id " + + appId; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } return Response.status(Response.Status.OK).entity(application).build(); } catch (NotFoundException e) { String msg = "ApplicationDTO with application id: " + appId + " not found"; log.error(msg, e); return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); - } catch (ApplicationManagementException e) { + } catch(ForbiddenException e){ + String msg = "You don't have permission to access the application. application id: " + appId; + log.error(msg); + return Response.status(Response.Status.FORBIDDEN).entity(msg).build(); + } + catch (ApplicationManagementException e) { String msg = "Error occurred while getting application with the id " + appId; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); @@ -143,8 +156,8 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { applicationManager.validateAppCreatingRequest(applicationWrapper); applicationManager.validateReleaseCreatingRequest(applicationWrapper.getApplicationReleaseWrappers().get(0), applicationWrapper.getType()); - applicationManager.isValidAttachmentSet(binaryFile, iconFile, bannerFile, attachmentList, - applicationWrapper.getType()); + applicationManager.validateBinaryArtifact(binaryFile, applicationWrapper.getType()); + applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); // Created new application entry Application application = applicationManager.createApplication(applicationWrapper, @@ -167,99 +180,63 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { } } -// @POST -// @Consumes("multipart/mixed") -// @Path("/{deviceType}/{appType}/{appId}") -// public Response createRelease( -// @PathParam("deviceType") String deviceType, -// @PathParam("appType") String appType, -// @PathParam("appId") int appId, -// @Multipart("applicationRelease") ApplicationReleaseDTO applicationRelease, -// @Multipart("binaryFile") Attachment binaryFile, -// @Multipart("icon") Attachment iconFile, -// @Multipart("banner") Attachment bannerFile, -// @Multipart("screenshot1") Attachment screenshot1, -// @Multipart("screenshot2") Attachment screenshot2, -// @Multipart("screenshot3") Attachment screenshot3) { -// ApplicationManager applicationManager = APIUtil.getApplicationManager(); -// ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); -// InputStream iconFileStream; -// InputStream bannerFileStream; -// List attachments = new ArrayList<>(); -// List attachmentList = new ArrayList<>(); -// attachmentList.add(screenshot1); -// if (screenshot2 != null) { -// attachmentList.add(screenshot2); -// } -// if (screenshot3 != null) { -// attachmentList.add(screenshot3); -// } -// -// try { -// applicationManager -// .validateReleaseCreatingRequest(applicationRelease, appType, binaryFile, iconFile, bannerFile, -// attachmentList); -// -// // The application executable artifacts such as apks are uploaded. -// if (!ApplicationType.ENTERPRISE.toString().equals(appType)) { -// applicationRelease = applicationStorageManager -// .uploadReleaseArtifact(applicationRelease, appType, deviceType, null); -// } else { -// applicationRelease = applicationStorageManager -// .uploadReleaseArtifact(applicationRelease, appType, deviceType, -// binaryFile.getDataHandler().getInputStream()); -// if (applicationRelease.getInstallerName() == null || applicationRelease.getAppHashValue() == null) { -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); -// } -// } -// -// iconFileStream = iconFile.getDataHandler().getInputStream(); -// bannerFileStream = bannerFile.getDataHandler().getInputStream(); -// -// for (Attachment screenshot : attachmentList) { -// attachments.add(screenshot.getDataHandler().getInputStream()); -// } -// -// // Upload images -// applicationRelease = applicationStorageManager -// .uploadImageArtifacts(applicationRelease, iconFileStream, bannerFileStream, attachments); -// applicationRelease.setUuid(UUID.randomUUID().toString()); -// -// // Created new application release entry -// ApplicationReleaseDTO release = applicationManager.createRelease(appId, applicationRelease); -// 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 (ApplicationManagementException e) { -// String msg = "Error occurred while creating the application"; -// log.error(msg, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); -// } catch (ResourceManagementException e) { -// String msg = "Error occurred while uploading the releases artifacts of the application ID: " + appId; -// log.error(msg, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); -// } catch (IOException e) { -// String msg = "Error while uploading binary file and resources for the application release of the " -// + "application ID: " + appId; -// log.error(msg, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); -// } catch (RequestValidatingException e) { -// String msg = "Error occurred while handling the application creating request"; -// log.error(msg, e); -// return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); -// } -// } + @POST + @Consumes("multipart/mixed") + @Path("/{appType}/{appId}") + public Response createRelease( + @PathParam("appType") String appType, + @PathParam("appId") int appId, + @Multipart("applicationRelease") ApplicationReleaseWrapper applicationReleaseWrapper, + @Multipart("binaryFile") Attachment binaryFile, + @Multipart("icon") Attachment iconFile, + @Multipart("banner") Attachment bannerFile, + @Multipart("screenshot1") Attachment screenshot1, + @Multipart("screenshot2") Attachment screenshot2, + @Multipart("screenshot3") Attachment screenshot3) { + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + List attachmentList = new ArrayList<>(); + + if (screenshot1 != null) { + attachmentList.add(screenshot1); + } + if (screenshot2 != null) { + attachmentList.add(screenshot2); + } + if (screenshot3 != null) { + attachmentList.add(screenshot3); + } + + try { + applicationManager.validateReleaseCreatingRequest(applicationReleaseWrapper, appType); + applicationManager.validateBinaryArtifact(binaryFile, appType); + applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList); + + // Created new application release + ApplicationRelease release = applicationManager.createRelease(appId, applicationReleaseWrapper, + 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 (ApplicationManagementException e) { + String msg = "Error occurred while creating the application"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (RequestValidatingException e) { + String msg = "Error occurred while handling the application creating request"; + log.error(msg, e); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + } @Override @PUT @Consumes("multipart/mixed") @Produces(MediaType.APPLICATION_JSON) - @Path("/image-artifacts/{appId}/{uuid}") + @Path("/image-artifacts/{uuid}") public Response updateApplicationImageArtifacts( - @PathParam("appId") int appId, @PathParam("uuid") String applicationReleaseUuid, @Multipart("icon") Attachment iconFile, @Multipart("banner") Attachment bannerFile, @@ -267,89 +244,72 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { @Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot3") Attachment screenshot3) { try { - InputStream iconFileStream = null; - InputStream bannerFileStream = null; - List attachments = new ArrayList<>(); + List attachments = new ArrayList<>(); - if (iconFile != null) { - iconFileStream = iconFile.getDataHandler().getInputStream(); - } - if (bannerFile != null) { - bannerFileStream = bannerFile.getDataHandler().getInputStream(); + if (screenshot1 != null) { + attachments.add(screenshot1); } - attachments.add(screenshot1.getDataHandler().getInputStream()); if (screenshot2 != null) { - attachments.add(screenshot2.getDataHandler().getInputStream()); + attachments.add(screenshot2); } if (screenshot3 != null) { - attachments.add(screenshot3.getDataHandler().getInputStream()); + attachments.add(screenshot3); } ApplicationManager applicationManager = APIUtil.getApplicationManager(); - applicationManager - .updateApplicationImageArtifact(appId, applicationReleaseUuid, iconFileStream, bannerFileStream, - attachments); + applicationManager.validateImageArtifacts(iconFile, bannerFile, attachments); + applicationManager.updateApplicationImageArtifact(applicationReleaseUuid, + constructApplicationArtifact(null, iconFile, bannerFile, attachments)); return Response.status(Response.Status.OK) .entity("Successfully uploaded artifacts for the application " + applicationReleaseUuid).build(); + } catch (RequestValidatingException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (NotFoundException e) { log.error(e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); - } catch (ValidationException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (ForbiddenException e) { log.error(e.getMessage(), e); return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build(); } catch (ApplicationManagementException e) { - String msg = "Error occurred while updating the application image artifacts for app id: " + appId - + " application release uuid: " + applicationReleaseUuid; + String msg = "Error occurred while updating the application image artifacts for application release uuid: " + + applicationReleaseUuid; log.error(msg, e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } catch (IOException e) { - String msg = - "Exception while trying to read icon, banner files for the application " + applicationReleaseUuid; - log.error(msg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); } } @Override @PUT @Consumes("multipart/mixed") - @Path("/app-artifacts/{deviceType}/{appType}/{appId}/{uuid}") + @Path("/app-artifact/{deviceType}/{appType}/{uuid}") public Response updateApplicationArtifact( @PathParam("deviceType") String deviceType, @PathParam("appType") String appType, - @PathParam("appId") int applicationId, @PathParam("uuid") String applicationReleaseUuid, @Multipart("binaryFile") Attachment binaryFile) { try { - if (binaryFile == null) { - return Response.status(Response.Status.BAD_REQUEST) - .entity("binary file is NULL, hence invalid request to update application release artifact for application release UUID: " - + applicationReleaseUuid).build(); - } + ApplicationManager applicationManager = APIUtil.getApplicationManager(); + if (!ApplicationType.ENTERPRISE.toString().equals(appType)) { - return Response.status(Response.Status.BAD_REQUEST).entity("If ApplicationDTO type is " + appType + String msg = "If ApplicationDTO type is " + appType + ", therefore you don't have application release artifact to update for application release UUID: " - + applicationReleaseUuid).build(); + + applicationReleaseUuid; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } - APIUtil.getApplicationManager().updateApplicationArtifact(applicationId, deviceType, applicationReleaseUuid, - binaryFile.getDataHandler().getInputStream()); + applicationManager.validateBinaryArtifact(binaryFile, appType); + applicationManager.updateApplicationArtifact(deviceType, appType, applicationReleaseUuid, + constructApplicationArtifact(binaryFile, null, null, null)); return Response.status(Response.Status.OK) .entity("Successfully uploaded artifacts for the application release. UUID is " + applicationReleaseUuid).build(); - } catch (IOException e) { - String msg = "Error occurred while trying to read icon, banner files for the application release" - + applicationReleaseUuid; - log.error(msg); - return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (RequestValidatingException e) { + log.error(e.getMessage(), e); + return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (NotFoundException e) { log.error(e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); - } catch (ValidationException e) { - log.error(e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build(); } catch (ApplicationManagementException e) { log.error("Error occurred while updating the image artifacts of the application with the uuid " + applicationReleaseUuid, e); @@ -363,10 +323,13 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { @Path("/{appId}") public Response updateApplication( @PathParam("appId") int applicationId, - @Valid ApplicationDTO application) { + @Valid ApplicationWrapper applicationWrapper) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); try { - application = applicationManager.updateApplication(applicationId, application); + //todo wrong + applicationManager.updateApplication(applicationId, applicationWrapper); + return Response.status(Response.Status.OK) + .entity("Application was updated successfully. ApplicationID " + applicationId).build(); } catch (NotFoundException e) { log.error(e.getMessage()); return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); @@ -378,7 +341,6 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { log.error(msg, e); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); } - return Response.status(Response.Status.OK).entity(application).build(); } @Override @@ -610,65 +572,71 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { applicationArtifact.setInstallerStream(installerStream); } - dataHandler = iconFile.getDataHandler(); - String iconFileName = dataHandler.getName(); - InputStream iconStream = dataHandler.getInputStream(); + 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); - - 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); + 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); } - applicationArtifact.setBannerName(bannerFileName); - applicationArtifact.setBannerStream(bannerStream); - - Map scrrenshotData = new HashMap<>(); - for (Attachment sc : attachmentList) { - dataHandler = sc.getDataHandler(); - String screenshotrFileName = 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."; + + 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 (screenshotrFileName == null) { - String msg = - "Screenshot file name retrieving is failed for one screenshot. Hence can't proceed. Please verify the " - + "screenshots."; + 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); } - scrrenshotData.put(screenshotrFileName, screenshotStream); + applicationArtifact.setBannerName(bannerFileName); + applicationArtifact.setBannerStream(bannerStream); + } + + if (attachmentList != null) { + Map scrrenshotData = new HashMap<>(); + for (Attachment sc : attachmentList) { + dataHandler = sc.getDataHandler(); + String screenshotrFileName = 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 (screenshotrFileName == 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); + } + scrrenshotData.put(screenshotrFileName, screenshotStream); + } + applicationArtifact.setScreenshots(scrrenshotData); } - applicationArtifact.setScreenshots(scrrenshotData); return applicationArtifact; } catch (IOException e) { String msg = "Error occurred when reading attachment data.";