Add ne APIs and refactor

feature/appm-store/pbac
lasanthaDLPDS 6 years ago
parent 19f088d222
commit 6c543922b4

@ -53,12 +53,12 @@ public interface ApplicationManager {
/** /**
* Updates an already existing application. * 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 * @param applicationId ID of the application
* @return Updated Application * @return Updated Application
* @throws ApplicationManagementException ApplicationDTO Management Exception * @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. * Delete an application identified by the unique ID.
@ -94,7 +94,7 @@ public interface ApplicationManager {
* @return the ApplicationDTO identified by the ID * @return the ApplicationDTO identified by the ID
* @throws ApplicationManagementException ApplicationDTO Management Exception. * @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. * To get the ApplicationDTO for given application relase UUID.
@ -139,28 +139,24 @@ public interface ApplicationManager {
/** /**
* To update release images such as icons, banner and screenshots. * To update release images such as icons, banner and screenshots.
* *
* @param appId ID of the ApplicationDTO
* @param uuid uuid of the ApplicationDTO * @param uuid uuid of the ApplicationDTO
* @param iconFileStream icon file of the release * @param applicationArtifact Application artifact that contains names and input streams of the application artifacts.
* @param bannerFileStream bannerFileStream of the release.
* @param attachments screenshot attachments of the release
* @throws ApplicationManagementException ApplicationDTO Management Exception. * @throws ApplicationManagementException ApplicationDTO Management Exception.
*/ */
void updateApplicationImageArtifact(int appId, String uuid, InputStream iconFileStream, InputStream void updateApplicationImageArtifact(String uuid, ApplicationArtifact applicationArtifact) throws ApplicationManagementException;
bannerFileStream, List<InputStream> attachments) throws ApplicationManagementException;
/** /**
* To update release images. * To update release images.
* *
* @param appId ID of the ApplicationDTO * @param deviceType Application artifact compatible device type name.
* @param deviceType Applicable device type of the application * @param appType Type of the application.
* @param uuid uuid of the ApplicationDTO * @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. * @throws ApplicationManagementException ApplicationDTO Management Exception.
*/ */
void updateApplicationArtifact(int appId, String deviceType, String uuid, InputStream binaryFile) void updateApplicationArtifact(String deviceType, String appType, String uuid,
throws ApplicationManagementException; ApplicationArtifact applicationArtifact) throws ApplicationManagementException;
/** /**
* To create an application release for an ApplicationDTO. * To create an application release for an ApplicationDTO.
@ -207,15 +203,15 @@ public interface ApplicationManager {
/*** /***
* *
* @param binaryFile Uploading binary fila. i.e .apk or .ipa
* @param iconFile Icon file for the application. * @param iconFile Icon file for the application.
* @param bannerFile Banner file for the application. * @param bannerFile Banner file for the application.
* @param attachmentList Screenshot list. * @param attachmentList Screenshot list.
* @param applicationType Type of the application.
* @throws RequestValidatingException If request doesn't contains required attachments. * @throws RequestValidatingException If request doesn't contains required attachments.
*/ */
void isValidAttachmentSet(Attachment binaryFile, Attachment iconFile, Attachment bannerFile, void validateImageArtifacts(Attachment iconFile, Attachment bannerFile, List<Attachment> attachmentList)
List<Attachment> attachmentList, String applicationType) throws RequestValidatingException; throws RequestValidatingException;
void validateBinaryArtifact(Attachment binaryFile, String applicationType) throws RequestValidatingException;
void addAplicationCategories(List<String> categories) throws ApplicationManagementException; void addAplicationCategories(List<String> categories) throws ApplicationManagementException;

@ -47,13 +47,9 @@ public interface ApplicationStorageManager {
* To upload image artifacts related with an ApplicationDTO. * To upload image artifacts related with an ApplicationDTO.
* *
* @param applicationRelease Release of the application * @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. * @throws ResourceManagementException Resource Management Exception.
*/ */
ApplicationReleaseDTO updateImageArtifacts(ApplicationReleaseDTO applicationRelease, InputStream iconFile, void deleteImageArtifacts(ApplicationReleaseDTO applicationRelease) throws ResourceManagementException;
InputStream bannerFile, List<InputStream> screenshots) throws ResourceManagementException;
ApplicationInstaller getAppInstallerData(InputStream binaryFile, String deviceType) ApplicationInstaller getAppInstallerData(InputStream binaryFile, String deviceType)
throws ApplicationStorageManagementException; throws ApplicationStorageManagementException;
@ -74,14 +70,12 @@ public interface ApplicationStorageManager {
/** /**
* To upload release artifacts for an ApplicationDTO. * To upload release artifacts for an ApplicationDTO.
* *
* @param applicationRelease applicationRelease ApplicationDTO release of a particular application. * @param applicationReleaseDTO applicationRelease ApplicationDTO release of a particular application.
* @param appType Type of the application. * @param deletingAppHashValue Hash value of the deleting application release.
* @param deviceType Compatible device tipe of the application.
* @param binaryFile Binary File for the release.
* @throws ApplicationStorageManagementException Resource Management Exception. * @throws ApplicationStorageManagementException Resource Management Exception.
*/ */
ApplicationReleaseDTO updateReleaseArtifacts(ApplicationReleaseDTO applicationRelease, String appType, String deviceType, void copyImageArtifactsAndDeleteInstaller(String deletingAppHashValue,
InputStream binaryFile) throws ApplicationStorageManagementException, RequestValidatingException; ApplicationReleaseDTO applicationReleaseDTO) throws ApplicationStorageManagementException;
/** /**
* To delete the artifacts related with particular ApplicationDTO Release. * To delete the artifacts related with particular ApplicationDTO Release.

@ -149,15 +149,16 @@ public interface ApplicationDAO {
boolean verifyApplicationExistenceById(int appId, int tenantId) throws ApplicationManagementDAOException; 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 appName name of the application.
* @param appType type of the application. * @param deviceTypeId ID of the device type.
* @param tenantId ID of the tenant. * @param tenantId ID of the tenant.
* @return ID of the ApplicationDTO. * @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. * To edit the given application.

@ -82,12 +82,11 @@ public interface ApplicationReleaseDAO {
* To update an ApplicationDTO release. * To update an ApplicationDTO release.
* *
* @param applicationRelease ApplicationReleaseDTO that need to be updated. * @param applicationRelease ApplicationReleaseDTO that need to be updated.
* @param applicationId Id of the application.
* @param tenantId Id of the tenant * @param tenantId Id of the tenant
* @return the updated ApplicationDTO Release * @return the updated ApplicationDTO Release
* @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception
*/ */
ApplicationReleaseDTO updateRelease(int applicationId, ApplicationReleaseDTO applicationRelease, int tenantId) throws ApplicationReleaseDTO updateRelease(ApplicationReleaseDTO applicationRelease, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
/** /**
@ -129,6 +128,8 @@ public interface ApplicationReleaseDAO {
ApplicationReleaseDTO getReleaseByIds(int applicationId, String releaseUuid, int tenantId) throws ApplicationReleaseDTO getReleaseByIds(int applicationId, String releaseUuid, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
ApplicationReleaseDTO getReleaseByUUID(String uuid, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To verify whether application release exist or not. * To verify whether application release exist or not.
* *

@ -108,10 +108,12 @@ public class Util {
appRelease.setReleaseType(rs.getString("RELEASE_TYPE")); appRelease.setReleaseType(rs.getString("RELEASE_TYPE"));
appRelease.setVersion(rs.getString("RELEASE_VERSION")); appRelease.setVersion(rs.getString("RELEASE_VERSION"));
appRelease.setInstallerName(rs.getString("AP_RELEASE_STORED_LOC")); 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.setBannerName(rs.getString("AP_RELEASE_BANNER_LOC"));
appRelease.setScreenshotName1("AP_RELEASE_SC1"); appRelease.setScreenshotName1(rs.getString("AP_RELEASE_SC1"));
appRelease.setScreenshotName2("AP_RELEASE_SC2"); appRelease.setScreenshotName2(rs.getString("AP_RELEASE_SC2"));
appRelease.setScreenshotName3("AP_RELEASE_SC3"); appRelease.setScreenshotName3(rs.getString("AP_RELEASE_SC3"));
appRelease.setAppHashValue(rs.getString("RELEASE_HASH_VALUE"));
appRelease.setPrice(rs.getDouble("RELEASE_PRICE")); appRelease.setPrice(rs.getDouble("RELEASE_PRICE"));
appRelease.setMetaData(rs.getString("RELEASE_META_INFO")); appRelease.setMetaData(rs.getString("RELEASE_META_INFO"));
appRelease.setSupportedOsVersions(rs.getString("RELEASE_SUP_OS_VERSIONS")); appRelease.setSupportedOsVersions(rs.getString("RELEASE_SUP_OS_VERSIONS"));

@ -149,10 +149,12 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
+ "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + "AP_APP_RELEASE.UUID AS RELEASE_UUID, "
+ "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, " + "AP_APP_RELEASE.RELEASE_TYPE AS RELEASE_TYPE, "
+ "AP_APP_RELEASE.INSTALLER_LOCATION AS AP_RELEASE_STORED_LOC, " + "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.BANNER_LOCATION AS AP_RELEASE_BANNER_LOC, "
+ "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, " + "AP_APP_RELEASE.SC_1_LOCATION AS AP_RELEASE_SC1, "
+ "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, " + "AP_APP_RELEASE.SC_2_LOCATION AS AP_RELEASE_SC2, "
+ "AP_APP_RELEASE.SC_3_LOCATION AS AP_RELEASE_SC3, " + "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_PRICE AS RELEASE_PRICE, "
+ "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, " + "AP_APP_RELEASE.APP_META_INFO AS RELEASE_META_INFO, "
+ "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, "
@ -1063,23 +1065,25 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @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; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
String sql; String sql;
int id = -1;
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setString(1, appName); stmt.setString(1, appName);
stmt.setString(2, appType); stmt.setInt(2, deviceTypeId);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (rs.next()) { return rs.next();
id = rs.getInt(1);
}
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -1087,6 +1091,5 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
return id;
} }
} }

@ -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. * To insert the application release properties.
* *
@ -378,39 +424,56 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
/** /**
* To insert the application release properties. * 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. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
@Override @Override
public ApplicationReleaseDTO updateRelease(int applicationId, ApplicationReleaseDTO applicationRelease, int tenantId) public ApplicationReleaseDTO updateRelease(ApplicationReleaseDTO applicationReleaseDTO, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
String sql = "UPDATE AP_APP_RELEASE SET VERSION = ?, UUID = ?, RELEASE_TYPE = ?, PACKAGE_NAME = ?," String sql = "UPDATE AP_APP_RELEASE "
+ " APP_PRICE = ?, STORED_LOCATION = ?, BANNER_LOCATION = ?, ICON_LOCATION =?, SC_1_LOCATION = ?, " + + "SET "
"SC_2_LOCATION = ?," + "DESCRIPTION = ?, "
+ " SC_3_LOCATION = ?, APP_HASH_VALUE = ?, SHARED_WITH_ALL_TENANTS = ?, APP_META_INFO = ? " + "VERSION = ?, "
+ "WHERE AP_APP_ID = ? AND TENANT_ID = ? AND ID = ?;"; + "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 { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setString(1, applicationRelease.getVersion()); statement.setString(1, applicationReleaseDTO.getDescription());
statement.setString(2, applicationRelease.getUuid()); statement.setString(2, applicationReleaseDTO.getVersion());
statement.setString(3, applicationRelease.getReleaseType()); statement.setString(3, applicationReleaseDTO.getUuid());
statement.setString(4, applicationRelease.getPackageName()); statement.setString(4, applicationReleaseDTO.getReleaseType());
statement.setDouble(5, applicationRelease.getPrice()); statement.setString(5, applicationReleaseDTO.getPackageName());
statement.setString(6, applicationRelease.getInstallerName()); statement.setDouble(6, applicationReleaseDTO.getPrice());
statement.setString(7, applicationRelease.getBannerName()); statement.setString(7, applicationReleaseDTO.getInstallerName());
statement.setString(8, applicationRelease.getIconName()); statement.setString(8, applicationReleaseDTO.getBannerName());
statement.setString(9, applicationRelease.getScreenshotName1()); statement.setString(9, applicationReleaseDTO.getIconName());
statement.setString(10, applicationRelease.getScreenshotName2()); statement.setString(10, applicationReleaseDTO.getScreenshotName1());
statement.setString(11, applicationRelease.getScreenshotName3()); statement.setString(11, applicationReleaseDTO.getScreenshotName2());
statement.setString(12, applicationRelease.getAppHashValue()); statement.setString(12, applicationReleaseDTO.getScreenshotName3());
statement.setBoolean(13, applicationRelease.getIsSharedWithAllTenants()); statement.setString(13, applicationReleaseDTO.getAppHashValue());
statement.setString(14, applicationRelease.getMetaData()); statement.setBoolean(14, applicationReleaseDTO.getIsSharedWithAllTenants());
statement.setInt(15, applicationId); statement.setString(15, applicationReleaseDTO.getMetaData());
statement.setInt(16, tenantId); statement.setString(16, applicationReleaseDTO.getSupportedOsVersions());
statement.setInt(17, applicationRelease.getId()); statement.setString(17, applicationReleaseDTO.getCurrentState());
statement.setInt(18, tenantId);
statement.setInt(19, applicationReleaseDTO.getId());
if (statement.executeUpdate() == 0) { if (statement.executeUpdate() == 0) {
return null; return null;
} }
@ -423,7 +486,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
} finally { } finally {
Util.cleanupResources(statement, null); Util.cleanupResources(statement, null);
} }
return applicationRelease; return applicationReleaseDTO;
} }
/** /**

@ -67,7 +67,6 @@ 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.LifeCycleManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; 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.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.exception.VisibilityManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; 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.lifecycle.LifecycleStateManager;
@ -145,9 +144,10 @@ public class ApplicationManagerImpl implements ApplicationManager {
applicationDTO = appWrapperToAppDTO(applicationWrapper); applicationDTO = appWrapperToAppDTO(applicationWrapper);
ApplicationReleaseDTO initialApplicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0); ApplicationReleaseDTO initialApplicationReleaseDTO = applicationDTO.getApplicationReleaseDTOs().get(0);
applicationDTO.getApplicationReleaseDTOs().clear(); applicationDTO.getApplicationReleaseDTOs().clear();
applicationDTO.getApplicationReleaseDTOs()
.add(addApplicationReleaseArtifacts(applicationDTO.getType(), applicationDTO.getDeviceTypeName(), ApplicationReleaseDTO applicationReleaseDTO = addApplicationReleaseArtifacts(applicationDTO.getType(), applicationDTO.getDeviceTypeName(),
initialApplicationReleaseDTO, applicationArtifact)); initialApplicationReleaseDTO, applicationArtifact);
applicationDTO.getApplicationReleaseDTOs().add(addImageArtifacts(applicationReleaseDTO, applicationArtifact));
} catch (UnexpectedServerErrorException e) { } catch (UnexpectedServerErrorException e) {
String msg = "Error occurred when getting Device Type data."; String msg = "Error occurred when getting Device Type data.";
log.error(msg); log.error(msg);
@ -161,8 +161,8 @@ public class ApplicationManagerImpl implements ApplicationManager {
try { try {
List<ApplicationReleaseDTO> applicationReleaseEntities = new ArrayList<>(); List<ApplicationReleaseDTO> applicationReleaseEntities = new ArrayList<>();
ApplicationReleaseDTO applicationReleaseDTO; ApplicationReleaseDTO applicationReleaseDTO;
Filter filter = new Filter();
Filter filter = new Filter();
filter.setFullMatch(true); filter.setFullMatch(true);
filter.setAppName(applicationDTO.getName().trim()); filter.setAppName(applicationDTO.getName().trim());
filter.setOffset(0); filter.setOffset(0);
@ -193,10 +193,20 @@ public class ApplicationManagerImpl implements ApplicationManager {
List<String> unrestrictedRoles = applicationWrapper.getUnrestrictedRoles(); List<String> unrestrictedRoles = applicationWrapper.getUnrestrictedRoles();
if (!unrestrictedRoles.isEmpty()) { if (!unrestrictedRoles.isEmpty()) {
if (!isValidRestrictedRole(unrestrictedRoles)) { if (!isValidRestrictedRole(unrestrictedRoles)) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Unrestricted role list contain role/roles which are not in the user store."; String msg = "Unrestricted role list contain role/roles which are not in the user store.";
log.error(msg); log.error(msg);
throw new ApplicationManagementException(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); this.visibilityDAO.addUnrestrictedRoles(unrestrictedRoles, appId, tenantId);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("New restricted roles to app ID mapping added to AP_UNRESTRICTED_ROLE table." log.debug("New restricted roles to app ID mapping added to AP_UNRESTRICTED_ROLE table."
@ -251,7 +261,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
tagIds = this.applicationDAO.getTagIdsForTagNames(tags, tenantId); tagIds = this.applicationDAO.getTagIdsForTagNames(tags, tenantId);
} else { } else {
for (TagDTO tagDTO : registeredTags) { for (TagDTO tagDTO : registeredTags) {
for (String tagName : tags) { for (String tagName : tags) {
if (tagName.equals(tagDTO.getTagName())) { if (tagName.equals(tagDTO.getTagName())) {
@ -403,6 +412,12 @@ public class ApplicationManagerImpl implements ApplicationManager {
// Since WEB CLIP doesn't have an installer, set uuid as has value for WEB CLIP // Since WEB CLIP doesn't have an installer, set uuid as has value for WEB CLIP
applicationReleaseDTO.setAppHashValue(uuid); applicationReleaseDTO.setAppHashValue(uuid);
} }
return applicationReleaseDTO;
}
private ApplicationReleaseDTO addImageArtifacts(ApplicationReleaseDTO applicationReleaseDTO,
ApplicationArtifact applicationArtifact) throws ResourceManagementException {
ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager();
applicationReleaseDTO.setIconName(applicationArtifact.getIconName()); applicationReleaseDTO.setIconName(applicationArtifact.getIconName());
applicationReleaseDTO.setBannerName(applicationArtifact.getBannerName()); applicationReleaseDTO.setBannerName(applicationArtifact.getBannerName());
@ -441,8 +456,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
DeviceType deviceType = null; DeviceType deviceType = null;
try { try {
validateFilter(filter);
//set default values //set default values
if (StringUtils.isEmpty(filter.getSortBy())) { if (StringUtils.isEmpty(filter.getSortBy())) {
filter.setSortBy("ASC"); filter.setSortBy("ASC");
@ -456,6 +469,8 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
validateFilter(filter);
if (deviceType == null) { if (deviceType == null) {
appDTOs = applicationDAO.getApplications(filter, 0, tenantId); appDTOs = applicationDAO.getApplications(filter, 0, tenantId);
} else { } else {
@ -464,62 +479,46 @@ public class ApplicationManagerImpl implements ApplicationManager {
for (ApplicationDTO app : appDTOs) { for (ApplicationDTO app : appDTOs) {
boolean isSearchingApp = true; boolean isSearchingApp = true;
List<String> tags = filter.getTags(); List<String> filteringTags = filter.getTags();
List<String> categories = filter.getAppCategories(); List<String> filteringCategories = filter.getAppCategories();
List<String> unrestrictedRoles = filter.getUnrestrictedRoles(); List<String> filteringUnrestrictedRoles = filter.getUnrestrictedRoles();
if (lifecycleStateManager.getEndState().equals(app.getStatus())) { 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);
}
List<String> appUnrestrictedRoles = visibilityDAO.getUnrestrictedRoles(app.getId(), tenantId); List<String> appUnrestrictedRoles = visibilityDAO.getUnrestrictedRoles(app.getId(), tenantId);
boolean isUnrestrictedRoleExistForApp = false; if ((appUnrestrictedRoles.isEmpty() || hasUserRole(appUnrestrictedRoles, userName)) && (
for (String role : unrestrictedRoles) { filteringUnrestrictedRoles == null || filteringUnrestrictedRoles.isEmpty()
if (appUnrestrictedRoles.contains(role)) { || hasAppUnrestrictedRole(appUnrestrictedRoles, filteringUnrestrictedRoles,
isUnrestrictedRoleExistForApp = true; userName))) {
break; if (filteringCategories != null && !filteringCategories.isEmpty()) {
List<String> 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 (filteringTags != null && !filteringTags.isEmpty()) {
if (!isUnrestrictedRoleExistForApp) { List<String> appTagList = applicationDAO.getAppTags(app.getId(), tenantId);
isSearchingApp = false; boolean isAppTag = false;
} for (String tag : filteringTags) {
} if (appTagList.contains(tag)) {
if (tags != null && !tags.isEmpty()) { isAppTag = true;
List<String> appTagList = applicationDAO.getAppTags(app.getId(), tenantId); break;
boolean isTagExistForApp = false; }
for (String tag : tags) { }
if (appTagList.contains(tag)) { if (!isAppTag) {
isTagExistForApp = true; isSearchingApp = false;
break; }
} }
} if (isSearchingApp) {
if (!isTagExistForApp) { filteredApplications.add(app);
isSearchingApp = false;
}
}
if (categories != null && !categories.isEmpty()) {
List<String> appTagList = applicationDAO.getAppCategories(app.getId(), tenantId);
boolean isCategoryExistForApp = false;
for (String category : categories) {
if (appTagList.contains(category)) {
isCategoryExistForApp = true;
break;
} }
} }
if (!isCategoryExistForApp) {
isSearchingApp = false;
}
}
if (isSearchingApp) {
filteredApplications.add(app);
} }
} }
@ -546,6 +545,25 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
private boolean hasAppUnrestrictedRole(List<String> appUnrestrictedRoles, List<String> 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 @Override
public ApplicationRelease createRelease(int applicationId, public ApplicationRelease createRelease(int applicationId,
ApplicationReleaseWrapper applicationReleaseWrapper, ApplicationArtifact applicationArtifact) ApplicationReleaseWrapper applicationReleaseWrapper, ApplicationArtifact applicationArtifact)
@ -567,6 +585,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
ApplicationReleaseDTO applicationReleaseDTO = addApplicationReleaseArtifacts(applicationDTO.getType(), ApplicationReleaseDTO applicationReleaseDTO = addApplicationReleaseArtifacts(applicationDTO.getType(),
applicationDTO.getDeviceTypeName(), releaseWrapperToReleaseDTO(applicationReleaseWrapper), applicationDTO.getDeviceTypeName(), releaseWrapperToReleaseDTO(applicationReleaseWrapper),
applicationArtifact); applicationArtifact);
applicationReleaseDTO = addImageArtifacts(applicationReleaseDTO, applicationArtifact);
String initialstate = lifecycleStateManager.getInitialState(); String initialstate = lifecycleStateManager.getInitialState();
applicationReleaseDTO.setCurrentState(initialstate); applicationReleaseDTO.setCurrentState(initialstate);
@ -607,45 +626,54 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
@Override @Override
public ApplicationDTO getApplicationById(int appId, String state) throws ApplicationManagementException { public Application getApplicationById(int appId, String state) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
ApplicationDTO application; ApplicationDTO applicationDTO;
boolean isAppAllowed = false; List<ApplicationReleaseDTO> filteredApplicationReleaseDTOs;
boolean isVisibleApp = false;
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
application = this.applicationDAO.getApplicationById(appId, tenantId); applicationDTO = this.applicationDAO.getApplicationById(appId, tenantId);
if (application == null) { if (applicationDTO == null) {
throw new NotFoundException("Couldn't find an application for application Id: " + appId); 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<String> tags = this.applicationDAO.getAppTags(appId, tenantId); List<String> tags = this.applicationDAO.getAppTags(appId, tenantId);
List<String> categories = this.applicationDAO.getAppCategories(appId, tenantId); List<String> categories = this.applicationDAO.getAppCategories(appId, tenantId);
application.setTags(tags); applicationDTO.setTags(tags);
//todo when support to add multiple categories this has to be changed //todo when support to add multiple categories this has to be changed
if (!categories.isEmpty()){ if (!categories.isEmpty()){
application.setAppCategory(categories.get(0)); applicationDTO.setAppCategory(categories.get(0));
} }
if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
return application; return appDtoToAppResponse(applicationDTO);
} }
List<String> unrestrictedRoles = this.visibilityDAO.getUnrestrictedRoles(appId, tenantId); List<String> unrestrictedRoles = this.visibilityDAO.getUnrestrictedRoles(appId, tenantId);
if (!unrestrictedRoles.isEmpty()) { if (!unrestrictedRoles.isEmpty()) {
if (isRoleExists(unrestrictedRoles, userName)) { if (hasUserRole(unrestrictedRoles, userName)) {
isAppAllowed = true; isVisibleApp = true;
} }
} else { } else {
isAppAllowed = true; isVisibleApp = true;
} }
if (!isAppAllowed) { if (!isVisibleApp) {
String msg = "You are trying to access visibility restricted application. You don't have required " String msg = "You are trying to access visibility restricted application. You don't have required "
+ "roles to view this application,"; + "roles to view this application,";
log.error(msg); log.error(msg);
throw new ForbiddenException(msg); throw new ForbiddenException(msg);
} }
return application; return appDtoToAppResponse(applicationDTO);
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new ApplicationManagementException( throw new ApplicationManagementException(
"User-store exception while getting application with the application id " + appId); "User-store exception while getting application with the application id " + appId);
@ -674,7 +702,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
if (!application.getUnrestrictedRoles().isEmpty()) { if (!application.getUnrestrictedRoles().isEmpty()) {
if (isRoleExists(application.getUnrestrictedRoles(), userName)) { if (hasUserRole(application.getUnrestrictedRoles(), userName)) {
isAppAllowed = true; isAppAllowed = true;
} }
} else { } else {
@ -695,7 +723,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
private boolean isRoleExists(Collection<String> unrestrictedRoleList, String userName) throws UserStoreException { private boolean hasUserRole(Collection<String> unrestrictedRoleList, String userName) throws UserStoreException {
String[] roleList; String[] roleList;
roleList = getRolesOfUser(userName); roleList = getRolesOfUser(userName);
for (String unrestrictedRole : unrestrictedRoleList) { for (String unrestrictedRole : unrestrictedRoleList) {
@ -708,6 +736,20 @@ public class ApplicationManagerImpl implements ApplicationManager {
return false; return false;
} }
private boolean haveAllUserRoles(Collection<String> 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<String> unrestrictedRoleList) throws UserStoreException { private boolean isValidRestrictedRole(Collection<String> unrestrictedRoleList) throws UserStoreException {
List<String> roleList = new ArrayList<>(Arrays.asList(getRoleNames())); List<String> roleList = new ArrayList<>(Arrays.asList(getRoleNames()));
return roleList.containsAll(unrestrictedRoleList); return roleList.containsAll(unrestrictedRoleList);
@ -754,7 +796,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
if (!application.getUnrestrictedRoles().isEmpty()) { if (!application.getUnrestrictedRoles().isEmpty()) {
if (isRoleExists(application.getUnrestrictedRoles(), userName)) { if (hasUserRole(application.getUnrestrictedRoles(), userName)) {
isAppAllowed = true; isAppAllowed = true;
} }
} else { } else {
@ -784,7 +826,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
application = this.applicationDAO.getApplicationByRelease(appReleaseUUID, tenantId); application = this.applicationDAO.getApplicationByRelease(appReleaseUUID, tenantId);
if (application.getUnrestrictedRoles().isEmpty() || isRoleExists(application.getUnrestrictedRoles(), if (application.getUnrestrictedRoles().isEmpty() || hasUserRole(application.getUnrestrictedRoles(),
userName)) { userName)) {
return application; return application;
} }
@ -867,7 +909,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION) && !application 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( throw new ForbiddenException(
"You don't have permission to delete this application. In order to delete an application you " "You don't have permission to delete this application. In order to delete an application you "
+ "need to have required permission. ApplicationDTO ID: " + applicationId); + "need to have required permission. ApplicationDTO ID: " + applicationId);
@ -988,7 +1030,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new NotFoundException("Couldn't find an application for application ID: " + applicationId); throw new NotFoundException("Couldn't find an application for application ID: " + applicationId);
} }
if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION) && !application 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( throw new ForbiddenException(
"You don't have permission for deleting application release. ApplicationDTO id: " + applicationId "You don't have permission for deleting application release. ApplicationDTO id: " + applicationId
+ " and release UUID: " + releaseUuid); + " and release UUID: " + releaseUuid);
@ -1094,77 +1136,76 @@ public class ApplicationManagerImpl implements ApplicationManager {
return false; return false;
} }
//todo check whether user is whether admin user or application owner, otherwise throw an exception
@Override @Override
public void updateApplicationImageArtifact(int appId, String uuid, InputStream iconFileStream, //todo with this implementation user has to provide all image artifacts in order to update one image artifact as
InputStream bannerFileStream, List<InputStream> attachments) throws ApplicationManagementException { // well. Therefore enhance this later.
public void updateApplicationImageArtifact(String uuid, ApplicationArtifact applicationArtifact)
throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager(); ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager();
ApplicationReleaseDTO applicationRelease; ApplicationReleaseDTO applicationReleaseDTO;
try { try {
if (appId <= 0) {
throw new ValidationException(
"ApplicationDTO id could,t be a negative integer. Hence please add valid application id.");
}
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
applicationRelease = this.applicationReleaseDAO.getReleaseByIds(appId, uuid, tenantId); applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId);
if (applicationRelease == null) { if (applicationReleaseDTO == null) {
throw new NotFoundException( String msg = "Application release image artifact uploading is failed. Doesn't exist a application "
"Doesn't exist a application release for application ID: " + appId + "and application UUID: " + "release for application ID: application UUID: " + uuid;
+ uuid); log.error(msg);
} throw new NotFoundException(msg);
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);
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(); ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementException( String msg =
"Error occured when getting DB connection to update image artifacts of the application, appid: " "Error occured when getting DB connection to update image artifacts of the application release of haveing uuid "
+ appId + " and uuid " + uuid + ".", e); + uuid + ".";
log.error(msg);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException( String msg =
"Error occured while getting application release data for updating image artifacts of the application, appid: " "Error occured while getting application release data for updating image artifacts of the application release uuid "
+ appId + " and uuid " + uuid + ".", e); + uuid + ".";
} catch (LifeCycleManagementDAOException e) { log.error(msg);
ConnectionManagerUtil.rollbackDBTransaction(); throw new ApplicationManagementException(msg, e);
throw new ApplicationManagementException(
"Error occured while getting latest lifecycle state for updating image artifacts of the application, appid: "
+ appId + " and uuid " + uuid + ".", e);
} catch (ResourceManagementException e) { } catch (ResourceManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException( String msg = "Error occured while updating image artifacts of the application release uuid " + uuid + ".";
"Error occured while updating image artifacts of the application, appid: " + appId + " and uuid " log.error(msg);
+ uuid + " to the system.", e); throw new ApplicationManagementException(msg , e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
//todo check whether package names are same
@Override @Override
public void updateApplicationArtifact(int appId, String deviceType, String uuid, InputStream binaryFile) public void updateApplicationArtifact(String deviceType, String appType, String uuid,
throws ApplicationManagementException { ApplicationArtifact applicationArtifact) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager(); ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager();
ApplicationReleaseDTO applicationRelease; boolean isValidDeviceType = false;
List<DeviceType> deviceTypes;
try { try {
boolean isValidDeviceType = false; deviceTypes = Util.getDeviceManagementService().getDeviceTypes();
List<DeviceType> deviceTypes = Util.getDeviceManagementService().getDeviceTypes();
for (DeviceType dt : deviceTypes) { for (DeviceType dt : deviceTypes) {
if (dt.getName().equals(deviceType)) { if (dt.getName().equals(deviceType)) {
isValidDeviceType = true; isValidDeviceType = true;
@ -1172,59 +1213,64 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
if (!isValidDeviceType) { if (!isValidDeviceType) {
throw new ValidationException( String msg = "Invalid request to update application release artifact, invalid application type: "
"Invalid request to update application release artifact, invalid application type: " + deviceType + " for application release uuid: " + uuid;
+ deviceType + " for ApplicationDTO id: " + appId + " application release uuid: " + uuid); log.error(msg);
} throw new BadRequestException(msg);
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);
} }
} 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(); ConnectionManagerUtil.beginDBTransaction();
ApplicationDTO application = this.applicationDAO.getApplicationById(appId, tenantId); ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO.getReleaseByUUID(uuid, tenantId);
if (application == null) { if (applicationReleaseDTO == null) {
throw new NotFoundException("Doesn't exist a application for the application ID: " + appId); String msg = "Couldn't found an application release for UUID: " + uuid;
} log.error(msg);
applicationRelease = this.applicationReleaseDAO.getReleaseByIds(appId, uuid, tenantId); throw new NotFoundException(msg);
if (applicationRelease == null) {
throw new NotFoundException(
"Doesn't exist a application release for application ID: " + appId + "and application UUID: "
+ uuid);
} }
applicationRelease = applicationStorageManager
.updateReleaseArtifacts(applicationRelease, application.getType(), application.getDeviceTypeName(), String deletingAppHashValue = applicationReleaseDTO.getAppHashValue();
binaryFile); applicationReleaseDTO = addApplicationReleaseArtifacts(appType, deviceType, applicationReleaseDTO,
applicationRelease = this.applicationReleaseDAO.updateRelease(appId, applicationRelease, tenantId); applicationArtifact);
if (applicationRelease == null) { applicationStorageManager.copyImageArtifactsAndDeleteInstaller(deletingAppHashValue, applicationReleaseDTO);
applicationReleaseDTO = this.applicationReleaseDAO.updateRelease(applicationReleaseDTO, tenantId);
if (applicationReleaseDTO == null) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException( throw new ApplicationManagementException(
"ApplicationDTO release updating count is 0. ApplicationDTO id: " + appId "ApplicationDTO release updating count is 0. ApplicationDTO release UUID: " + uuid);
+ " ApplicationDTO release UUID: " + uuid);
} }
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); 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) { } catch (TransactionManagementException e) {
throw new ApplicationManagementException( String msg =
"Error occured while starting the transaction to update application release artifact of the application, appid: " "Error occured while starting the transaction to update application release artifact of the application uuid "
+ appId + " and uuid " + uuid + ".", e); + uuid + ".";
} catch (RequestValidatingException e) { log.error(msg);
ConnectionManagerUtil.rollbackDBTransaction(); throw new ApplicationManagementException(msg, e);
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);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementException( String msg =
"Error occured when getting DB connection to update application release artifact of the application, appid: " "Error occured when getting DB connection to update application release artifact of the application release uuid "
+ appId + " and uuid " + uuid + ".", e); + uuid + ".";
log.error(msg);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException("In order to update the artifact, couldn't find it in the system", throw new ApplicationManagementException("In order to update the artifact, couldn't find it in the system",
e); e);
} catch (ResourceManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured when updating application installer.";
log.error(msg);
throw new ApplicationManagementException(msg, e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -1246,7 +1292,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
// unRestrictedApplications.add(application); // unRestrictedApplications.add(application);
// } else { // } else {
// try { // try {
// if (isRoleExists(application.getUnrestrictedRoles(), userName)) { // if (hasUserRole(application.getUnrestrictedRoles(), userName)) {
// unRestrictedApplications.add(application); // unRestrictedApplications.add(application);
// } // }
// } catch (UserStoreException e) { // } catch (UserStoreException e) {
@ -1366,82 +1412,137 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
@Override @Override
public ApplicationDTO updateApplication(int applicationId, ApplicationDTO application) public void updateApplication(int applicationId, ApplicationWrapper applicationWrapper)
throws ApplicationManagementException { throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
ApplicationDTO existingApplication; ApplicationDTO applicationDTO;
boolean isExistingAppRestricted = false;
List<String> addingRoleList;
List<String> removingRoleList;
List<String> addingTags;
List<String> removingTags;
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
existingApplication = this.applicationDAO.getApplicationById(applicationId, tenantId); applicationDTO = this.applicationDAO.getApplicationById(applicationId, tenantId);
if (existingApplication == null) { 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(); 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())) { if (!StringUtils.isEmpty(applicationWrapper.getType()) && !applicationDTO.getType()
ConnectionManagerUtil.rollbackDBTransaction(); .equals(applicationWrapper.getType())) {
throw new ApplicationManagementException("You are trying to change the application type and it is not " 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 " + "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 (!StringUtils.isEmpty(applicationWrapper.getDeviceType()) && !applicationDTO.getDeviceTypeName()
if (ApplicationSubscriptionType.PAID.toString().equals(existingApplication.getSubType()) && ( .equals(applicationWrapper.getDeviceType())) {
!"".equals(application.getPaymentCurrency()) || application.getPaymentCurrency() != null)) { String msg = "You are trying to change the compatible device type of the application type and it is not "
ConnectionManagerUtil.rollbackDBTransaction(); + "possible after you create an application for device type. " +
throw new ApplicationManagementException("If you are going to change Non-Free app as Free app, " applicationWrapper.getDeviceType() + "Therefore please remove this application and publish "
+ "currency attribute in the application updating payload should be null or \"\""); + "new application with device type: " + applicationWrapper.getDeviceType();
} else if (ApplicationSubscriptionType.FREE.toString().equals(existingApplication.getSubType()) && ( log.error(msg);
application.getPaymentCurrency() == null || "".equals(application.getPaymentCurrency()))) { throw new BadRequestException(msg);
ConnectionManagerUtil.rollbackDBTransaction(); }
throw new ApplicationManagementException("If you are going to change Free app as Non-Free app, " if (!StringUtils.isEmpty(applicationWrapper.getSubType()) && !applicationDTO.getSubType()
+ "currency attribute in the application payload should not be null or \"\""); .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<ApplicationDTO> 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()) { if (!StringUtils.isEmpty(applicationWrapper.getDescription())){
visibilityDAO.deleteUnrestrictedRoles(existingApplication.getUnrestrictedRoles(), application.getId(), applicationDTO.setDescription(applicationWrapper.getDescription());
tenantId); }
} else if (!isExistingAppRestricted && !application.getUnrestrictedRoles().isEmpty()) {
visibilityDAO.addUnrestrictedRoles(application.getUnrestrictedRoles(), application.getId(), tenantId); List<String> appUnrestrictedRoles = this.visibilityDAO.getUnrestrictedRoles(applicationId, tenantId);
} else if (isExistingAppRestricted && !application.getUnrestrictedRoles().isEmpty()) { List<String> appCategories = this.applicationDAO.getAppCategories(applicationId, tenantId);
addingRoleList = getDifference(application.getUnrestrictedRoles(),
existingApplication.getUnrestrictedRoles()); boolean isExistingAppRestricted = !appUnrestrictedRoles.isEmpty();
removingRoleList = getDifference(existingApplication.getUnrestrictedRoles(), boolean isUpdatingAppRestricted = !applicationWrapper.getUnrestrictedRoles().isEmpty();
application.getUnrestrictedRoles());
if (!addingRoleList.isEmpty()) { if (isExistingAppRestricted && !isUpdatingAppRestricted) {
visibilityDAO.addUnrestrictedRoles(addingRoleList, application.getId(), tenantId); 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<String> addingRoleList = getDifference(applicationWrapper.getUnrestrictedRoles(),
applicationDTO.getUnrestrictedRoles());
List<String> 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()); List<String> appTags = this.applicationDAO.getAppTags(applicationId, tenantId);
removingTags = getDifference(application.getTags(), existingApplication.getTags()); List<String> addingTagList = getDifference(appTags, applicationWrapper.getTags());
if (!addingTags.isEmpty()) { List<String> removingTagList = getDifference(applicationWrapper.getTags(), appTags);
if (!addingTagList.isEmpty()) {
// applicationDAO.addTags(addingTags, application.getId(), tenantId); // applicationDAO.addTags(addingTags, application.getId(), tenantId);
} }
if (!removingTags.isEmpty()) { if (!removingTagList.isEmpty()) {
applicationDAO.deleteTags(removingTags, application.getId(), tenantId); applicationDAO.deleteTags(removingTagList, applicationId, tenantId);
} }
return applicationDAO.editApplication(application, tenantId); applicationDAO.editApplication(applicationDTO, tenantId);
} catch (UserStoreException e) { } catch (UserStoreException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException( throw new ApplicationManagementException(
@ -1613,7 +1714,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
String applicationReleaseCreatedUser = lifecycleStateDAO String applicationReleaseCreatedUser = lifecycleStateDAO
.getAppReleaseCreatedUsername(applicationId, releaseUuid, tenantId); .getAppReleaseCreatedUsername(applicationId, releaseUuid, tenantId);
if (!isAdminUser && !(!unrestrictedRoles.isEmpty() && isRoleExists(unrestrictedRoles, userName)) if (!isAdminUser && !(!unrestrictedRoles.isEmpty() && hasUserRole(unrestrictedRoles, userName))
&& !userName.equals(applicationReleaseCreatedUser)) { && !userName.equals(applicationReleaseCreatedUser)) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ForbiddenException("You are not authorized user to update application"); throw new ForbiddenException("You are not authorized user to update application");
@ -1630,11 +1731,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
+ " State"); + " State");
} }
release = applicationStorageManager // release = applicationStorageManager
.updateImageArtifacts(release, iconFileStream, bannerFileStream, attachments); // .deleteImageArtifacts(release, iconFileStream, bannerFileStream, attachments);
release = applicationStorageManager // release = applicationStorageManager
.updateReleaseArtifacts(release, app.getType(), deviceType, binaryFileStram); // .copyImageArtifactsAndDeleteInstaller(release, app.getType(), deviceType, binaryFileStram);
return applicationReleaseDAO.updateRelease(applicationId, release, tenantId) != null; return applicationReleaseDAO.updateRelease(release, tenantId) != null;
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new ApplicationManagementException("Error occured when validating the device type " + deviceType, e); throw new ApplicationManagementException("Error occured when validating the device type " + deviceType, e);
} catch (UserStoreException e) { } catch (UserStoreException e) {
@ -1651,31 +1752,32 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException( throw new ApplicationManagementException(
"Error occured when updating ApplicationDTO release. ApplicationDTO ID " + applicationId "Error occured when updating ApplicationDTO release. ApplicationDTO ID " + applicationId
+ " ApplicationDTO Release UUID: " + releaseUuid, e); + " 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 @Override
public void validateAppCreatingRequest(ApplicationWrapper applicationWrapper) throws RequestValidatingException { public void validateAppCreatingRequest(ApplicationWrapper applicationWrapper) throws RequestValidatingException {
boolean isValidApplicationType;
String applicationType = applicationWrapper.getType(); String applicationType = applicationWrapper.getType();
if (StringUtils.isEmpty(applicationWrapper.getName())) { if (StringUtils.isEmpty(applicationWrapper.getName())) {
@ -1699,13 +1801,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new RequestValidatingException(msg); 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<ApplicationReleaseWrapper> applicationReleaseWrappers; List<ApplicationReleaseWrapper> applicationReleaseWrappers;
applicationReleaseWrappers = applicationWrapper.getApplicationReleaseWrappers(); applicationReleaseWrappers = applicationWrapper.getApplicationReleaseWrappers();
@ -1754,8 +1849,8 @@ public class ApplicationManagerImpl implements ApplicationManager {
@Override @Override
public void isValidAttachmentSet(Attachment binaryFile, Attachment iconFile, Attachment bannerFile, public void validateImageArtifacts(Attachment iconFile, Attachment bannerFile,
List<Attachment> attachmentList, String applicationType) throws RequestValidatingException { List<Attachment> attachmentList) throws RequestValidatingException {
if (iconFile == null) { if (iconFile == null) {
String msg = "Icon file is not found with the application release creating request."; String msg = "Icon file is not found with the application release creating request.";
log.error(msg); log.error(msg);
@ -1771,8 +1866,18 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg); log.error(msg);
throw new RequestValidatingException(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); log.error(msg);
throw new RequestValidatingException(msg); throw new RequestValidatingException(msg);
} }

@ -24,18 +24,14 @@ import com.dd.plist.NSString;
import com.dd.plist.PropertyListFormatException; import com.dd.plist.PropertyListFormatException;
import com.dd.plist.PropertyListParser; import com.dd.plist.PropertyListParser;
import net.dongliu.apk.parser.bean.ApkMeta; import net.dongliu.apk.parser.bean.ApkMeta;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.UrlValidator;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.ApplicationInstaller; 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.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.DeviceTypes;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; 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.exception.ResourceManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.core.exception.ParsingException; 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 javax.xml.parsers.ParserConfigurationException;
import java.io.*; import java.io.*;
import java.nio.file.Files;
import java.text.ParseException; import java.text.ParseException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -54,7 +51,7 @@ import java.util.Objects;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; 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; import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.saveFile;
/** /**
@ -88,7 +85,6 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
String scStoredLocation = null; String scStoredLocation = null;
try { try {
// todo handle WEB CLIP and save data in different folder (uuid)
artifactDirectoryPath = storagePath + applicationRelease.getAppHashValue(); artifactDirectoryPath = storagePath + applicationRelease.getAppHashValue();
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath); StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
iconStoredLocation = artifactDirectoryPath + File.separator + applicationRelease.getIconName(); iconStoredLocation = artifactDirectoryPath + File.separator + applicationRelease.getIconName();
@ -135,43 +131,42 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
@Override @Override
public ApplicationReleaseDTO updateImageArtifacts(ApplicationReleaseDTO applicationRelease, InputStream public void deleteImageArtifacts(ApplicationReleaseDTO applicationReleaseDTO)
iconFileStream, InputStream bannerFileStream, List<InputStream> screenShotStreams)
throws ResourceManagementException { throws ResourceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try { try {
if (iconFileStream != null) { String iconName = applicationReleaseDTO.getIconName();
deleteApplicationReleaseArtifacts(applicationRelease.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) { if (bannerName != null) {
deleteApplicationReleaseArtifacts(applicationRelease.getBannerName()); deleteApplicationReleaseArtifacts(
storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + bannerName);
} }
if (!screenShotStreams.isEmpty()) {
if (screenShotStreams.size() > screenShotMaxCount) { if (sc1 != null) {
throw new ApplicationStorageManagementException("Maximum limit for the screen-shot exceeds"); deleteApplicationReleaseArtifacts(
} storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc1);
int count = 1; }
while (count < screenShotStreams.size()) { if (sc2 != null) {
if (count == 1) { deleteApplicationReleaseArtifacts(
deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotName1()); storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc2);
} }
if (count == 2) { if (sc3 != null) {
deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotName2()); deleteApplicationReleaseArtifacts(
} storagePath + Constants.FORWARD_SLASH + hashValue + Constants.FORWARD_SLASH + sc3);
if (count == 3) {
deleteApplicationReleaseArtifacts(applicationRelease.getScreenshotName3());
}
count++;
}
} }
applicationRelease = uploadImageArtifacts(applicationRelease, iconFileStream, bannerFileStream,
screenShotStreams);
return applicationRelease;
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
throw new ApplicationStorageManagementException("ApplicationDTO Storage exception while trying to" 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); " for the tenant " + tenantId, e);
} }
} }
@ -225,27 +220,53 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
} }
@Override @Override
public ApplicationReleaseDTO updateReleaseArtifacts(ApplicationReleaseDTO applicationRelease, public void copyImageArtifactsAndDeleteInstaller(String deletingAppHashValue,
String appType, String deviceType, InputStream binaryFile) throws ApplicationStorageManagementException { ApplicationReleaseDTO applicationReleaseDTO) throws ApplicationStorageManagementException {
try { try {
deleteApplicationReleaseArtifacts(applicationRelease.getInstallerName()); String basePath = storagePath + Constants.FORWARD_SLASH;
applicationRelease = uploadReleaseArtifact(applicationRelease, appType, deviceType, binaryFile); String appHashValue = applicationReleaseDTO.getAppHashValue();
} catch (ApplicationStorageManagementException e) { String bannerName = applicationReleaseDTO.getBannerName();
throw new ApplicationStorageManagementException("ApplicationDTO Artifact doesn't contains in the System", e); String iconName = applicationReleaseDTO.getIconName();
} catch (ResourceManagementException e) { String screenshot1 = applicationReleaseDTO.getScreenshotName1();
throw new ApplicationStorageManagementException("ApplicationDTO Artifact Updating failed", e); 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 @Override
public void deleteApplicationReleaseArtifacts(String directoryPath) throws ApplicationStorageManagementException { public void deleteApplicationReleaseArtifacts(String artifactPath) throws ApplicationStorageManagementException {
File artifact = new File(directoryPath); File artifact = new File(artifactPath);
if (artifact.exists()) { if (artifact.exists()) {
try { try {
StorageManagementUtil.deleteDir(artifact); StorageManagementUtil.delete(artifact);
} catch (IOException e) { } catch (IOException e) {
throw new ApplicationStorageManagementException( throw new ApplicationStorageManagementException(
"Error occured while deleting application release artifacts", e); "Error occured while deleting application release artifacts", e);
@ -283,7 +304,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
ipaDirectory = new File(ipaAbsPath).getParent(); ipaDirectory = new File(ipaAbsPath).getParent();
if (new File(ipaDirectory + File.separator + Constants.PAYLOAD).exists()) { 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 // unzip ipa zip file
@ -313,7 +334,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
if (ipaDirectory != null) { if (ipaDirectory != null) {
// remove unzip folder // remove unzip folder
deleteDir(new File(ipaDirectory + File.separator + Constants.PAYLOAD)); delete(new File(ipaDirectory + File.separator + Constants.PAYLOAD));
} }
} catch (ParseException e) { } catch (ParseException e) {

@ -133,7 +133,7 @@ public class LifecycleStateManager {
return null; return null;
} }
public boolean isUpdatable(String state) throws LifecycleManagementException { public boolean isUpdatableState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state); State currentState = getMatchingState(state);
if (currentState != null) { if (currentState != null) {
return currentState.isAppUpdatable(); 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); State currentState = getMatchingState(state);
if (currentState != null) { if (currentState != null) {
return currentState.isAppInstallable(); return currentState.isAppInstallable();

@ -63,16 +63,28 @@ public class StorageManagementUtil {
* *
* @param artifactDirectory Artifact Directory that need to be deleted. * @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(); File[] contents = artifactDirectory.listFiles();
if (contents != null) { if (contents != null) {
for (File file : contents) { for (File file : contents) {
deleteDir(file); delete(file);
} }
} }
Files.delete(artifactDirectory.toPath()); 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. * To save a file in a given location.
* *

@ -51,27 +51,27 @@ public class LifecycleManagementTest {
// @Test // @Test
// public void CheckUpdatableState() { // public void CheckUpdatableState() {
// boolean isUpdatable = lifecycleStateManager.isUpdatable(UPDATABLE_STATE); // boolean isUpdatableState = lifecycleStateManager.isUpdatableState(UPDATABLE_STATE);
// System.out.println(isUpdatable); // System.out.println(isUpdatableState);
// Assert.assertTrue("Updatable state: " + UPDATABLE_STATE, isUpdatable); // Assert.assertTrue("Updatable state: " + UPDATABLE_STATE, isUpdatableState);
// } // }
// //
// @Test // @Test
// public void CheckNonUpdatableState() { // public void CheckNonUpdatableState() {
// boolean isUpdatable = lifecycleStateManager.isUpdatable(NON_UPDATABLE_STATE); // boolean isUpdatableState = lifecycleStateManager.isUpdatableState(NON_UPDATABLE_STATE);
// Assert.assertFalse("Non Updatable state: " + NON_UPDATABLE_STATE, isUpdatable); // Assert.assertFalse("Non Updatable state: " + NON_UPDATABLE_STATE, isUpdatableState);
// } // }
// //
// @Test // @Test
// public void CheckInstallableState() { // public void CheckInstallableState() {
// boolean isInstallable = lifecycleStateManager.isInstallable(INSTALLABLE_STATE); // boolean isInstallableState = lifecycleStateManager.isInstallableState(INSTALLABLE_STATE);
// Assert.assertTrue("Installable state: " + INSTALLABLE_STATE, isInstallable); // Assert.assertTrue("Installable state: " + INSTALLABLE_STATE, isInstallableState);
// } // }
// //
// @Test // @Test
// public void CheckUnInstallableState() { // public void CheckUnInstallableState() {
// boolean isInstallable = lifecycleStateManager.isInstallable(UNINSTALlABLE_STATE); // boolean isInstallableState = lifecycleStateManager.isInstallableState(UNINSTALlABLE_STATE);
// Assert.assertFalse("UnInstallable state: " + UNINSTALlABLE_STATE, isInstallable); // Assert.assertFalse("UnInstallable state: " + UNINSTALlABLE_STATE, isInstallableState);
// } // }
// //
// @Test // @Test

@ -39,7 +39,7 @@ public class StorageManagementUtilTest {
public void before() throws IOException { public void before() throws IOException {
File file = new File(TEMP_FOLDER); File file = new File(TEMP_FOLDER);
if (file.exists()) { if (file.exists()) {
StorageManagementUtil.deleteDir(file); StorageManagementUtil.delete(file);
} }
} }
@ -67,7 +67,7 @@ public class StorageManagementUtilTest {
@AfterMethod @AfterMethod
public void deleteFileTest() throws IOException, ResourceManagementException { public void deleteFileTest() throws IOException, ResourceManagementException {
File file = new File(TEMP_FOLDER); File file = new File(TEMP_FOLDER);
StorageManagementUtil.deleteDir(file); StorageManagementUtil.delete(file);
if (file.exists()) { if (file.exists()) {
Assert.fail("File deleting failed."); Assert.fail("File deleting failed.");
} }

@ -223,7 +223,7 @@ public interface ApplicationManagementAPI {
name = "application", name = "application",
value = "The application that need to be edited.", value = "The application that need to be edited.",
required = true) required = true)
@Valid ApplicationDTO application @Valid ApplicationWrapper applicationWrapper
); );
@POST @POST
@ -298,7 +298,7 @@ public interface ApplicationManagementAPI {
@POST @POST
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@Path("/{deviceType}/{appType}/{appId}") @Path("/{appType}/{appId}")
@ApiOperation( @ApiOperation(
consumes = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -328,8 +328,15 @@ public interface ApplicationManagementAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response createRelease( Response createRelease(
@PathParam("deviceType") String deviceType, @ApiParam(
@PathParam("appId") String appType, 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, @PathParam("appId") int appId,
@ApiParam( @ApiParam(
name = "applicationRelease", name = "applicationRelease",
@ -404,7 +411,7 @@ public interface ApplicationManagementAPI {
); );
@PUT @PUT
@Path("/image-artifacts/{appId}/{uuid}") @Path("/image-artifacts/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@ApiOperation( @ApiOperation(
@ -442,11 +449,6 @@ public interface ApplicationManagementAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response updateApplicationImageArtifacts( Response updateApplicationImageArtifacts(
@ApiParam(
name = "appId",
value = "ID of the application",
required = true)
@PathParam("appId") int applicatioId,
@ApiParam( @ApiParam(
name = "uuid", name = "uuid",
value = "UUID of the application", value = "UUID of the application",
@ -514,13 +516,20 @@ public interface ApplicationManagementAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response updateApplicationArtifact( 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, @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, @PathParam("appType") String appType,
@ApiParam(name = "appId", value = "Id of the application", required = true) @ApiParam(
@PathParam("appId") int applicationId, name = "uuid",
@ApiParam(name = "uuid", value = "UUID of the application", required = true) value = "UUID of the application",
required = true)
@PathParam("uuid") String applicationUUID, @PathParam("uuid") String applicationUUID,
@Multipart("binaryFile") Attachment binaryFile @Multipart("binaryFile") Attachment binaryFile
); );

@ -105,7 +105,13 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@DefaultValue("PUBLISHED") @QueryParam("state") String state) { @DefaultValue("PUBLISHED") @QueryParam("state") String state) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { 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(); return Response.status(Response.Status.OK).entity(application).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
String msg = "ApplicationDTO with application id: " + appId + " not found"; String msg = "ApplicationDTO with application id: " + appId + " not found";
@ -150,8 +156,8 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
applicationManager.validateAppCreatingRequest(applicationWrapper); applicationManager.validateAppCreatingRequest(applicationWrapper);
applicationManager.validateReleaseCreatingRequest(applicationWrapper.getApplicationReleaseWrappers().get(0), applicationManager.validateReleaseCreatingRequest(applicationWrapper.getApplicationReleaseWrappers().get(0),
applicationWrapper.getType()); applicationWrapper.getType());
applicationManager.isValidAttachmentSet(binaryFile, iconFile, bannerFile, attachmentList, applicationManager.validateBinaryArtifact(binaryFile, applicationWrapper.getType());
applicationWrapper.getType()); applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList);
// Created new application entry // Created new application entry
Application application = applicationManager.createApplication(applicationWrapper, Application application = applicationManager.createApplication(applicationWrapper,
@ -176,9 +182,8 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@POST @POST
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@Path("/{deviceType}/{appType}/{appId}") @Path("/{appType}/{appId}")
public Response createRelease( public Response createRelease(
@PathParam("deviceType") String deviceType,
@PathParam("appType") String appType, @PathParam("appType") String appType,
@PathParam("appId") int appId, @PathParam("appId") int appId,
@Multipart("applicationRelease") ApplicationReleaseWrapper applicationReleaseWrapper, @Multipart("applicationRelease") ApplicationReleaseWrapper applicationReleaseWrapper,
@ -203,7 +208,8 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
try { try {
applicationManager.validateReleaseCreatingRequest(applicationReleaseWrapper, appType); applicationManager.validateReleaseCreatingRequest(applicationReleaseWrapper, appType);
applicationManager.isValidAttachmentSet(binaryFile, iconFile, bannerFile, attachmentList, appType); applicationManager.validateBinaryArtifact(binaryFile, appType);
applicationManager.validateImageArtifacts(iconFile, bannerFile, attachmentList);
// Created new application release // Created new application release
ApplicationRelease release = applicationManager.createRelease(appId, applicationReleaseWrapper, ApplicationRelease release = applicationManager.createRelease(appId, applicationReleaseWrapper,
@ -229,9 +235,8 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@PUT @PUT
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/image-artifacts/{appId}/{uuid}") @Path("/image-artifacts/{uuid}")
public Response updateApplicationImageArtifacts( public Response updateApplicationImageArtifacts(
@PathParam("appId") int appId,
@PathParam("uuid") String applicationReleaseUuid, @PathParam("uuid") String applicationReleaseUuid,
@Multipart("icon") Attachment iconFile, @Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile, @Multipart("banner") Attachment bannerFile,
@ -239,89 +244,72 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) { @Multipart("screenshot3") Attachment screenshot3) {
try { try {
InputStream iconFileStream = null; List<Attachment> attachments = new ArrayList<>();
InputStream bannerFileStream = null;
List<InputStream> attachments = new ArrayList<>();
if (iconFile != null) { if (screenshot1 != null) {
iconFileStream = iconFile.getDataHandler().getInputStream(); attachments.add(screenshot1);
} }
if (bannerFile != null) {
bannerFileStream = bannerFile.getDataHandler().getInputStream();
}
attachments.add(screenshot1.getDataHandler().getInputStream());
if (screenshot2 != null) { if (screenshot2 != null) {
attachments.add(screenshot2.getDataHandler().getInputStream()); attachments.add(screenshot2);
} }
if (screenshot3 != null) { if (screenshot3 != null) {
attachments.add(screenshot3.getDataHandler().getInputStream()); attachments.add(screenshot3);
} }
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
applicationManager applicationManager.validateImageArtifacts(iconFile, bannerFile, attachments);
.updateApplicationImageArtifact(appId, applicationReleaseUuid, iconFileStream, bannerFileStream, applicationManager.updateApplicationImageArtifact(applicationReleaseUuid,
attachments); constructApplicationArtifact(null, iconFile, bannerFile, attachments));
return Response.status(Response.Status.OK) return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application " + applicationReleaseUuid).build(); .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) { } catch (NotFoundException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); 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) { } catch (ForbiddenException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build(); return Response.status(Response.Status.FORBIDDEN).entity(e.getMessage()).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while updating the application image artifacts for app id: " + appId String msg = "Error occurred while updating the application image artifacts for application release uuid: "
+ " application release uuid: " + applicationReleaseUuid; + applicationReleaseUuid;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); 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 @Override
@PUT @PUT
@Consumes("multipart/mixed") @Consumes("multipart/mixed")
@Path("/app-artifacts/{deviceType}/{appType}/{appId}/{uuid}") @Path("/app-artifact/{deviceType}/{appType}/{uuid}")
public Response updateApplicationArtifact( public Response updateApplicationArtifact(
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@PathParam("appType") String appType, @PathParam("appType") String appType,
@PathParam("appId") int applicationId,
@PathParam("uuid") String applicationReleaseUuid, @PathParam("uuid") String applicationReleaseUuid,
@Multipart("binaryFile") Attachment binaryFile) { @Multipart("binaryFile") Attachment binaryFile) {
try { try {
if (binaryFile == null) { ApplicationManager applicationManager = APIUtil.getApplicationManager();
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();
}
if (!ApplicationType.ENTERPRISE.toString().equals(appType)) { 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: " + ", 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, applicationManager.validateBinaryArtifact(binaryFile, appType);
binaryFile.getDataHandler().getInputStream()); applicationManager.updateApplicationArtifact(deviceType, appType, applicationReleaseUuid,
constructApplicationArtifact(binaryFile, null, null, null));
return Response.status(Response.Status.OK) return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application release. UUID is " .entity("Successfully uploaded artifacts for the application release. UUID is "
+ applicationReleaseUuid).build(); + applicationReleaseUuid).build();
} catch (IOException e) { } catch (RequestValidatingException e) {
String msg = "Error occurred while trying to read icon, banner files for the application release" log.error(e.getMessage(), e);
+ applicationReleaseUuid; return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); 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) { } catch (ApplicationManagementException e) {
log.error("Error occurred while updating the image artifacts of the application with the uuid " log.error("Error occurred while updating the image artifacts of the application with the uuid "
+ applicationReleaseUuid, e); + applicationReleaseUuid, e);
@ -335,10 +323,13 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@Path("/{appId}") @Path("/{appId}")
public Response updateApplication( public Response updateApplication(
@PathParam("appId") int applicationId, @PathParam("appId") int applicationId,
@Valid ApplicationDTO application) { @Valid ApplicationWrapper applicationWrapper) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { 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) { } catch (NotFoundException e) {
log.error(e.getMessage()); log.error(e.getMessage());
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build(); return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
@ -350,7 +341,6 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} }
return Response.status(Response.Status.OK).entity(application).build();
} }
@Override @Override
@ -582,65 +572,71 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
applicationArtifact.setInstallerStream(installerStream); applicationArtifact.setInstallerStream(installerStream);
} }
dataHandler = iconFile.getDataHandler(); if (iconFile != null) {
String iconFileName = dataHandler.getName(); dataHandler = iconFile.getDataHandler();
InputStream iconStream = dataHandler.getInputStream(); String iconFileName = dataHandler.getName();
InputStream iconStream = dataHandler.getInputStream();
if (iconStream == null) { if (iconStream == null) {
String msg = "Stream of the application release icon is null. Hence can't proceed. Please " String msg = "Stream of the application release icon is null. Hence can't proceed. Please "
+ "verify the uploaded icon file."; + "verify the uploaded icon file.";
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
if (iconFileName == null) { if (iconFileName == null) {
String msg = String msg = "Icon file name retrieving is failed.. Hence can't proceed. Please verify the "
"Icon file name retrieving is failed.. Hence can't proceed. Please verify the " + "icon file."; + "icon file.";
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
applicationArtifact.setIconName(iconFileName); applicationArtifact.setIconName(iconFileName);
applicationArtifact.setIconStream(iconStream); 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);
} }
applicationArtifact.setBannerName(bannerFileName);
applicationArtifact.setBannerStream(bannerStream); if (bannerFile != null) {
dataHandler = bannerFile.getDataHandler();
Map<String, InputStream> scrrenshotData = new HashMap<>(); String bannerFileName = dataHandler.getName();
for (Attachment sc : attachmentList) { InputStream bannerStream = dataHandler.getInputStream();
dataHandler = sc.getDataHandler(); if (bannerStream == null) {
String screenshotrFileName = dataHandler.getName(); String msg = "Stream of the application release banner is null. Hence can't proceed. Please "
InputStream screenshotStream = dataHandler.getInputStream(); + "verify the uploaded banner file.";
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); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
if (screenshotrFileName == null) { if (bannerFileName == null) {
String msg = String msg = "Banner file name retrieving is failed.. Hence can't proceed. Please verify the "
"Screenshot file name retrieving is failed for one screenshot. Hence can't proceed. Please verify the " + "banner file.";
+ "screenshots.";
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
scrrenshotData.put(screenshotrFileName, screenshotStream); applicationArtifact.setBannerName(bannerFileName);
applicationArtifact.setBannerStream(bannerStream);
}
if (attachmentList != null) {
Map<String, InputStream> 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; return applicationArtifact;
} catch (IOException e) { } catch (IOException e) {
String msg = "Error occurred when reading attachment data."; String msg = "Error occurred when reading attachment data.";

Loading…
Cancel
Save