refactored the source and fixed some bugs

feature/appm-store/pbac
lasantha 7 years ago
parent 669881eae7
commit fb8d9dd494

@ -49,7 +49,9 @@ public class Application {
private int isRestricted; private int isRestricted;
private ApplicationRelease releaseVersion; private List<ApplicationRelease> applicationReleases;
// private ApplicationRelease releaseVersion;
private DeviceType devicetype; private DeviceType devicetype;
@ -103,13 +105,13 @@ public class Application {
this.unrestrictedRoles = unrestrictedRoles; this.unrestrictedRoles = unrestrictedRoles;
} }
public ApplicationRelease getReleaseVersion() { // public ApplicationRelease getReleaseVersion() {
return releaseVersion; // return releaseVersion;
} // }
//
public void setReleaseVersion(ApplicationRelease releaseVersion) { // public void setReleaseVersion(ApplicationRelease releaseVersion) {
this.releaseVersion = releaseVersion; // this.releaseVersion = releaseVersion;
} // }
public String getType() { public String getType() {
return type; return type;
@ -166,4 +168,12 @@ public class Application {
public void setIconOfLatestRelease(ImageArtifact iconOfLatestRelease) { public void setIconOfLatestRelease(ImageArtifact iconOfLatestRelease) {
this.iconOfLatestRelease = iconOfLatestRelease; this.iconOfLatestRelease = iconOfLatestRelease;
} }
public List<ApplicationRelease> getApplicationReleases() {
return applicationReleases;
}
public void setApplicationReleases(List<ApplicationRelease> applicationReleases) {
this.applicationReleases = applicationReleases;
}
} }

@ -60,18 +60,12 @@ public class ApplicationRelease {
private Timestamp publishedAt; private Timestamp publishedAt;
private int starts;
private String modifiedBy; private String modifiedBy;
private Timestamp modifiedAt; private Timestamp modifiedAt;
private ImageArtifact icon;
private String iconLoc; private String iconLoc;
private ImageArtifact banner;
private String currentState; private String currentState;
private String previousState; private String previousState;
@ -80,8 +74,6 @@ public class ApplicationRelease {
private Timestamp stateModifiedAt; private Timestamp stateModifiedAt;
private List<ImageArtifact> screenShots = new ArrayList<>();
private String appHashValue; private String appHashValue;
private int isSharedWithAllTenants; private int isSharedWithAllTenants;
@ -136,18 +128,6 @@ public class ApplicationRelease {
this.releaseType = releaseType; this.releaseType = releaseType;
} }
public void setIcon(ImageArtifact icon) {
this.icon = icon;
}
public void setBanner(ImageArtifact banner) {
this.banner = banner;
}
public void setScreenShots(List<ImageArtifact> screenShots) {
this.screenShots = screenShots;
}
public void setAppHashValue(String appHashValue) { public void setAppHashValue(String appHashValue) {
this.appHashValue = appHashValue; this.appHashValue = appHashValue;
} }
@ -208,18 +188,6 @@ public class ApplicationRelease {
this.stateModifiedAt = stateModifiedAt; this.stateModifiedAt = stateModifiedAt;
} }
public ImageArtifact getIcon() {
return icon;
}
public ImageArtifact getBanner() {
return banner;
}
public List<ImageArtifact> getScreenShots() {
return screenShots;
}
public String getAppHashValue() { public String getAppHashValue() {
return appHashValue; return appHashValue;
} }
@ -304,14 +272,6 @@ public class ApplicationRelease {
this.publishedAt = publishedAt; this.publishedAt = publishedAt;
} }
public int getStarts() {
return starts;
}
public void setStarts(int starts) {
this.starts = starts;
}
public String getModifiedBy() { public String getModifiedBy() {
return modifiedBy; return modifiedBy;
} }

@ -35,8 +35,7 @@ public interface ApplicationManager {
* @return Created application * @return Created application
* @throws ApplicationManagementException Application Management Exception * @throws ApplicationManagementException Application Management Exception
*/ */
Application createApplication(Application application) Application createApplication(Application application) throws ApplicationManagementException;
throws ApplicationManagementException;
/** /**
* Updates an already existing application. * Updates an already existing application.
@ -126,4 +125,15 @@ public interface ApplicationManager {
* * @throws ApplicationManagementException Application Management Exception. * * @throws ApplicationManagementException Application Management Exception.
*/ */
Boolean isUserAllowable(List<UnrestrictedRole> unrestrictedRoles, String userName) throws ApplicationManagementException; Boolean isUserAllowable(List<UnrestrictedRole> unrestrictedRoles, String userName) throws ApplicationManagementException;
/**
* To get all the releases of a particular Application.
*
* @param applicationId ID of the Application to get all the releases.
* @return the List of the Application releases related with the particular Application.
* @throws ApplicationManagementException Application Management Exception.
*/
List<ApplicationRelease> getReleases(int applicationId) throws ApplicationManagementException;
} }

@ -35,13 +35,12 @@ public interface ApplicationStorageManager {
/** /**
* To upload image artifacts related with an Application. * To upload image artifacts related with an Application.
* *
* @param applicationId ID of the application
* @param applicationRelease ApplicationRelease Object * @param applicationRelease ApplicationRelease Object
* @param iconFile Icon File input stream * @param iconFile Icon File input stream
* @param bannerFile Banner File input stream * @param bannerFile Banner File input stream
* @throws ResourceManagementException Resource Management Exception. * @throws ResourceManagementException Resource Management Exception.
*/ */
ApplicationRelease uploadImageArtifacts(int applicationId, ApplicationRelease applicationRelease, ApplicationRelease uploadImageArtifacts(ApplicationRelease applicationRelease,
InputStream iconFile, InputStream bannerFile, List<InputStream> screenshots) throws ResourceManagementException; InputStream iconFile, InputStream bannerFile, List<InputStream> screenshots) throws ResourceManagementException;
/** /**
@ -61,12 +60,11 @@ public interface ApplicationStorageManager {
/** /**
* To upload release artifacts for an Application. * To upload release artifacts for an Application.
* *
* @param applicationId UUID of the application related with the release.
* @param applicationRelease Application Release Object. * @param applicationRelease Application Release Object.
* @param binaryFile Binary File for the release. * @param binaryFile Binary File for the release.
* @throws ResourceManagementException Resource Management Exception. * @throws ResourceManagementException Resource Management Exception.
*/ */
ApplicationRelease uploadReleaseArtifacts(int applicationId, ApplicationRelease applicationRelease, InputStream binaryFile) ApplicationRelease uploadReleaseArtifacts(ApplicationRelease applicationRelease, InputStream binaryFile)
throws ResourceManagementException; throws ResourceManagementException;
/** /**

@ -151,7 +151,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
applicationRelease.setCreatedAt(resultSet.getTimestamp("CREATED_AT")); applicationRelease.setCreatedAt(resultSet.getTimestamp("CREATED_AT"));
applicationRelease.setPublishedBy(resultSet.getString("PUBLISHED_BY")); applicationRelease.setPublishedBy(resultSet.getString("PUBLISHED_BY"));
applicationRelease.setPublishedAt(resultSet.getTimestamp("PUBLISHED_AT")); applicationRelease.setPublishedAt(resultSet.getTimestamp("PUBLISHED_AT"));
applicationRelease.setStarts(resultSet.getInt("STARS")); applicationRelease.setStars(resultSet.getInt("STARS"));
applicationRelease.setCurrentState(resultSet.getString("CURRENT_STATE")); applicationRelease.setCurrentState(resultSet.getString("CURRENT_STATE"));
applicationRelease.setPreviousState(resultSet.getString("PREVIOUSE_STATE")); applicationRelease.setPreviousState(resultSet.getString("PREVIOUSE_STATE"));
applicationRelease.setStateModifiedBy(resultSet.getString("UPDATED_BY")); applicationRelease.setStateModifiedBy(resultSet.getString("UPDATED_BY"));
@ -221,11 +221,8 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
applicationRelease.setCreatedAt(resultSet.getTimestamp("CREATED_AT")); applicationRelease.setCreatedAt(resultSet.getTimestamp("CREATED_AT"));
applicationRelease.setPublishedBy(resultSet.getString("PUBLISHED_BY")); applicationRelease.setPublishedBy(resultSet.getString("PUBLISHED_BY"));
applicationRelease.setPublishedAt(resultSet.getTimestamp("PUBLISHED_AT")); applicationRelease.setPublishedAt(resultSet.getTimestamp("PUBLISHED_AT"));
applicationRelease.setStarts(resultSet.getInt("STARS")); applicationRelease.setStars(resultSet.getInt("STARS"));
if ("REMOVED".equals(ApplicationManagementDAOFactory.getLifecycleStateDAO(). applicationReleases.add(applicationRelease);
getLatestLifeCycleStateByReleaseID(applicationRelease.getId()).getCurrentState())){
applicationReleases.add(applicationRelease);
}
} }
return applicationReleases; return applicationReleases;

@ -30,6 +30,7 @@ import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO; import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO; import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.exception.ValidationException; import org.wso2.carbon.device.application.mgt.core.exception.ValidationException;
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.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
@ -39,7 +40,10 @@ import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.sql.Timestamp;
import java.util.Date;
/** /**
* Default Concrete implementation of Application Management related implementations. * Default Concrete implementation of Application Management related implementations.
@ -52,9 +56,8 @@ public class ApplicationManagerImpl implements ApplicationManager {
private LifecycleStateDAO lifecycleStateDAO; private LifecycleStateDAO lifecycleStateDAO;
private ApplicationDAO applicationDAO; private ApplicationDAO applicationDAO;
public ApplicationManagerImpl(){ public ApplicationManagerImpl() {
initDataAccessObjects(); initDataAccessObjects();
} }
private void initDataAccessObjects() { private void initDataAccessObjects() {
@ -62,11 +65,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO(); this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
this.lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO(); this.lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
} }
@Override @Override public Application createApplication(Application application) throws ApplicationManagementException {
public Application createApplication(Application application) throws ApplicationManagementException {
User loggedInUser = new User(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(), User loggedInUser = new User(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(),
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)); PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true));
@ -76,33 +77,40 @@ public class ApplicationManagerImpl implements ApplicationManager {
+ " the user : " + application.getUser().getUserName()); + " the user : " + application.getUser().getUserName());
} }
validateApplication(application); validateAppCreatingRequest(application);
validateReleaseCreateRequest(application.getApplicationReleases());
DeviceType deviceType; DeviceType deviceType;
ApplicationRelease applicationRelease;
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
int tenantId = application.getUser().getTenantId(); int tenantId = application.getUser().getTenantId();
deviceType = this.deviceTypeDAO.getDeviceType(application.getType(), application.getUser().getTenantId()); deviceType = this.deviceTypeDAO.getDeviceType(application.getType(), application.getUser().getTenantId());
if (deviceType == null){ if (deviceType == null) {
log.error("Device type is not matched with application type"); log.error("Device type is not matched with application type");
return null; return null;
} }
application.setDevicetype(deviceType); application.setDevicetype(deviceType);
int appId = this.applicationDAO.createApplication(application, deviceType.getId()); int appId = this.applicationDAO.createApplication(application, deviceType.getId());
if (appId != -1){ if (appId != -1) {
log.error("Application creation Failed"); log.error("Application creation Failed");
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
}else{ } else {
if (!application.getTags().isEmpty()){ if (!application.getTags().isEmpty()) {
this.applicationDAO.addTags(application.getTags(), appId, tenantId); this.applicationDAO.addTags(application.getTags(), appId, tenantId);
} }
if (application.getIsRestricted() == 1 && !application.getUnrestrictedRoles().isEmpty()){ if (application.getIsRestricted() == 1 && !application.getUnrestrictedRoles().isEmpty()) {
this.visibilityDAO.addUnrestrictedRoles(application.getUnrestrictedRoles(), appId, tenantId); this.visibilityDAO.addUnrestrictedRoles(application.getUnrestrictedRoles(), appId, tenantId);
}else{ } else {
application.setIsRestricted(0); application.setIsRestricted(0);
} }
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
applicationRelease = application.getApplicationReleases().get(0);
applicationRelease.setCreatedAt((Timestamp) new Date());
applicationRelease = ApplicationManagementDAOFactory.getApplicationReleaseDAO().
createRelease(applicationRelease, application.getId());
//todo add lifecycle and add this into application
} }
return application; return application;
@ -112,145 +120,50 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg, e); log.error(msg, e);
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch(ApplicationManagementException e){ } catch (ApplicationManagementException e) {
String msg = "Error occurred while adding application"; String msg = "Error occurred while adding application";
log.error(msg, e); log.error(msg, e);
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
}finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
@Override @Override public ApplicationList getApplications(Filter filter) throws ApplicationManagementException {
public Application editApplication(Application application) throws ApplicationManagementException {
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// if (application.getUuid() == null) {
// throw new ValidationException("Application UUID cannot be empty");
// }
//
// if (!isApplicationOwnerOrAdmin(application.getUuid(), userName, tenantId)) {
// throw new ApplicationManagementException(
// "User " + userName + " does not have permissions to edit the " + "application with the UUID "
// + application.getUuid());
// }
// if (this.getApplication(application.getUuid()) != null) {
// if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) {
// throw new NotFoundException("Platform information not available with the application!");
// }
// Platform platform = DataHolder.getInstance().getPlatformManager()
// .getPlatform(tenantId, application.getPlatform().getIdentifier());
// if (platform == null) {
// throw new NotFoundException(
// "Platform specified by identifier " + application.getPlatform().getIdentifier()
// + " is not found. Please give a valid platform identifier.");
// }
// application.setPlatform(platform);
// if (application.getCategory() != null) {
// String applicationCategoryName = application.getCategory().getName();
// if (applicationCategoryName == null || applicationCategoryName.isEmpty()) {
// throw new ApplicationManagementException(
// "Application category name cannot be null or " + "empty. Cannot edit the application.");
// }
// Category category = DataHolder.getInstance().getCategoryManager()
// .getCategory(application.getCategory().getName());
// if (category == null) {
// throw new NotFoundException(
// "Invalid Category is provided for the application " + application.getUuid() + ". "
// + "Cannot edit application");
// }
// application.setCategory(category);
// }
// try {
// ConnectionManagerUtil.beginDBTransaction();
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// application.setModifiedAt(new Date());
// Application modifiedApplication = applicationDAO.editApplication(application, tenantId);
// Visibility visibility = DataHolder.getInstance().getVisibilityManager()
// .put(application.getId(), application.getVisibility());
// modifiedApplication.setVisibility(visibility);
// ConnectionManagerUtil.commitDBTransaction();
// return modifiedApplication;
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw e;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
// } else {
// throw new NotFoundException("No applications found with application UUID - " + application.getUuid());
// }
return application;
}
@Override
public void deleteApplication(String uuid) throws ApplicationManagementException {
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// if (!isApplicationOwnerOrAdmin(uuid, userName, tenantId)) {
// throw new ApplicationManagementException("User '" + userName + "' of tenant - " + tenantId + " does have"
// + " the permission to delete the application with UUID " + uuid);
// }
// try {
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// ConnectionManagerUtil.beginDBTransaction();
// int appId = applicationDAO.getApplicationId(uuid, tenantId);
// if (appId != -1) {
// applicationDAO.deleteTags(appId);
// applicationDAO.deleteProperties(appId);
// DataHolder.getInstance().getVisibilityManager().remove(appId);
// applicationDAO.deleteApplication(uuid, tenantId);
// }
// ConnectionManagerUtil.commitDBTransaction();
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// String msg = "Failed to delete application: " + uuid;
// throw new ApplicationManagementException(msg, e);
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override
public ApplicationList getApplications(Filter filter) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
ApplicationList roleRestrictedApplicationList = new ApplicationList(); ApplicationList applicationList;
ApplicationList applicationList ; List<ApplicationRelease> applicationReleases;
try { try {
filter.setUserName(userName); filter.setUserName(userName);
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
applicationList = applicationDAO.getApplications(filter, tenantId); applicationList = applicationDAO.getApplications(filter, tenantId);
if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
return applicationList; applicationList = getRoleRestrictedApplicationList(applicationList, userName);
} }
for (Application application : applicationList.getApplications()) { for (Application application : applicationList.getApplications()) {
if (application.getUnrestrictedRoles().isEmpty()){ applicationReleases = getReleases(application.getId());
roleRestrictedApplicationList.getApplications().add(application); application.setApplicationReleases(applicationReleases);
}else{
if (isRoleExists(application.getUnrestrictedRoles(), userName)){
roleRestrictedApplicationList.getApplications().add(application);
}
}
} }
return roleRestrictedApplicationList;
}catch (UserStoreException e) { return applicationList;
throw new ApplicationManagementException("User-store exception while checking whether the user " + } catch (UserStoreException e) {
userName + " of tenant " + tenantId + " has the publisher permission"); throw new ApplicationManagementException(
} "User-store exception while checking whether the user " + userName + " of tenant " + tenantId
finally { + " has the publisher permission");
} finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
@Override @Override public String getUuidOfLatestRelease(int appId) throws ApplicationManagementException {
public String getUuidOfLatestRelease(int appId) throws ApplicationManagementException {
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
return applicationDAO.getUuidOfLatestRelease(appId); return applicationDAO.getUuidOfLatestRelease(appId);
}finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -276,173 +189,82 @@ public class ApplicationManagerImpl implements ApplicationManager {
if (userRealm != null) { if (userRealm != null) {
roleList = userRealm.getUserStoreManager().getRoleListOfUser(userName); roleList = userRealm.getUserStoreManager().getRoleListOfUser(userName);
} else { } else {
log.error("role list is empty of user :"+ userName); log.error("role list is empty of user :" + userName);
} }
return roleList; return roleList;
} }
@Override public Application getApplication(String appType, String appName) throws ApplicationManagementException {
@Override
public void changeLifecycle(String applicationUuid, String lifecycleIdentifier) throws
ApplicationManagementException {
// boolean isAvailableNextState = false;
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// List<LifecycleStateTransition> nextLifeCycles = getLifeCycleStates(applicationUuid);
//
// for (LifecycleStateTransition lifecycleStateTransition : nextLifeCycles) {
// if (log.isDebugEnabled()) {
// log.debug("Lifecycle state of the application " + applicationUuid + " can be changed to"
// + lifecycleStateTransition.getNextState());
// }
// if (lifecycleStateTransition.getNextState().equalsIgnoreCase(lifecycleIdentifier)) {
// isAvailableNextState = true;
// break;
// }
// }
// if (!isAvailableNextState) {
// throw new ApplicationManagementException("User " + userName + " does not have the permission to change "
// + "the lifecycle state of the application " + applicationUuid + " to lifecycle state "
// + lifecycleIdentifier);
// }
// try {
// ConnectionManagerUtil.beginDBTransaction();
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// applicationDAO.changeLifecycle(applicationUuid, lifecycleIdentifier, userName, tenantId);
// ConnectionManagerUtil.commitDBTransaction();
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw e;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override
public List<LifecycleStateTransition> getLifeCycleStates(String applicationUUID)
throws ApplicationManagementException {
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// boolean isAdminOrApplicationOwner = isApplicationOwnerOrAdmin(applicationUUID, userName, tenantId);
//
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " in tenant " + tenantId + " is an Admin or Application owner of the "
// + "application " + applicationUUID);
// }
// try {
// ConnectionManagerUtil.openDBConnection();
// List<LifecycleStateTransition> transitions = ApplicationManagementDAOFactory.getApplicationDAO()
// .getNextLifeCycleStates(applicationUUID, tenantId);
// List<LifecycleStateTransition> filteredTransitions = new ArrayList<>();
//
// if (log.isDebugEnabled()) {
// log.debug("Lifecycle of the application with UUID : " + applicationUUID + " can be changed to "
// + transitions.size() + ". The number may vary according to the permission level of user : "
// + userName + " of tenant " + tenantId);
// }
// for (LifecycleStateTransition transition : transitions) {
// String permission = transition.getPermission();
// if (permission != null) {
// if (log.isDebugEnabled()) {
// log.debug("In order to make the state change to " + transition.getNextState() + " permission "
// + permission + " is required");
// }
// if (isAdminUser(userName, tenantId, permission)) {
// filteredTransitions.add(transition);
// } else {
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " does not have the permission " + permission + " to "
// + "change the life-cycle state to " + transition.getNextState() + " of the "
// + "application " + applicationUUID);
// }
// }
// } else if (isAdminOrApplicationOwner) {
// filteredTransitions.add(transition);
// }
// }
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " can do " + filteredTransitions.size() + " life-cyle state changes "
// + "currently on application with the UUID " + applicationUUID);
// }
// return filteredTransitions;
// } catch (UserStoreException e) {
// throw new ApplicationManagementException(
// "Userstore exception while checking whether user " + userName + " from tenant " + tenantId
// + " is authorized to do a life-cycle status change in an application ", e);
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
return null;
}
@Override
public Application getApplication(String appType, String appName) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Application application; Application application;
boolean isAppAllowed = false; boolean isAppAllowed = false;
List<ApplicationRelease> applicationReleases;
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
application = ApplicationManagementDAOFactory.getApplicationDAO().getApplication(appType, appName, tenantId); application = ApplicationManagementDAOFactory.getApplicationDAO()
.getApplication(appType, appName, tenantId);
if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
return application; return application;
} }
if (!application.getUnrestrictedRoles().isEmpty()) { if (!application.getUnrestrictedRoles().isEmpty()) {
if(isRoleExists(application.getUnrestrictedRoles(), userName)){ if (isRoleExists(application.getUnrestrictedRoles(), userName)) {
isAppAllowed = true ; isAppAllowed = true;
} }
} else { } else {
isAppAllowed = true; isAppAllowed = true;
} }
if (!isAppAllowed){ if (!isAppAllowed) {
return null; return null;
} }
applicationReleases = getReleases(application.getId());
application.setApplicationReleases(applicationReleases);
return application; return application;
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new ApplicationManagementException("User-store exception while getting application with the " throw new ApplicationManagementException(
+ "application name " + appName); "User-store exception while getting application with the " + "application name " + appName);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
@Override @Override public Application getApplicationById(int applicationId) throws ApplicationManagementException {
public Application getApplicationById(int applicationId) throws ApplicationManagementException{
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Application application; Application application;
boolean isAppAllowed = false; boolean isAppAllowed = false;
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
application = ApplicationManagementDAOFactory.getApplicationDAO().getApplicationById(applicationId, tenantId); application = ApplicationManagementDAOFactory.getApplicationDAO()
.getApplicationById(applicationId, tenantId);
if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
return application; return application;
} }
if (!application.getUnrestrictedRoles().isEmpty()) { if (!application.getUnrestrictedRoles().isEmpty()) {
if(isRoleExists(application.getUnrestrictedRoles(), userName)){ if (isRoleExists(application.getUnrestrictedRoles(), userName)) {
isAppAllowed = true ; isAppAllowed = true;
} }
} else { } else {
isAppAllowed = true; isAppAllowed = true;
} }
if (!isAppAllowed){ if (!isAppAllowed) {
return null; return null;
} }
return application; return application;
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new ApplicationManagementException("User-store exception while getting application with the " throw new ApplicationManagementException(
+ "application id " + applicationId); "User-store exception while getting application with the " + "application id " + applicationId);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
public Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException {
public Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException{
try { try {
Boolean isAppExist; Boolean isAppExist;
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
@ -453,15 +275,41 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
public Boolean isUserAllowable(List<UnrestrictedRole> unrestrictedRoles, String userName) throws ApplicationManagementException{ public Boolean isUserAllowable(List<UnrestrictedRole> unrestrictedRoles, String userName)
throws ApplicationManagementException {
try { try {
return isRoleExists(unrestrictedRoles, userName); return isRoleExists(unrestrictedRoles, userName);
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new ApplicationManagementException("User-store exception while verifying whether user have assigned" throw new ApplicationManagementException(
+ "unrestricted roles or not"); } "User-store exception while verifying whether user have assigned" + "unrestricted roles or not");
}
} }
@Override public List<ApplicationRelease> getReleases(int applicationId) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
Application application = validateApplication(applicationId);
List<ApplicationRelease> applicationReleases;
List<ApplicationRelease> filteredApplicationReleases = new ArrayList<>();
if (log.isDebugEnabled()) {
log.debug("Request is received to retrieve all the releases related with the application " + application
.toString());
}
try {
ConnectionManagerUtil.openDBConnection();
applicationReleases = ApplicationManagementDAOFactory.getApplicationReleaseDAO()
.getApplicationReleases(application.getName(), application.getType(), tenantId);
for (ApplicationRelease applicationRelease : applicationReleases) {
if (!"REMOVED".equals(ApplicationManagementDAOFactory.getLifecycleStateDAO().
getLatestLifeCycleStateByReleaseID(applicationRelease.getId()).getCurrentState())) {
filteredApplicationReleases.add(applicationRelease);
}
}
return filteredApplicationReleases;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
/** /**
* To check whether current user is application owner or admin. * To check whether current user is application owner or admin.
@ -472,22 +320,22 @@ public class ApplicationManagerImpl implements ApplicationManager {
*/ */
private boolean isApplicationOwnerOrAdmin(String applicationUUID, String userName, int tenantId) private boolean isApplicationOwnerOrAdmin(String applicationUUID, String userName, int tenantId)
throws ApplicationManagementException { throws ApplicationManagementException {
// try { // try {
// if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { // if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
// return true; // return true;
// } // }
// } catch (UserStoreException e) { // } catch (UserStoreException e) {
// throw new ApplicationManagementException("Userstore exception while checking whether user is an admin", e); // throw new ApplicationManagementException("Userstore exception while checking whether user is an admin", e);
// } // }
// try { // try {
// ConnectionManagerUtil.openDBConnection(); // ConnectionManagerUtil.openDBConnection();
// Application application = ApplicationManagementDAOFactory.getApplicationDAO() // Application application = ApplicationManagementDAOFactory.getApplicationDAO()
// .getApplication(applicationUUID, tenantId, userName); // .getApplication(applicationUUID, tenantId, userName);
// return application.getUser().getUserName().equals(userName) // return application.getUser().getUserName().equals(userName)
// && application.getUser().getTenantId() == tenantId; // && application.getUser().getTenantId() == tenantId;
// } finally { // } finally {
// ConnectionManagerUtil.closeDBConnection(); // ConnectionManagerUtil.closeDBConnection();
// } // }
return false; return false;
} }
@ -503,8 +351,8 @@ public class ApplicationManagerImpl implements ApplicationManager {
private boolean isAdminUser(String username, int tenantId, String permission) throws UserStoreException { private boolean isAdminUser(String username, int tenantId, String permission) throws UserStoreException {
UserRealm userRealm = DataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); UserRealm userRealm = DataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
return userRealm != null && userRealm.getAuthorizationManager() != null && userRealm.getAuthorizationManager() return userRealm != null && userRealm.getAuthorizationManager() != null && userRealm.getAuthorizationManager()
.isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), .isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission,
permission, CarbonConstants.UI_PERMISSION_ACTION); CarbonConstants.UI_PERMISSION_ACTION);
} }
/** /**
@ -513,13 +361,13 @@ public class ApplicationManagerImpl implements ApplicationManager {
* @param application Application that need to be created * @param application Application that need to be created
* @throws ValidationException Validation Exception * @throws ValidationException Validation Exception
*/ */
private void validateApplication(Application application) throws ValidationException { private void validateAppCreatingRequest(Application application) throws ValidationException {
if (application.getName() == null) { if (application.getName() == null) {
throw new ValidationException("Application name cannot be empty"); throw new ValidationException("Application name cannot be empty");
} }
if (application.getUser() == null || application.getUser().getUserName() == null || if (application.getUser() == null || application.getUser().getUserName() == null
application.getUser().getTenantId() == 0) { || application.getUser().getTenantId() == 0) {
throw new ValidationException("Username and tenant Id cannot be empty"); throw new ValidationException("Username and tenant Id cannot be empty");
} }
if (application.getAppCategory() == null) { if (application.getAppCategory() == null) {
@ -528,8 +376,8 @@ public class ApplicationManagerImpl implements ApplicationManager {
try { try {
validateApplicationExistence(application); validateApplicationExistence(application);
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
throw new ValidationException("Error occured while validating whether there is already an application " + throw new ValidationException("Error occured while validating whether there is already an application "
"registered with same name.", e); + "registered with same name.", e);
} }
} }
@ -541,10 +389,264 @@ public class ApplicationManagerImpl implements ApplicationManager {
filter.setLimit(1); filter.setLimit(1);
ApplicationList applicationList = getApplications(filter); ApplicationList applicationList = getApplications(filter);
if (applicationList != null && applicationList.getApplications() != null && if (applicationList != null && applicationList.getApplications() != null && !applicationList.getApplications()
!applicationList.getApplications().isEmpty()) { .isEmpty()) {
throw new ValidationException("Already an application registered with same name - " throw new ValidationException(
+ applicationList.getApplications().get(0).getName()); "Already an application registered with same name - " + applicationList.getApplications().get(0)
.getName());
} }
} }
/**
* To validate the pre-request of the ApplicationRelease.
*
* @param applicationID ID of the Application.
* @return Application related with the UUID
*/
private Application validateApplication(int applicationID) throws ApplicationManagementException {
if (applicationID <= 0) {
throw new ApplicationManagementException("Application UUID is null. Application UUID is a required "
+ "parameter to get the relevant application.");
}
Application application = DataHolder.getInstance().getApplicationManager().getApplicationById(applicationID);
if (application == null) {
throw new NotFoundException("Application of the " + applicationID + " does not exist.");
}
return application;
}
/**
* To get role restricted application list.
*
* @param applicationList list of applications.
* @param userName user name
* @return Application related with the UUID
*/
private ApplicationList getRoleRestrictedApplicationList(ApplicationList applicationList, String userName)
throws ApplicationManagementException {
ApplicationList roleRestrictedApplicationList = new ApplicationList();
ArrayList<Application> unRestrictedApplications = new ArrayList<>();
for (Application application : applicationList.getApplications()) {
if (application.getUnrestrictedRoles().isEmpty()) {
unRestrictedApplications.add(application);
} else {
try {
if (isRoleExists(application.getUnrestrictedRoles(), userName)) {
unRestrictedApplications.add(application);
}
} catch (UserStoreException e) {
throw new ApplicationManagementException("Role restriction verifying is failed");
}
}
}
roleRestrictedApplicationList.setApplications(unRestrictedApplications);
return roleRestrictedApplicationList;
}
/**
* To validate a create release request to make sure all the pre-conditions satisfied.
*
* @param applicationReleases ApplicationRelease that need to be created.
* @throws ApplicationManagementException Application Management Exception.
*/
private void validateReleaseCreateRequest(List<ApplicationRelease> applicationReleases)
throws ApplicationManagementException {
if (applicationReleases.isEmpty() || applicationReleases.size() > 1) {
throw new ApplicationManagementException("ApplicationRelease size is grater than minimal release size or "
+ "request doesn't contains application release");
}
if (applicationReleases.get(0).getVersion() == null) {
throw new ApplicationManagementException("ApplicationRelease version name is a mandatory parameter for "
+ "creating release. It cannot be found.");
}
//todo
// if (getRelease(applicationReleases.get(0).getUuid(), applicationReleases.get(0).getVersion(),
// applicationReleases.get(0).getReleaseType()) != null) {
// throw new ApplicationManagementException( "Application Release for the Application UUID " +
// applicationReleases.get(0).getUuid() + " " + "with the version "
// + applicationReleases.get(0).getVersion() + " already exists. Cannot create an " +
// "application release with the same version.");
// }
}
@Override public Application editApplication(Application application) throws ApplicationManagementException {
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// if (application.getUuid() == null) {
// throw new ValidationException("Application UUID cannot be empty");
// }
//
// if (!isApplicationOwnerOrAdmin(application.getUuid(), userName, tenantId)) {
// throw new ApplicationManagementException(
// "User " + userName + " does not have permissions to edit the " + "application with the UUID "
// + application.getUuid());
// }
// if (this.getApplication(application.getUuid()) != null) {
// if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) {
// throw new NotFoundException("Platform information not available with the application!");
// }
// Platform platform = DataHolder.getInstance().getPlatformManager()
// .getPlatform(tenantId, application.getPlatform().getIdentifier());
// if (platform == null) {
// throw new NotFoundException(
// "Platform specified by identifier " + application.getPlatform().getIdentifier()
// + " is not found. Please give a valid platform identifier.");
// }
// application.setPlatform(platform);
// if (application.getCategory() != null) {
// String applicationCategoryName = application.getCategory().getName();
// if (applicationCategoryName == null || applicationCategoryName.isEmpty()) {
// throw new ApplicationManagementException(
// "Application category name cannot be null or " + "empty. Cannot edit the application.");
// }
// Category category = DataHolder.getInstance().getCategoryManager()
// .getCategory(application.getCategory().getName());
// if (category == null) {
// throw new NotFoundException(
// "Invalid Category is provided for the application " + application.getUuid() + ". "
// + "Cannot edit application");
// }
// application.setCategory(category);
// }
// try {
// ConnectionManagerUtil.beginDBTransaction();
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// application.setModifiedAt(new Date());
// Application modifiedApplication = applicationDAO.editApplication(application, tenantId);
// Visibility visibility = DataHolder.getInstance().getVisibilityManager()
// .put(application.getId(), application.getVisibility());
// modifiedApplication.setVisibility(visibility);
// ConnectionManagerUtil.commitDBTransaction();
// return modifiedApplication;
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw e;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
// } else {
// throw new NotFoundException("No applications found with application UUID - " + application.getUuid());
// }
return application;
}
@Override public void deleteApplication(String uuid) throws ApplicationManagementException {
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// if (!isApplicationOwnerOrAdmin(uuid, userName, tenantId)) {
// throw new ApplicationManagementException("User '" + userName + "' of tenant - " + tenantId + " does have"
// + " the permission to delete the application with UUID " + uuid);
// }
// try {
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// ConnectionManagerUtil.beginDBTransaction();
// int appId = applicationDAO.getApplicationId(uuid, tenantId);
// if (appId != -1) {
// applicationDAO.deleteTags(appId);
// applicationDAO.deleteProperties(appId);
// DataHolder.getInstance().getVisibilityManager().remove(appId);
// applicationDAO.deleteApplication(uuid, tenantId);
// }
// ConnectionManagerUtil.commitDBTransaction();
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// String msg = "Failed to delete application: " + uuid;
// throw new ApplicationManagementException(msg, e);
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override public void changeLifecycle(String applicationUuid, String lifecycleIdentifier)
throws ApplicationManagementException {
// boolean isAvailableNextState = false;
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// List<LifecycleStateTransition> nextLifeCycles = getLifeCycleStates(applicationUuid);
//
// for (LifecycleStateTransition lifecycleStateTransition : nextLifeCycles) {
// if (log.isDebugEnabled()) {
// log.debug("Lifecycle state of the application " + applicationUuid + " can be changed to"
// + lifecycleStateTransition.getNextState());
// }
// if (lifecycleStateTransition.getNextState().equalsIgnoreCase(lifecycleIdentifier)) {
// isAvailableNextState = true;
// break;
// }
// }
// if (!isAvailableNextState) {
// throw new ApplicationManagementException("User " + userName + " does not have the permission to change "
// + "the lifecycle state of the application " + applicationUuid + " to lifecycle state "
// + lifecycleIdentifier);
// }
// try {
// ConnectionManagerUtil.beginDBTransaction();
// ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
// applicationDAO.changeLifecycle(applicationUuid, lifecycleIdentifier, userName, tenantId);
// ConnectionManagerUtil.commitDBTransaction();
// } catch (ApplicationManagementDAOException e) {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw e;
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
}
@Override public List<LifecycleStateTransition> getLifeCycleStates(String applicationUUID)
throws ApplicationManagementException {
// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
// String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
// boolean isAdminOrApplicationOwner = isApplicationOwnerOrAdmin(applicationUUID, userName, tenantId);
//
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " in tenant " + tenantId + " is an Admin or Application owner of the "
// + "application " + applicationUUID);
// }
// try {
// ConnectionManagerUtil.openDBConnection();
// List<LifecycleStateTransition> transitions = ApplicationManagementDAOFactory.getApplicationDAO()
// .getNextLifeCycleStates(applicationUUID, tenantId);
// List<LifecycleStateTransition> filteredTransitions = new ArrayList<>();
//
// if (log.isDebugEnabled()) {
// log.debug("Lifecycle of the application with UUID : " + applicationUUID + " can be changed to "
// + transitions.size() + ". The number may vary according to the permission level of user : "
// + userName + " of tenant " + tenantId);
// }
// for (LifecycleStateTransition transition : transitions) {
// String permission = transition.getPermission();
// if (permission != null) {
// if (log.isDebugEnabled()) {
// log.debug("In order to make the state change to " + transition.getNextState() + " permission "
// + permission + " is required");
// }
// if (isAdminUser(userName, tenantId, permission)) {
// filteredTransitions.add(transition);
// } else {
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " does not have the permission " + permission + " to "
// + "change the life-cycle state to " + transition.getNextState() + " of the "
// + "application " + applicationUUID);
// }
// }
// } else if (isAdminOrApplicationOwner) {
// filteredTransitions.add(transition);
// }
// }
// if (log.isDebugEnabled()) {
// log.debug("User " + userName + " can do " + filteredTransitions.size() + " life-cyle state changes "
// + "currently on application with the UUID " + applicationUUID);
// }
// return filteredTransitions;
// } catch (UserStoreException e) {
// throw new ApplicationManagementException(
// "Userstore exception while checking whether user " + userName + " from tenant " + tenantId
// + " is authorized to do a life-cycle status change in an application ", e);
// } finally {
// ConnectionManagerUtil.closeDBConnection();
// }
return null;
}
} }

@ -67,8 +67,8 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
} }
@Override @Override
public ApplicationRelease uploadImageArtifacts(int applicationId, ApplicationRelease applicationRelease, public ApplicationRelease uploadImageArtifacts(ApplicationRelease applicationRelease, InputStream iconFileStream,
InputStream iconFileStream, InputStream bannerFileStream, List<InputStream> screenShotStreams) throws ResourceManagementException { InputStream bannerFileStream,List<InputStream> screenShotStreams) throws ResourceManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String artifactDirectoryPath = null; String artifactDirectoryPath = null;
@ -77,56 +77,53 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
String scStoredLocation; String scStoredLocation;
try { try {
if (validateApplication(applicationId)) {
artifactDirectoryPath = storagePath + applicationRelease.getAppHashValue();
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
}
if (artifactDirectoryPath != null) {
iconStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[0]; artifactDirectoryPath = storagePath + applicationRelease.getAppHashValue();
bannerStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[1]; StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
iconStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[0];
bannerStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[1];
if (iconFileStream != null){ if (iconFileStream != null){
saveFile(iconFileStream, iconStoredLocation); saveFile(iconFileStream, iconStoredLocation);
applicationRelease.setIconLoc(iconStoredLocation); applicationRelease.setIconLoc(iconStoredLocation);
} }
if (bannerFileStream != null){ if (bannerFileStream != null){
saveFile(bannerFileStream, bannerStoredLocation); saveFile(bannerFileStream, bannerStoredLocation);
applicationRelease.setBannerLoc(bannerStoredLocation); applicationRelease.setBannerLoc(bannerStoredLocation);
} }
if (screenShotStreams.size() > screenShotMaxCount) { if (screenShotStreams.size() > screenShotMaxCount) {
throw new ApplicationStorageManagementException("Maximum limit for the screen-shot exceeds"); throw new ApplicationStorageManagementException("Maximum limit for the screen-shot exceeds");
}else if(!screenShotStreams.isEmpty() && screenShotStreams.size() <= screenShotMaxCount){ }else if(!screenShotStreams.isEmpty() && screenShotStreams.size() <= screenShotMaxCount){
int count = 1; int count = 1;
for (InputStream screenshotStream : screenShotStreams) { for (InputStream screenshotStream : screenShotStreams) {
scStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[2] + count; scStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[2] + count;
if (count == 1) { if (count == 1) {
applicationRelease.setScreenshotLoc1(scStoredLocation); applicationRelease.setScreenshotLoc1(scStoredLocation);
} }
if (count == 2) { if (count == 2) {
applicationRelease.setScreenshotLoc2(scStoredLocation); applicationRelease.setScreenshotLoc2(scStoredLocation);
} }
if (count == 3) { if (count == 3) {
applicationRelease.setScreenshotLoc3(scStoredLocation); applicationRelease.setScreenshotLoc3(scStoredLocation);
}
saveFile(screenshotStream, scStoredLocation);
count++;
} }
saveFile(screenshotStream, scStoredLocation);
count++;
} }
} }
return applicationRelease; return applicationRelease;
} catch (IOException e) { } catch (IOException e) {
throw new ApplicationStorageManagementException( throw new ApplicationStorageManagementException(
"IO Exception while saving the screens hots for the " + "application " + applicationId, e); "IO Exception while saving the screens hots for the " + "application " +
applicationRelease.getUuid(), e);
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationStorageManagementException("Application Management DAO exception while trying to " throw new ApplicationStorageManagementException("Application Management DAO exception while trying to "
+ "update the screen-shot count for the application " + applicationId + " for the tenant id " + "update the screen-shot count for the application " + applicationRelease.getUuid() +
+ tenantId, e); " for the tenant id " + tenantId, e);
} }
} }
@ -140,7 +137,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
try { try {
ApplicationRelease applicationRelease = validateApplicationRelease(uuid); ApplicationRelease applicationRelease = validateApplicationRelease(uuid);
applicationRelease = uploadImageArtifacts(applicationId, applicationRelease, iconFileStream, bannerFileStream, screenShotStreams); applicationRelease = uploadImageArtifacts(applicationRelease, iconFileStream, bannerFileStream, screenShotStreams);
return applicationRelease; return applicationRelease;
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
@ -157,7 +154,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
} }
@Override @Override
public ApplicationRelease uploadReleaseArtifacts(int applicationId, ApplicationRelease applicationRelease , InputStream binaryFile) public ApplicationRelease uploadReleaseArtifacts(ApplicationRelease applicationRelease , InputStream binaryFile)
throws ResourceManagementException { throws ResourceManagementException {
String artifactDirectoryPath; String artifactDirectoryPath;
@ -165,12 +162,12 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
md5OfApp = getMD5(binaryFile); md5OfApp = getMD5(binaryFile);
//todo validate binary file. //todo validate binary file.
if(validateApplication(applicationId) && md5OfApp != null){ if(md5OfApp != null){
artifactDirectoryPath = storagePath + md5OfApp; artifactDirectoryPath = storagePath + md5OfApp;
StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath); StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Artifact Directory Path for saving the application release related artifacts related with " log.debug("Artifact Directory Path for saving the application release related artifacts related with "
+ "application ID " + applicationId + " is " + artifactDirectoryPath); + "application UUID " + applicationRelease.getUuid() + " is " + artifactDirectoryPath);
} }
try { try {
saveFile(binaryFile, artifactDirectoryPath); saveFile(binaryFile, artifactDirectoryPath);
@ -178,8 +175,8 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
applicationRelease.setAppHashValue(md5OfApp); applicationRelease.setAppHashValue(md5OfApp);
} catch (IOException e) { } catch (IOException e) {
throw new ApplicationStorageManagementException( throw new ApplicationStorageManagementException(
"IO Exception while saving the release artifacts in the server for the application " "IO Exception while saving the release artifacts in the server for the application UUID "
+ applicationId, e); + applicationRelease.getUuid(), e);
} }
}else{ }else{
@ -198,7 +195,7 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
ApplicationRelease applicationRelease = null; ApplicationRelease applicationRelease = null;
try { try {
applicationRelease = validateApplicationRelease(applicationUuid); applicationRelease = validateApplicationRelease(applicationUuid);
applicationRelease = uploadReleaseArtifacts(applicationId, applicationRelease,binaryFile); applicationRelease = uploadReleaseArtifacts(applicationRelease,binaryFile);
return applicationRelease; return applicationRelease;
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
throw new ApplicationStorageManagementException("Application Management exception while trying to" throw new ApplicationStorageManagementException("Application Management exception while trying to"
@ -213,38 +210,38 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
throws ApplicationStorageManagementException { throws ApplicationStorageManagementException {
return null; return null;
// todo this should be validate application release // todo this should be validate application release
// Application application = validateApplication(applicationUUID); // Application application = validateApplication(applicationUUID);
// String artifactPath = storagePath + application.getId() + File.separator + versionName; // String artifactPath = storagePath + application.getId() + File.separator + versionName;
// //
// if (log.isDebugEnabled()) { // if (log.isDebugEnabled()) {
// log.debug("ApplicationRelease artifacts are searched in the location " + artifactPath); // log.debug("ApplicationRelease artifacts are searched in the location " + artifactPath);
// } // }
// //
// File binaryFile = new File(artifactPath); // File binaryFile = new File(artifactPath);
// //
// if (!binaryFile.exists()) { // if (!binaryFile.exists()) {
// throw new ApplicationStorageManagementException("Binary file does not exist for this release"); // throw new ApplicationStorageManagementException("Binary file does not exist for this release");
// } else { // } else {
// try { // try {
// return new FileInputStream(artifactPath); // return new FileInputStream(artifactPath);
// } catch (FileNotFoundException e) { // } catch (FileNotFoundException e) {
// throw new ApplicationStorageManagementException( // throw new ApplicationStorageManagementException(
// "Binary file does not exist for the version " + versionName + " for the application ", e); // "Binary file does not exist for the version " + versionName + " for the application ", e);
// } // }
// } // }
} }
//todo //todo
@Override @Override
public void deleteApplicationArtifacts(String applicationUUID) throws ApplicationStorageManagementException { public void deleteApplicationArtifacts(String applicationUUID) throws ApplicationStorageManagementException {
// todo this should be validate application release // todo this should be validate application release
// Application application = validateApplication(applicationUUID); // Application application = validateApplication(applicationUUID);
// String artifactDirectoryPath = storagePath + application.getId(); // String artifactDirectoryPath = storagePath + application.getId();
// File artifactDirectory = new File(artifactDirectoryPath); // File artifactDirectory = new File(artifactDirectoryPath);
// //
// if (artifactDirectory.exists()) { // if (artifactDirectory.exists()) {
// StorageManagementUtil.deleteDir(artifactDirectory); // StorageManagementUtil.deleteDir(artifactDirectory);
// } // }
} }
//todo //todo
@ -252,13 +249,13 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
public void deleteApplicationReleaseArtifacts(String applicationUUID, String version) public void deleteApplicationReleaseArtifacts(String applicationUUID, String version)
throws ApplicationStorageManagementException { throws ApplicationStorageManagementException {
// todo this should be validate application release // todo this should be validate application release
// Application application = validateApplication(applicationUUID); // Application application = validateApplication(applicationUUID);
// String artifactPath = storagePath + application.getId() + File.separator + version; // String artifactPath = storagePath + application.getId() + File.separator + version;
// File artifact = new File(artifactPath); // File artifact = new File(artifactPath);
// //
// if (artifact.exists()) { // if (artifact.exists()) {
// StorageManagementUtil.deleteDir(artifact); // StorageManagementUtil.deleteDir(artifact);
// } // }
} }
//todo //todo
@ -266,18 +263,18 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
public void deleteAllApplicationReleaseArtifacts(String applicationUUID) throws public void deleteAllApplicationReleaseArtifacts(String applicationUUID) throws
ApplicationStorageManagementException { ApplicationStorageManagementException {
// todo this should be validate application release // todo this should be validate application release
// validateApplication(applicationUUID); // validateApplication(applicationUUID);
// try { // try {
// List<ApplicationRelease> applicationReleases = DataHolder.getInstance().getApplicationReleaseManager() // List<ApplicationRelease> applicationReleases = DataHolder.getInstance().getApplicationReleaseManager()
// .getReleases(applicationUUID); // .getReleases(applicationUUID);
// for (ApplicationRelease applicationRelease : applicationReleases) { // for (ApplicationRelease applicationRelease : applicationReleases) {
// deleteApplicationReleaseArtifacts(applicationUUID, applicationRelease.getVersion()); // deleteApplicationReleaseArtifacts(applicationUUID, applicationRelease.getVersion());
// } // }
// } catch (ApplicationManagementException e) { // } catch (ApplicationManagementException e) {
// throw new ApplicationStorageManagementException( // throw new ApplicationStorageManagementException(
// "Application Management Exception while getting releases " + "for the application " // "Application Management Exception while getting releases " + "for the application "
// + applicationUUID, e); // + applicationUUID, e);
// } // }
} }
//todo //todo
@ -286,29 +283,29 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
ApplicationStorageManagementException { ApplicationStorageManagementException {
return null; return null;
// todo this should be validate application release // todo this should be validate application release
// Application application = validateApplication(applicationUUID); // Application application = validateApplication(applicationUUID);
// validateImageArtifactNames(name); // validateImageArtifactNames(name);
// String imageArtifactPath = storagePath + application.getId() + File.separator + name.toLowerCase(); // String imageArtifactPath = storagePath + application.getId() + File.separator + name.toLowerCase();
// //
// if (name.equalsIgnoreCase(Constants.IMAGE_ARTIFACTS[2])) { // if (name.equalsIgnoreCase(Constants.IMAGE_ARTIFACTS[2])) {
// imageArtifactPath += count; // imageArtifactPath += count;
// } // }
// File imageFile = new File(imageArtifactPath); // File imageFile = new File(imageArtifactPath);
// if (!imageFile.exists()) { // if (!imageFile.exists()) {
// throw new ApplicationStorageManagementException( // throw new ApplicationStorageManagementException(
// "Image artifact " + name + " does not exist for the " + "application with UUID " + applicationUUID); // "Image artifact " + name + " does not exist for the " + "application with UUID " + applicationUUID);
// } else { // } else {
// try { // try {
// return StorageManagementUtil.createImageArtifact(imageFile, imageArtifactPath); // return StorageManagementUtil.createImageArtifact(imageFile, imageArtifactPath);
// } catch (FileNotFoundException e) { // } catch (FileNotFoundException e) {
// throw new ApplicationStorageManagementException( // throw new ApplicationStorageManagementException(
// "File not found exception while trying to get the image artifact " + name + " for the " // "File not found exception while trying to get the image artifact " + name + " for the "
// + "application " + applicationUUID, e); // + "application " + applicationUUID, e);
// } catch (IOException e) { // } catch (IOException e) {
// throw new ApplicationStorageManagementException("IO Exception while trying to detect the image " // throw new ApplicationStorageManagementException("IO Exception while trying to detect the image "
// + "artifact " + name + " for the application " + applicationUUID, e); // + "artifact " + name + " for the application " + applicationUUID, e);
// } // }
// } // }
} }
/** /**

@ -287,7 +287,31 @@ public interface ApplicationManagementAPI {
name = "application", name = "application",
value = "The application that need to be created.", value = "The application that need to be created.",
required = true) required = true)
@Valid Application application); @Valid Application application,
@ApiParam(
name = "applicationRelease",
value = "Application Release")
@Valid ApplicationRelease applicationRelease,
@ApiParam(
name = "binaryFile",
value = "Binary file of uploading application",
required = true)
@Multipart(value = "binaryFile") Attachment binaryFile,
@ApiParam(
name = "icon",
value = "Icon of the uploading application",
required = true)
@Multipart(value = "icon") Attachment iconFile,
@ApiParam(
name = "banner",
value = "Banner of the uploading application",
required = true)
@Multipart(value = "banner") Attachment bannerFile,
@ApiParam(
name = "screenshot",
value = "Screen Shots of the uploading application",
required = true)
@Multipart(value = "screenshot") List<Attachment> attachmentList);
@DELETE @DELETE
@Consumes("application/json") @Consumes("application/json")
@ -371,4 +395,107 @@ public interface ApplicationManagementAPI {
value = "Whether to make it default or not", value = "Whether to make it default or not",
required = false) required = false)
@QueryParam("isDefault") boolean isDefault); @QueryParam("isDefault") boolean isDefault);
@POST
@Path("/image-artifacts/{appId}/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Upload artifacts",
notes = "This will create a new application",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully uploaded artifacts."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the application list.",
response = ErrorResponse.class)
})
Response updateApplicationImageArtifacts(
@ApiParam(name = "appId", value = "ID of the application", required = true) @PathParam("appId") int applicatioId,
@ApiParam(name = "uuid", value = "UUID of the application", required = true) @PathParam("uuid") String applicationUUID,
@Multipart(value = "icon") Attachment iconFile, @Multipart(value = "banner") Attachment bannerFile,
@Multipart(value = "screenshot") List<Attachment> screenshots);
@PUT
@Path("/app-artifacts/{appId}/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Upload artifacts",
notes = "This will create a new application",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully uploaded artifacts."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the application list.",
response = ErrorResponse.class)
})
Response updateApplicationArtifact(
@ApiParam(name = "id", value = "Id of the application", required = true) @PathParam("uuid") int applicationId,
@ApiParam(name = "uuid", value = "UUID of the application", required = true) @PathParam("uuid") String applicationUUID,
@Multipart("binaryFile") Attachment binaryFile );
@PUT
@Path("/{appId}/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update an application release",
notes = "This will update a new application release",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully created an application release.",
response = ApplicationRelease.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while releasing the application.",
response = ErrorResponse.class)
})
Response updateApplicationRelease(
@ApiParam(name = "appId", value = "Identifier of the Application", required = true) @PathParam("appId") int applicationId,
@ApiParam(name = "UUID", value = "Unique identifier of the Application Release", required = true) @PathParam("uuid") String applicationUUID,
@Multipart(value = "applicationRelease", required = false, type = "application/json") ApplicationRelease applicationRelease,
@Multipart(value = "binaryFile", required = false) Attachment binaryFile,
@Multipart(value = "icon", required = false) Attachment iconFile,
@Multipart(value = "banner", required = false) Attachment bannerFile,
@Multipart(value = "screenshot", required = false) List<Attachment> attachmentList);
} }

@ -1,400 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.publisher.api.services;
import io.swagger.annotations.*;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.publisher.api.beans.ErrorResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
/**
* APIs to handle application management related tasks.
*/
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "Application Management Service",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "ApplicationManagementService"),
@ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/applications"),
})
}
),
tags = {
@Tag(name = "application_management, device_management", description = "Application Management related "
+ "APIs")
}
)
@Scopes(
scopes = {
@Scope(
name = "Get Application Details",
description = "Get application details",
key = "perm:application:get",
permissions = {"/device-mgt/application/get"}
),
@Scope(
name = "Create an Application",
description = "Create an application",
key = "perm:application:create",
permissions = {"/device-mgt/application/create"}
),
@Scope(
name = "Update an Application",
description = "Update an application",
key = "perm:application:update",
permissions = {"/device-mgt/application/update"}
),
@Scope(
name = "Create an Application",
description = "Create an application",
key = "perm:application-mgt:login",
permissions = {"/device-mgt/application-mgt/login"}
),
@Scope(
name = "Delete an Application",
description = "Delete an application",
key = "perm:application:delete",
permissions = {"/device-mgt/application/delete"}
),
@Scope(
name = "Create an application category",
description = "Create an application category",
key = "perm:application-category:create",
permissions = {"/device-mgt/application/category/create"}
),
@Scope(
name = "Delete an Application category",
description = "Delete an application category",
key = "perm:application-category:delete",
permissions = {"/device-mgt/application/category/delete"}
)
}
)
@Path("/publisher/release")
@Api(value = "Application Management", description = "This API carries all application management related operations " +
"such as get all the applications, add application, etc.")
@Produces(MediaType.APPLICATION_JSON)
public interface ApplicationReleaseManagementAPI {
String SCOPE = "scope";
@POST
@Path("/{appType}/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Create an application release",
notes = "This will create a new application release",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully created an application release.",
response = ApplicationRelease.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while releasing the application.",
response = ErrorResponse.class)
}) Response createApplicationRelease(
@Multipart(value = "applicationRelease", type = "application/json") ApplicationRelease applicationRelease,
@ApiParam(
name = "binaryFile",
value = "Binary file of uploading application",
required = true)
@Multipart(value = "binaryFile") Attachment binaryFile,
@ApiParam(
name = "icon",
value = "Icon of the uploading application",
required = true)
@Multipart(value = "icon") Attachment iconFile,
@ApiParam(
name = "banner",
value = "Banner of the uploading application",
required = true)
@Multipart(value = "banner") Attachment bannerFile,
@ApiParam(
name = "screenshot",
value = "Screen Shots of the uploading application",
required = true)
@Multipart(value = "screenshot") List<Attachment> attachmentList,
@ApiParam(
name = "appType",
value = "Application Type",
required = true)
@PathParam("appType") String applicationType,
@ApiParam(
name = "appId",
value = "Application ID",
required = true)
@PathParam("appId") int applicationId);
@POST
@Path("/update-image-artifacts/{appId}/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Upload artifacts",
notes = "This will create a new application",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully uploaded artifacts."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the application list.",
response = ErrorResponse.class)
})
Response updateApplicationImageArtifacts(
@ApiParam(name = "appId", value = "ID of the application", required = true) @PathParam("appId") int applicatioId,
@ApiParam(name = "uuid", value = "UUID of the application", required = true) @PathParam("uuid") String applicationUUID,
@Multipart(value = "icon") Attachment iconFile, @Multipart(value = "banner") Attachment bannerFile,
@Multipart(value = "screenshot") List<Attachment> screenshots);
@PUT
@Path("/update-artifacts/{appId}/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Upload artifacts",
notes = "This will create a new application",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:create")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully uploaded artifacts."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the application list.",
response = ErrorResponse.class)
})
Response updateApplicationArtifact(
@ApiParam(name = "id", value = "Id of the application", required = true) @PathParam("uuid") int applicationId,
@ApiParam(name = "uuid", value = "UUID of the application", required = true) @PathParam("uuid") String applicationUUID,
@Multipart("binaryFile") Attachment binaryFile );
@PUT
@Path("/{appId}/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "PUT",
value = "Update an application release",
notes = "This will update a new application release",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 201,
message = "OK. \n Successfully created an application release.",
response = ApplicationRelease.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while releasing the application.",
response = ErrorResponse.class)
})
Response updateApplicationRelease(
@ApiParam(name = "appId", value = "Identifier of the Application", required = true) @PathParam("appId") int applicationId,
@ApiParam(name = "UUID", value = "Unique identifier of the Application Release", required = true) @PathParam("uuid") String applicationUUID,
@Multipart(value = "applicationRelease", required = false, type = "application/json") ApplicationRelease applicationRelease,
@Multipart(value = "binaryFile", required = false) Attachment binaryFile,
@Multipart(value = "icon", required = false) Attachment iconFile,
@Multipart(value = "banner", required = false) Attachment bannerFile,
@Multipart(value = "screenshot", required = false) List<Attachment> attachmentList);
@GET
@Path("/release-artifacts/{uuid}/{version}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_OCTET_STREAM,
httpMethod = "GET",
value = "Get an application release",
notes = "This will return the application release indicated by Application UUID and version",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved the Application release.",
response = Attachment.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while releasing the application.",
response = ErrorResponse.class)
})
Response getApplicationReleaseArtifacts(
@ApiParam(name = "UUID", value = "Unique identifier of the Application", required = true) @PathParam("uuid") String applicationUUID,
@ApiParam(name = "Version", value = "Version of the Application release need to be retrieved", required = true) @PathParam("version") String version);
@GET
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get all the releases or specific release of an application",
notes = "This will retrieve the all the releases or specific release of an application",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved the Application release."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while releasing the application.",
response = ErrorResponse.class)
})
Response getApplicationReleases(@ApiParam(name = "appId", value = "Unique identifier of the Application",
required = true) @PathParam("appId") int applicationId);
@DELETE
@Path("/release/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Delete the releases of a particular applicaion",
notes = "This will delete the releases or specific release of an application",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:delete")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \nI Successfully deleted the Application release."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while deleting the release of a"
+ "particular application.",
response = ErrorResponse.class)
})
Response deleteApplicationRelease(
@ApiParam(name = "UUID", value = "Unique identifier of the Application", required = true) @PathParam("uuid") String applicationUUID,
@ApiParam(name = "version", value = "Version of the application") @QueryParam("version") String version);
@GET
@Path("/image-artifacts/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Delete the releases of a particular applicaion",
notes = "This will delete the releases or specific release of an application",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:application:get")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully deleted the Application release."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while deleting the release of a"
+ "particular application.",
response = ErrorResponse.class)
})
Response getApplicationImageArtifacts(
@ApiParam(name = "UUID", value = "Unique identifier of the Application", required = true) @PathParam("uuid") String applicationUUID,
@ApiParam(name = "name", value = "Name of the artifact to be retrieved", required = true) @QueryParam("name") String name,
@ApiParam(name = "count", value = "Count of the screen-shot artifact to be retrieved", required = false) @QueryParam("count") int count);
}

@ -45,6 +45,7 @@ import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.UUID;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
@ -77,7 +78,6 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@QueryParam("limit") int limit, @QueryParam("limit") int limit,
@QueryParam("query") String searchQuery) { @QueryParam("query") String searchQuery) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try { try {
if (limit == 0) { if (limit == 0) {
@ -89,16 +89,6 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
filter.setSearchQuery(searchQuery); filter.setSearchQuery(searchQuery);
ApplicationList applications = applicationManager.getApplications(filter); ApplicationList applications = applicationManager.getApplications(filter);
for (Application application : applications.getApplications()) {
String uuId = applicationManager.getUuidOfLatestRelease(application.getId());
if (uuId != null){
ImageArtifact imageArtifact = applicationStorageManager.getImageArtifact(uuId, Constants.IMAGE_ARTIFACTS[0], 0);
application.setIconOfLatestRelease(imageArtifact);
}else{
// ToDo set default icon
}
}
return Response.status(Response.Status.OK).entity(applications).build(); return Response.status(Response.Status.OK).entity(applications).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).build();
@ -106,9 +96,6 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
String msg = "Error occurred while getting the application list for publisher "; String msg = "Error occurred while getting the application list for publisher ";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} catch (ApplicationStorageManagementException e) {
log.error("Error occurred while getting the image artifacts of the application for publisher", e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }
@ -119,20 +106,11 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@PathParam("appType") String appType, @PathParam("appType") String appType,
@QueryParam("appName") String appName) { @QueryParam("appName") String appName) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try { try {
Application application = applicationManager.getApplication(appType, appName); Application application = applicationManager.getApplication(appType, appName);
if (application == null) { if (application == null) {
return Response.status(Response.Status.NOT_FOUND) return Response.status(Response.Status.NOT_FOUND).entity
.entity("Application with UUID " + appType + " not found").build(); ("Application with UUID " + appType + " not found").build();
}
String uuId = applicationManager.getUuidOfLatestRelease(application.getId());
if (uuId != null){
ImageArtifact imageArtifact = applicationStorageManager.getImageArtifact(uuId, Constants.IMAGE_ARTIFACTS[0], 0);
application.setIconOfLatestRelease(imageArtifact);
}else{
// ToDo set default icon
} }
return Response.status(Response.Status.OK).entity(application).build(); return Response.status(Response.Status.OK).entity(application).build();
@ -141,30 +119,177 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
log.error("Error occurred while getting application with the uuid " + appType, e); log.error("Error occurred while getting application with the uuid " + appType, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (ApplicationStorageManagementException e) {
log.error("Error occurred while getting the image artifacts of the application with the uuid " + appType, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }
@POST @POST
@Consumes("application/json") @Consumes("application/json")
public Response createApplication(@Valid Application application) { public Response createApplication(
@Valid Application application,
@Valid ApplicationRelease applicationRelease,
@Multipart("binaryFile") Attachment binaryFile,
@Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile,
@Multipart("screenshot") List<Attachment> attachmentList) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
InputStream iconFileStream;
InputStream bannerFileStream;
List<InputStream> attachments = new ArrayList<>();
try { try {
if (iconFile == null) {
throw new ApplicationManagementException(
"Icon file is not uploaded for the application release of " + application.getName() +
" of application type " + application.getType()); }
if (bannerFile == null) {
throw new ApplicationManagementException(
"Banner file is not uploaded for the application release of " + application.getName() +
" of application type " + application.getType()); }
if (attachmentList == null || attachmentList.isEmpty()) {
throw new ApplicationManagementException(
"Screenshots are not uploaded for the application release of " + application.getName() +
" of application type " + application.getType()); }
if (binaryFile == null){
throw new ApplicationManagementException(
"Binary file is not uploaded for the application release of " + application.getName() +
" of application type " + application.getType()); }
iconFileStream = iconFile.getDataHandler().getInputStream();
bannerFileStream = bannerFile.getDataHandler().getInputStream();
for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream());
}
applicationRelease = applicationStorageManager.uploadReleaseArtifacts(applicationRelease,
binaryFile.getDataHandler().getInputStream());
if(applicationRelease.getAppStoredLoc() == null || applicationRelease.getAppHashValue() == null){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
applicationRelease = applicationStorageManager.uploadImageArtifacts(applicationRelease, iconFileStream,
bannerFileStream, attachments);
applicationRelease.setUuid(UUID.randomUUID().toString());
Application createdApplication = applicationManager.createApplication(application); Application createdApplication = applicationManager.createApplication(application);
if (application != null){ if (application != null){
return Response.status(Response.Status.CREATED).entity(createdApplication).build(); return Response.status(Response.Status.CREATED).entity(createdApplication).build();
}else{ }else{
String msg = "Given device type is not matched with existing device types"; log.error("Given device type is not matched with existing device types");
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} }
}catch (ApplicationManagementException e) { }catch (ApplicationManagementException e) {
String msg = "Error occurred while creating the application"; String msg = "Error occurred while creating the application";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} catch (ResourceManagementException e) {
log.error("Error occurred while uploading the releases artifacts of the application "
+ application.getName(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
String errorMessage =
"Error while uploading binary file and resources for the application release of the application "
+ application.getName();
log.error(errorMessage, e);
return APIUtil.getResponse(new ApplicationManagementException(errorMessage, e),
Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@POST
@Path("/image-artifacts/{appId}/{uuid}")
public Response updateApplicationImageArtifacts(
@PathParam("appId") int appId,
@PathParam("uuid") String applicationUUID,
@Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile,
@Multipart("screenshot") List<Attachment> attachmentList) {
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationRelease applicationRelease = null;
try {
InputStream iconFileStream = null;
InputStream bannerFileStream = null;
List<InputStream> attachments = new ArrayList<>();
if (iconFile != null) {
iconFileStream = iconFile.getDataHandler().getInputStream();
}
if (bannerFile != null) {
bannerFileStream = bannerFile.getDataHandler().getInputStream();
}
if (attachmentList != null && !attachmentList.isEmpty()) {
for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream());
}
}
applicationRelease = applicationStorageManager
.updateImageArtifacts(appId, applicationUUID, iconFileStream, bannerFileStream, attachments);
applicationReleaseManager.updateRelease(appId, applicationRelease);
return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application " + applicationUUID).build();
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while creating the application";
log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.BAD_REQUEST);
} catch (IOException e) {
log.error("Exception while trying to read icon, banner files for the application " + applicationUUID);
return APIUtil.getResponse(new ApplicationManagementException(
"Exception while trying to read icon, " + "banner files for the application " + applicationUUID, e),
Response.Status.BAD_REQUEST);
} catch (ResourceManagementException e) {
log.error("Error occurred while uploading the image artifacts of the application with the uuid "
+ applicationUUID, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@PUT
@Path("/app-artifacts/{appId}/{uuid}")
public Response updateApplicationArtifact(
@PathParam("appId") int applicationId,
@PathParam("uuid") String applicationUuuid,
@Multipart("binaryFile") Attachment binaryFile) {
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationRelease applicationRelease = null;
try {
if (binaryFile != null) {
applicationRelease = applicationStorageManager.updateReleaseArtifacts(applicationId, applicationUuuid,
binaryFile.getDataHandler().getInputStream());
applicationReleaseManager.updateRelease(applicationId, applicationRelease);
return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application " + applicationUuuid).build();
}
return Response.status(Response.Status.BAD_REQUEST)
.entity("Uploading artifacts for the application is failed " + applicationUuuid).build();
} catch (IOException e) {
log.error("Exception while trying to read icon, banner files for the application " + applicationUuuid);
return APIUtil.getResponse(new ApplicationManagementException(
"Exception while trying to read icon, banner files for the application " + applicationUuuid, e),
Response.Status.BAD_REQUEST);
} catch (ResourceManagementException e) {
log.error("Error occurred while uploading the image artifacts of the application with the uuid "
+ applicationUuuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (ApplicationManagementException e) {
log.error("Error occurred while updating the image artifacts of the application with the uuid "
+ applicationUuuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }
@ -233,4 +358,68 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }
@Override
@PUT
@Path("/{appId}/{uuid}")
public Response updateApplicationRelease(
@PathParam("appId") int applicationId,
@PathParam("uuid") String applicationUUID,
@Multipart("applicationRelease") ApplicationRelease applicationRelease,
@Multipart("binaryFile") Attachment binaryFile,
@Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile,
@Multipart("screenshot") List<Attachment> attachmentList) {
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
InputStream iconFileStream = null;
InputStream bannerFileStream = null;
List<InputStream> attachments = new ArrayList<>();
try {
if (binaryFile != null) {
//todo add binary file validation
applicationRelease = applicationStorageManager.updateReleaseArtifacts(applicationId, applicationUUID,
binaryFile.getDataHandler().getInputStream());
}
if (iconFile != null) {
iconFileStream = iconFile.getDataHandler().getInputStream();
}
if (bannerFile != null) {
bannerFileStream = bannerFile.getDataHandler().getInputStream();
}
if (!attachmentList.isEmpty()) {
for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream());
}
}
applicationRelease = applicationStorageManager
.updateImageArtifacts(applicationId, applicationUUID, iconFileStream, bannerFileStream,
attachments);
applicationRelease = applicationReleaseManager.updateRelease(applicationId, applicationRelease);
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) {
log.error("Error while updating the application release of the application with UUID " + applicationUUID);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
log.error("Error while updating the release artifacts of the application with UUID " + applicationUUID);
return APIUtil.getResponse(new ApplicationManagementException(
"Error while updating the release artifacts of the application with UUID " + applicationUUID),
Response.Status.INTERNAL_SERVER_ERROR);
} catch (ResourceManagementException e) {
log.error("Error occurred while updating the releases artifacts of the application with the uuid "
+ applicationUUID + " for the release " + applicationRelease.getVersion(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
} }

@ -1,404 +0,0 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.application.mgt.publisher.api.services.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationReleaseManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.publisher.api.APIUtil;
import org.wso2.carbon.device.application.mgt.publisher.api.FileStreamingOutput;
import org.wso2.carbon.device.application.mgt.publisher.api.services.ApplicationReleaseManagementAPI;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Implementation of Application Management related APIs.
*/
@Produces({"application/json"})
@Path("/publisher/release")
public class ApplicationReleaseManagementAPIImpl implements ApplicationReleaseManagementAPI {
private static final int DEFAULT_LIMIT = 20;
private static Log log = LogFactory.getLog(ApplicationReleaseManagementAPIImpl.class);
@Override
@POST
@Path("/{appType}/{appId}")
public Response createApplicationRelease(
@Multipart("applicationRelease") ApplicationRelease applicationRelease,
@Multipart("binaryFile") Attachment binaryFile,
@Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile,
@Multipart("screenshot") List<Attachment> attachmentList,
@PathParam("appType") String applicationType,
@PathParam("appId") int applicationId) {
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
InputStream iconFileStream;
InputStream bannerFileStream;
List<InputStream> attachments = new ArrayList<>();
try {
if (iconFile == null) {
throw new ApplicationManagementException(
"Icon file is not uploaded for the application release of " + applicationId); }
if (bannerFile == null) {
throw new ApplicationManagementException(
"Banner file is not uploaded for the application release of " + applicationId); }
if (attachmentList == null || attachmentList.isEmpty()) {
throw new ApplicationManagementException(
"Screenshots are not uploaded for the application release of " + applicationId); }
if (binaryFile == null){
throw new ApplicationManagementException(
"Binary file is not uploaded for the application release of " + applicationId); }
iconFileStream = iconFile.getDataHandler().getInputStream();
bannerFileStream = bannerFile.getDataHandler().getInputStream();
for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream());
}
applicationRelease = applicationStorageManager.uploadReleaseArtifacts(applicationId, applicationRelease,
binaryFile.getDataHandler().getInputStream());
if(applicationRelease.getAppStoredLoc() == null || applicationRelease.getAppHashValue() == null){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
applicationRelease = applicationStorageManager.uploadImageArtifacts(applicationId, applicationRelease,
iconFileStream, bannerFileStream, attachments);
applicationRelease.setUuid(UUID.randomUUID().toString());
applicationRelease = applicationReleaseManager.createRelease(applicationId, applicationRelease);
//Todo insert lifecycle into lifecycle table
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
} catch (ApplicationManagementException e) {
log.error("Error while creating an application release for the application ID " + applicationId,
e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
String errorMessage =
"Error while uploading binary file and resources for the application release of the application ID "
+ applicationId;
log.error(errorMessage, e);
return APIUtil.getResponse(new ApplicationManagementException(errorMessage, e),
Response.Status.INTERNAL_SERVER_ERROR);
} catch (ResourceManagementException e) {
log.error("Error occurred while uploading the releases artifacts of the application id "
+ applicationId + " the release version is " + applicationRelease.getVersion(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@Path("/{appId}")
@GET
public Response getApplicationReleases(@PathParam("appId") int applicationId){
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
UnrestrictedRoleManager unrestrictedRoleManager = APIUtil.getUnrestrictedRoleManager();
ApplicationManager applicationManager = APIUtil.getApplicationManager();
List<ApplicationRelease> applicationReleases;
try {
List<UnrestrictedRole> unrestrictedRoles = unrestrictedRoleManager.getUnrestrictedRoles(applicationId, tenantId);
if(unrestrictedRoles == null || applicationManager.isUserAllowable(unrestrictedRoles,userName)){
applicationReleases = applicationReleaseManager.getReleases(applicationId);
return Response.status(Response.Status.OK).entity(applicationReleases).build();
}
return Response.status(Response.Status.UNAUTHORIZED).build();
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) {
log.error("Error while getting all the application releases for the application with the id "
+ applicationId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@PUT
@Path("/{appId}/{uuid}")
public Response updateApplicationRelease(
@PathParam("appId") int applicationId,
@PathParam("uuid") String applicationUUID,
@Multipart("applicationRelease") ApplicationRelease applicationRelease,
@Multipart("binaryFile") Attachment binaryFile,
@Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile,
@Multipart("screenshot") List<Attachment> attachmentList) {
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
InputStream iconFileStream = null;
InputStream bannerFileStream = null;
List<InputStream> attachments = new ArrayList<>();
try {
if (binaryFile != null) {
//todo add binary file validation
applicationRelease = applicationStorageManager.uploadReleaseArtifacts
(applicationId, applicationRelease, binaryFile.getDataHandler().getInputStream());
}
if(iconFile != null ){
iconFileStream = iconFile.getDataHandler().getInputStream();
}
if (bannerFile != null){
bannerFileStream = bannerFile.getDataHandler().getInputStream();
}
if (!attachmentList.isEmpty()){
for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream());
}
}
applicationRelease = applicationStorageManager.uploadImageArtifacts(applicationId, applicationRelease,
iconFileStream, bannerFileStream, attachments);
if (applicationRelease != null) {
applicationRelease = applicationReleaseManager.updateRelease(applicationId, applicationRelease);
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) {
log.error("Error while updating the application release of the application with UUID " + applicationUUID);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
catch (IOException e) {
log.error("Error while updating the release artifacts of the application with UUID " + applicationUUID);
return APIUtil.getResponse(new ApplicationManagementException(
"Error while updating the release artifacts of the application with UUID "
+ applicationUUID), Response.Status.INTERNAL_SERVER_ERROR);
}
catch (ResourceManagementException e) {
log.error("Error occurred while updating the releases artifacts of the application with the uuid "
+ applicationUUID + " for the release " + applicationRelease.getVersion(), e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@POST
@Path("/update-image-artifacts/{appId}/{uuid}")
public Response updateApplicationImageArtifacts(
@PathParam("appId") int appId,
@PathParam("uuid") String applicationUUID,
@Multipart("icon") Attachment iconFile,
@Multipart("banner") Attachment bannerFile,
@Multipart("screenshot") List<Attachment> attachmentList) {
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationRelease applicationRelease = null;
try {
InputStream iconFileStream = null;
InputStream bannerFileStream = null;
List<InputStream> attachments = new ArrayList<>();
if (iconFile != null) {
iconFileStream = iconFile.getDataHandler().getInputStream();
}
if (bannerFile != null) {
bannerFileStream = bannerFile.getDataHandler().getInputStream();
}
if (attachmentList != null && !attachmentList.isEmpty()) {
for (Attachment screenshot : attachmentList) {
attachments.add(screenshot.getDataHandler().getInputStream());
}
}
applicationRelease = applicationStorageManager.updateImageArtifacts
(appId, applicationUUID, iconFileStream, bannerFileStream, attachments);
applicationReleaseManager.updateRelease(appId,applicationRelease);
return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application " + applicationUUID).build();
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while creating the application";
log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.BAD_REQUEST);
} catch (IOException e) {
log.error("Exception while trying to read icon, banner files for the application " + applicationUUID);
return APIUtil.getResponse(new ApplicationManagementException(
"Exception while trying to read icon, " + "banner files for the application " +
applicationUUID, e), Response.Status.BAD_REQUEST);
}
catch (ResourceManagementException e) {
log.error("Error occurred while uploading the image artifacts of the application with the uuid "
+ applicationUUID, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@Override
@PUT
@Path("/update-artifacts/{appId}/{uuid}")
public Response updateApplicationArtifact(
@PathParam("appId") int applicationId,
@PathParam("uuid") String applicationUuuid,
@Multipart("binaryFile") Attachment binaryFile) {
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationRelease applicationRelease = null;
try {
if (binaryFile != null) {
applicationRelease = applicationStorageManager.updateReleaseArtifacts(applicationId, applicationUuuid,
binaryFile.getDataHandler().getInputStream());
applicationReleaseManager.updateRelease(applicationId, applicationRelease);
return Response.status(Response.Status.OK)
.entity("Successfully uploaded artifacts for the application " + applicationUuuid).build();
}
return Response.status(Response.Status.BAD_REQUEST)
.entity("Uploading artifacts for the application is failed " + applicationUuuid).build();
} catch (IOException e) {
log.error("Exception while trying to read icon, banner files for the application " + applicationUuuid);
return APIUtil.getResponse(new ApplicationManagementException(
"Exception while trying to read icon, banner files for the application " +
applicationUuuid, e), Response.Status.BAD_REQUEST);
}
catch (ResourceManagementException e) {
log.error("Error occurred while uploading the image artifacts of the application with the uuid "
+ applicationUuuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (ApplicationManagementException e) {
log.error("Error occurred while updating the image artifacts of the application with the uuid "
+ applicationUuuid, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
//todo
@Override
@DELETE
@Path("/release/{uuid}")
public Response deleteApplicationRelease(@PathParam("uuid") String applicationUUID,
@QueryParam("version") String version) {
ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
if (version != null && !version.isEmpty()) {
applicationStorageManager.deleteApplicationReleaseArtifacts(applicationUUID, version);
// applicationReleaseManager.deleteApplicationRelease(applicationUUID, version);
return Response.status(Response.Status.OK)
.entity("Successfully deleted Application release with " + "version " + version
+ " for the application with UUID " + applicationUUID).build();
} else {
applicationStorageManager.deleteAllApplicationReleaseArtifacts(applicationUUID);
applicationReleaseManager.deleteApplicationReleases(applicationUUID);
return Response.status(Response.Status.OK)
.entity("Successfully deleted Application releases for the " + "application with UUID "
+ applicationUUID).build();
}
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) {
log.error("Error while deleting application release with the application UUID " + applicationUUID, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (ApplicationStorageManagementException e) {
log.error("Error occurred while deleting the releases artifacts of the application with the uuid "
+ applicationUUID + " for the release " + version, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
//todo I think we must remove following methods - By DLPDS
@Override
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/release-artifacts/{uuid}/{version}")
public Response getApplicationReleaseArtifacts(@PathParam("uuid") String applicationUUID,
@PathParam("version") String version) {
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
InputStream binaryFile = applicationStorageManager.getReleasedArtifacts(applicationUUID, version);
FileStreamingOutput fileStreamingOutput = new FileStreamingOutput(binaryFile);
Response.ResponseBuilder response = Response.status(Response.Status.OK).entity(fileStreamingOutput);
response.header("Content-Disposition", "attachment; filename=\"" + version + "\"");
return response.build();
} catch (ApplicationStorageManagementException e) {
log.error("Error while retrieving the binary file of the application release for the application UUID " +
applicationUUID + " and version " + version, e);
if (e.getMessage().contains("Binary file does not exist")) {
return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
} else {
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
@Override
@GET
@Path("/image-artifacts/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
public Response getApplicationImageArtifacts(@PathParam("uuid") String applicationUUID,
@QueryParam("name") String name, @QueryParam("count") int count) {
if (name == null || name.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity("Name should not be null. Name is mandatory to"
+ " retrieve the particular image artifact of the release").build();
}
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
ImageArtifact imageArtifact = applicationStorageManager.getImageArtifact(applicationUUID, name, count);
Response.ResponseBuilder response = Response.status(Response.Status.OK).entity(imageArtifact);
return response.build();
} catch (ApplicationStorageManagementException e) {
log.error("Application Storage Management Exception while getting the image artifact " + name + " of "
+ "the application with UUID " + applicationUUID, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
Loading…
Cancel
Save