Merge branch 'application-mgt-new' into 'application-mgt-new'

Add life-cycle management feature for APPM

See merge request entgra/carbon-device-mgt!88
feature/appm-store/pbac
Inosh Perara 6 years ago
commit f3abf07dc6

@ -80,33 +80,4 @@ public interface ConfigRetrieveAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response getUiConfig(); Response getUiConfig();
@GET
@Path("/lifecycle-config")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get application management UI configuration",
notes = "This will get all UI configuration of application management"
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully got Lifecycle Config.",
response = ApplicationList.class),
@ApiResponse(
code = 404,
message = "Not Found. There doesn't have an defined <LifecycleStates> in app management "
+ "configuration file." +
"query."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the lifecycle config.",
response = ErrorResponse.class)
})
Response getLifecycleConfig();
} }

@ -54,19 +54,4 @@ public class ConfigRetrieveAPIImpl implements ConfigRetrieveAPI {
} }
return Response.status(Response.Status.OK).entity(uiConfiguration).build(); return Response.status(Response.Status.OK).entity(uiConfiguration).build();
} }
@GET
@Override
@Consumes("application/json")
@Path("/lifecycle-config")
public Response getLifecycleConfig() {
AppmDataHandler dataHandler = APIUtil.getDataHandler();
try {
return Response.status(Response.Status.OK).entity(dataHandler.getLifecycleConfiguration()).build();
} catch (LifecycleManagementException e) {
String msg = "Error Occurred while accessing lifecycle manager.";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
} }

@ -23,6 +23,6 @@ package org.wso2.carbon.device.application.mgt.common;
* States of the Application. * States of the Application.
*/ */
public enum AppLifecycleState { public enum AppLifecycleState {
CREATED, IN_REVIEW, PUBLISHED, APPROVED, UNPUBLISHED, REJECTED, DEPRECATED, REMOVED CREATED, IN_REVIEW, PUBLISHED, APPROVED, BLOCKED, REJECTED, DEPRECATED, RETIRED
} }

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.application.mgt.common.dto; package org.wso2.carbon.device.application.mgt.common;
import java.sql.Timestamp; import java.sql.Timestamp;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
@ -24,13 +24,8 @@ import io.swagger.annotations.ApiModelProperty;
import java.util.List; import java.util.List;
@ApiModel(value = "LifecycleStateDTO", description = "LifecycleStateDTO represents the Lifecycle state for an application release") @ApiModel(value = "LifecycleState", description = "LifecycleState represents the Lifecycle state for an application release")
public class LifecycleStateDTO { public class LifecycleState {
@ApiModelProperty(name = "id",
value = "ID of the application release lifecycle",
required = true)
private int id;
@ApiModelProperty(name = "currentState", @ApiModelProperty(name = "currentState",
value = "Current state of the application release", value = "Current state of the application release",
@ -54,14 +49,6 @@ public class LifecycleStateDTO {
value = "Timestamp of the lifecycle has been updated") value = "Timestamp of the lifecycle has been updated")
private Timestamp updatedAt; private Timestamp updatedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrentState() { public String getCurrentState() {
return currentState; return currentState;
} }

@ -1,51 +0,0 @@
package org.wso2.carbon.device.application.mgt.common;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class represents the state of the lifecycle
*/
public class State {
private Set<String> proceedingStates;
private String stateName;
private String permission;
private boolean isAppUpdatable;
private boolean isAppInstallable;
private boolean isInitialState;
private boolean isEndState;
public State(String stateName, List<String> states, String permission, boolean isAppUpdatable,
boolean isAppInstallable, boolean isInitialState, boolean isEndState) {
this.stateName = stateName;
this.permission = permission;
this.isAppUpdatable=isAppUpdatable;
this.isAppInstallable=isAppInstallable;
this.isInitialState=isInitialState;
this.isEndState=isEndState;
if (states != null && !states.isEmpty()) {
proceedingStates = new HashSet<>(states);
}
}
public String getState() {
return stateName;
}
public Set<String> getProceedingStates() {
return proceedingStates;
}
public String getPermission(){ return permission;}
public boolean isAppUpdatable(){ return isAppUpdatable;}
public boolean isAppInstallable(){ return isAppInstallable;}
public boolean isInitialState(){ return isInitialState;}
public boolean isEndState(){ return isEndState;}
}

@ -19,6 +19,7 @@ public class LifecycleState {
private boolean isAppUpdatable; private boolean isAppUpdatable;
private boolean isInitialState; private boolean isInitialState;
private boolean isEndState; private boolean isEndState;
private boolean isDeletableState;
@XmlAttribute(name = "name") @XmlAttribute(name = "name")
public String getName() { public String getName() {
@ -84,4 +85,8 @@ public class LifecycleState {
this.isEndState = isEndState; this.isEndState = isEndState;
} }
@XmlElement(name = "IsDeletableState")
public boolean isDeletableState() { return isDeletableState; }
public void setDeletableState(boolean deletableState) { isDeletableState = deletableState; }
} }

@ -86,7 +86,7 @@ public class ApplicationDTO {
@ApiModelProperty(name = "status", @ApiModelProperty(name = "status",
value = "Application status", value = "Application status",
required = true, required = true,
example = "REMOVED, ACTIVE") example = "RETIRED, ACTIVE")
private String status; private String status;
@ApiModelProperty(name = "applicationReleaseDTOs", @ApiModelProperty(name = "applicationReleaseDTOs",

@ -24,7 +24,7 @@ import org.wso2.carbon.device.application.mgt.common.dto.ApplicationDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.Filter; import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO; import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.response.Application; import org.wso2.carbon.device.application.mgt.common.response.Application;
@ -69,14 +69,21 @@ public interface ApplicationManager {
*/ */
void deleteApplication(int applicationId) throws ApplicationManagementException; void deleteApplication(int applicationId) throws ApplicationManagementException;
/**
* Retire an application identified by the unique ID.
*
* @param applicationId ID for tha application
* @throws ApplicationManagementException ApplicationDTO Management Exception
*/
void retireApplication(int applicationId) throws ApplicationManagementException;
/** /**
* Delete an application identified by the unique ID. * Delete an application identified by the unique ID.
* *
* @param applicationId ID of tha application
* @param releaseUuid UUID of tha application release * @param releaseUuid UUID of tha application release
* @throws ApplicationManagementException ApplicationDTO Management Exception * @throws ApplicationManagementException ApplicationDTO Management Exception
*/ */
void deleteApplicationRelease(int applicationId, String releaseUuid) throws ApplicationManagementException; void deleteApplicationRelease(String releaseUuid) throws ApplicationManagementException;
/** /**
* To get the applications based on the search filter. * To get the applications based on the search filter.
@ -126,24 +133,22 @@ public interface ApplicationManager {
ApplicationDTO getApplicationByRelease(String appReleaseUUID) throws ApplicationManagementException; ApplicationDTO getApplicationByRelease(String appReleaseUUID) throws ApplicationManagementException;
/** /**
* To get all the releases of a particular ApplicationDTO. * To get lifecycle state change flow of a particular Application Release.
* *
* @param applicationId ID of the ApplicationDTO . * @param releaseUuid UUID of the Application Release.
* @param releaseUuid UUID of the ApplicationDTO Release. * @return the List of LifecycleStates which represent the lifecycle change flow of the application releases.
* @return the LifecycleStateDTO of the ApplicationDTO releases related with the particular ApplicationDTO. * @throws ApplicationManagementException Application Management Exception.
* @throws ApplicationManagementException ApplicationDTO Management Exception.
*/ */
LifecycleStateDTO getLifecycleState(int applicationId, String releaseUuid) throws ApplicationManagementException; List<LifecycleState> getLifecycleStateChangeFlow(String releaseUuid) throws ApplicationManagementException;
/** /**
* To get all the releases of a particular ApplicationDTO. * To get all the releases of a particular ApplicationDTO.
* *
* @param applicationId ID of the ApplicationDTO.
* @param releaseUuid UUID of the ApplicationDTO Release. * @param releaseUuid UUID of the ApplicationDTO Release.
* @param state Lifecycle state to change the app * @param stateName Lifecycle state to change the app
* @throws ApplicationManagementException ApplicationDTO Management Exception. * @throws ApplicationManagementException ApplicationDTO Management Exception.
*/ */
void changeLifecycleState(int applicationId, String releaseUuid, LifecycleStateDTO state) void changeLifecycleState(String releaseUuid, String stateName)
throws ApplicationManagementException; throws ApplicationManagementException;
/** /**

@ -17,7 +17,7 @@
package org.wso2.carbon.device.application.mgt.common.services; package org.wso2.carbon.device.application.mgt.common.services;
import org.wso2.carbon.device.application.mgt.common.State; import org.wso2.carbon.device.application.mgt.common.config.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration; import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException; import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
@ -33,7 +33,7 @@ public interface AppmDataHandler {
*/ */
UIConfiguration getUIConfiguration(); UIConfiguration getUIConfiguration();
Map<String, State> getLifecycleConfiguration() throws LifecycleManagementException; Map<String, LifecycleState> getLifecycleConfiguration() throws LifecycleManagementException;
InputStream getArtifactStream(String uuid, String artifactName) throws ApplicationManagementException; InputStream getArtifactStream(String uuid, String artifactName) throws ApplicationManagementException;
} }

@ -59,14 +59,18 @@ public interface ApplicationDAO {
void deleteTagMapping (List<Integer> tagIds, int applicationId, int tenantId) throws ApplicationManagementDAOException; void deleteTagMapping (List<Integer> tagIds, int applicationId, int tenantId) throws ApplicationManagementDAOException;
void deleteTagMapping (int applicationId, int tenantId) throws ApplicationManagementDAOException;
List<String> getAppCategories (int appId, int tenantId) throws ApplicationManagementDAOException; List<String> getAppCategories (int appId, int tenantId) throws ApplicationManagementDAOException;
List<CategoryDTO> getAllCategories(int tenantId) throws ApplicationManagementDAOException; List<CategoryDTO> getAllCategories(int tenantId) throws ApplicationManagementDAOException;
void addCategories(List<String> categories, int tenantId) throws ApplicationManagementDAOException; void addCategories(List<String> categories, int tenantId) throws ApplicationManagementDAOException;
void addCategoryMapping (List<Integer> categoryIds, int applicationId, int tenantId) throws ApplicationManagementDAOException; void addCategoryMapping(List<Integer> categoryIds, int applicationId, int tenantId)
throws ApplicationManagementDAOException;
void deleteCategoryMapping (int applicationId, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To check application existence. * To check application existence.
@ -176,7 +180,7 @@ public interface ApplicationDAO {
* @param appId ID of the application. * @param appId ID of the application.
* @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
void deleteApplication(int appId) throws ApplicationManagementDAOException; void retireApplication(int appId) throws ApplicationManagementDAOException;
/** /**
* To get the application count that satisfies gives search query. * To get the application count that satisfies gives search query.
@ -209,5 +213,8 @@ public interface ApplicationDAO {
ApplicationDTO getApplicationByRelease(String appReleaseUUID, int tenantId) throws ApplicationManagementDAOException; ApplicationDTO getApplicationByRelease(String appReleaseUUID, int tenantId) throws ApplicationManagementDAOException;
String getApplicationSubTypeByUUID(String uuid, int tenantId) throws ApplicationManagementDAOException; String getApplicationSubTypeByUUID(String uuid, int tenantId) throws ApplicationManagementDAOException;
void deleteApplication(int appId, int tenantId) throws ApplicationManagementDAOException;
} }

@ -19,7 +19,6 @@
package org.wso2.carbon.device.application.mgt.core.dao; package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.ApplicationReleaseArtifactPaths;
import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
@ -112,10 +111,12 @@ public interface ApplicationReleaseDAO {
* To delete a particular release. * To delete a particular release.
* *
* @param id ID of the ApplicationDTO which the release need to be deleted. * @param id ID of the ApplicationDTO which the release need to be deleted.
* @param version Version of the ApplicationDTO Release
* @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception. * @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/ */
void deleteRelease(int id, String version) throws ApplicationManagementDAOException; void deleteRelease(int id) throws ApplicationManagementDAOException;
void deleteReleases(List<Integer> applicationReleaseIds) throws ApplicationManagementDAOException;
/** /**
* To get release details of a specific application. * To get release details of a specific application.
@ -177,6 +178,10 @@ public interface ApplicationReleaseDAO {
* @return True if application release package name already exist in the IoT server, Otherwise returns False. * @return True if application release package name already exist in the IoT server, Otherwise returns False.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
boolean isActiveReleaseExisitForPackageName(String packageName, int tenantId, String inactiveState) throws ApplicationManagementDAOException; boolean isActiveReleaseExisitForPackageName(String packageName, int tenantId, String inactiveState)
throws ApplicationManagementDAOException;
boolean hasExistInstallableAppRelease(String releaseUuid, String installableStateName, int tenantId)
throws ApplicationManagementDAOException;
} }

@ -18,7 +18,7 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao; package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO; import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.util.List; import java.util.List;
@ -35,7 +35,7 @@ public interface LifecycleStateDAO {
* @return Latest Lifecycle State for the given application release * @return Latest Lifecycle State for the given application release
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
LifecycleStateDTO getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException; LifecycleState getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException;
/** /**
* To get the latest lifecycle state for the given application id and the application release UUID. * To get the latest lifecycle state for the given application id and the application release UUID.
@ -45,36 +45,38 @@ public interface LifecycleStateDAO {
* @return Latest Lifecycle State for the given application release * @return Latest Lifecycle State for the given application release
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
LifecycleStateDTO getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException; LifecycleState getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException;
/** /**
* To get all changed lifecycle states for the given application release id. * To get all changed lifecycle states for the given application release id.
* @param appReleaseId id of the application release. * @param appReleaseId id of the application release.
* @param tenantId Tenant Id.
* *
* @return Lifecycle States for the given application release * @return Lifecycle States for the given application release
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
List<LifecycleStateDTO> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException; List<LifecycleState> getLifecycleStates(int appReleaseId, int tenantId) throws LifeCycleManagementDAOException;
/** /**
* To add new lifecycle states for the given application release. * To add new lifecycle states for the given application release.
* @param uuid Id of the application release. * @param state LifecycleState.
* @param appId Id of the application.
* @param state LifecycleStateDTO.
* @param tenantId Tenant id * @param tenantId Tenant id
* *
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
void addLifecycleState(LifecycleStateDTO state, int appId, String uuid, int tenantId) void addLifecycleState(LifecycleState state, int appReleaseId, int tenantId)
throws LifeCycleManagementDAOException; throws LifeCycleManagementDAOException;
/** /**
* To delete a specific lifecycle state for application release. * To delete lifecycle state data of specific application release.
* @param identifier Id of the LifecycleStateDTO. * @param releaseId Id of the LifecycleState.
* *
* @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception. * @throws LifeCycleManagementDAOException Lifecycle Management DAO Exception.
*/ */
void deleteLifecycleState(int identifier) throws LifeCycleManagementDAOException; void deleteLifecycleStateByReleaseId(int releaseId) throws LifeCycleManagementDAOException;
void deleteLifecycleStates(List<Integer> appReleaseIds) throws LifeCycleManagementDAOException;
/*** /***
* *

@ -88,7 +88,7 @@ public interface SubscriptionDAO {
void subscribeGroupToApplication(int tenantId, String subscribedBy, List<DeviceGroup> groupList, int appId, void subscribeGroupToApplication(int tenantId, String subscribedBy, List<DeviceGroup> groupList, int appId,
int releaseId) throws ApplicationManagementDAOException; int releaseId) throws ApplicationManagementDAOException;
public List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId) throws List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
} }

@ -129,6 +129,7 @@ public class Util {
*/ */
public static ApplicationReleaseDTO loadAppRelease(ResultSet rs) throws SQLException { public static ApplicationReleaseDTO loadAppRelease(ResultSet rs) throws SQLException {
ApplicationReleaseDTO appRelease = new ApplicationReleaseDTO(); ApplicationReleaseDTO appRelease = new ApplicationReleaseDTO();
appRelease.setId(rs.getInt("RELEASE_ID"));
appRelease.setDescription(rs.getString("RELEASE_DESCRIPTION")); appRelease.setDescription(rs.getString("RELEASE_DESCRIPTION"));
appRelease.setUuid(rs.getString("RELEASE_UUID")); appRelease.setUuid(rs.getString("RELEASE_UUID"));
appRelease.setReleaseType(rs.getString("RELEASE_TYPE")); appRelease.setReleaseType(rs.getString("RELEASE_TYPE"));

@ -144,6 +144,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
+ "AP_APP.CURRENCY AS APP_CURRENCY, " + "AP_APP.CURRENCY AS APP_CURRENCY, "
+ "AP_APP.RATING AS APP_RATING, " + "AP_APP.RATING AS APP_RATING, "
+ "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, " + "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, "
+ "AP_APP_RELEASE.ID AS RELEASE_ID, "
+ "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, " + "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, "
+ "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, " + "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, "
+ "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + "AP_APP_RELEASE.UUID AS RELEASE_UUID, "
@ -456,7 +457,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, releaseUuid); stmt.setString(1, releaseUuid);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.setString(3, AppLifecycleState.REMOVED.toString()); stmt.setString(3, AppLifecycleState.RETIRED.toString());
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -502,6 +503,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
+ "AP_APP.CURRENCY AS APP_CURRENCY, " + "AP_APP.CURRENCY AS APP_CURRENCY, "
+ "AP_APP.RATING AS APP_RATING, " + "AP_APP.RATING AS APP_RATING, "
+ "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, " + "AP_APP.DEVICE_TYPE_ID AS APP_DEVICE_TYPE_ID, "
+ "AP_APP_RELEASE.ID AS RELEASE_ID, "
+ "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, " + "AP_APP_RELEASE.DESCRIPTION AS RELEASE_DESCRIPTION, "
+ "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, " + "AP_APP_RELEASE.VERSION AS RELEASE_VERSION, "
+ "AP_APP_RELEASE.UUID AS RELEASE_UUID, " + "AP_APP_RELEASE.UUID AS RELEASE_UUID, "
@ -619,14 +621,14 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public void deleteApplication(int appId) throws ApplicationManagementDAOException { public void retireApplication(int appId) throws ApplicationManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = "UPDATE AP_APP SET STATUS = ? WHERE ID = ? "; String sql = "UPDATE AP_APP SET STATUS = ? WHERE ID = ? ";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, AppLifecycleState.REMOVED.toString()); stmt.setString(1, AppLifecycleState.RETIRED.toString());
stmt.setInt(2, appId); stmt.setInt(2, appId);
stmt.executeUpdate(); stmt.executeUpdate();
@ -808,6 +810,34 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public void deleteCategoryMapping (int applicationId, int tenantId) throws ApplicationManagementDAOException{
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to delete Category mappings.");
}
Connection conn;
String sql = "DELETE FROM "
+ "AP_APP_CATEGORY_MAPPING cm "
+ "WHERE "
+ "cm.AP_APP_ID = ? AND "
+ "cm.TENANT_ID = ?";
try {
conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setInt(1, applicationId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when deleting category mapping of application ID: "
+ applicationId , e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred when deleting category mapping of application ID: "
+ applicationId, e);
}
}
@Override @Override
public List<Integer> getTagIdsForTagNames(List<String> tagNames, int tenantId) public List<Integer> getTagIdsForTagNames(List<String> tagNames, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
@ -931,12 +961,40 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when deleting tag mapppig", e); "Error occurred while obtaining the DB connection when deleting tag mapping", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred when deleting tag mapping", e); throw new ApplicationManagementDAOException("Error occurred when deleting tag mapping", e);
} }
} }
@Override
public void deleteTagMapping (int applicationId, int tenantId) throws ApplicationManagementDAOException{
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to delete Tag mappings.");
}
Connection conn;
String sql = "DELETE FROM "
+ "AP_APP_TAG_MAPPING tm "
+ "WHERE "
+ "tm.AP_APP_ID = ? AND "
+ "tm.TENANT_ID = ?";
try {
conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setInt(1, applicationId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when deleting tag mapping of application ID: "
+ applicationId , e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred when deleting tag mapping of application ID: "
+ applicationId, e);
}
}
@Override @Override
public List<String> getAppCategories(int appId, int tenantId) throws ApplicationManagementDAOException { public List<String> getAppCategories(int appId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -1132,4 +1190,31 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public void deleteApplication(int appId, int tenantId) throws ApplicationManagementDAOException {
Connection conn;
String sql;
try {
conn = this.getDBConnection();
sql = "DELETE AP_APP ap "
+ "WHERE ap.ID = ? AND "
+ "ap.TENANT_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)){
stmt.setInt(1, appId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining the DB connection to delete application for application id::."
+ appId;
log.error(msg);
throw new ApplicationManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while deleting application for application ID: " + appId;
log.error(msg);
throw new ApplicationManagementDAOException(msg, e);
}
}
} }

@ -226,7 +226,8 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
public ApplicationReleaseDTO getReleaseByUUID( String uuid, int tenantId) throws ApplicationManagementDAOException { public ApplicationReleaseDTO getReleaseByUUID( String uuid, int tenantId) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
String sql = String sql =
"SELECT AR.DESCRIPTION AS RELEASE_DESCRIPTION, " "SELECT AR.ID AS RELEASE_ID, "
+ "AR.DESCRIPTION AS RELEASE_DESCRIPTION, "
+ "AR.VERSION AS RELEASE_VERSION, " + "AR.VERSION AS RELEASE_VERSION, "
+ "AR.UUID AS RELEASE_UUID, " + "AR.UUID AS RELEASE_UUID, "
+ "AR.RELEASE_TYPE AS RELEASE_TYPE, " + "AR.RELEASE_TYPE AS RELEASE_TYPE, "
@ -490,35 +491,55 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
return applicationReleaseDTO; return applicationReleaseDTO;
} }
/** @Override
* To delete an application release. public void deleteRelease(int id) throws ApplicationManagementDAOException {
*
* @param id Id of the application Release.
* @param version version name of the application release.
* @throws ApplicationManagementDAOException ApplicationDTO Management DAO Exception.
*/
@Override public void deleteRelease(int id, String version) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
String sql = "DELETE FROM AP_APP_RELEASE WHERE ID = ? AND VERSION = ?"; String sql = "DELETE "
+ "FROM AP_APP_RELEASE "
+ "WHERE ID = ?";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setInt(1, id); statement.setInt(1, id);
statement.setString(2, version);
statement.executeUpdate(); statement.executeUpdate();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Database connection exception while trying to delete the release with version " + version, e); "Database connection exception while trying to delete the release fore release ID: " + id, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"SQL exception while deleting the release with version " + version + ",while executing the query " "SQL exception while deleting the release for release ID: " + id + ",while executing the query sql"
+ "sql", e); , e);
} finally { } finally {
Util.cleanupResources(statement, null); Util.cleanupResources(statement, null);
} }
} }
@Override
public void deleteReleases(List<Integer> applicationReleaseIds) throws ApplicationManagementDAOException{
Connection connection;
String sql = "DELETE "
+ "FROM AP_APP_RELEASE "
+ "WHERE ID = ?";
try {
connection = this.getDBConnection();
try (PreparedStatement statement = connection.prepareStatement(sql)){
for (Integer releaseId : applicationReleaseIds){
statement.setInt(1, releaseId);
statement.addBatch();
}
statement.executeBatch();
}
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Database connection exception occurred while trying to delete given application release", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"SQL exception occurred while execute delete query for deleting given application releases.", e);
}
}
@Override @Override
public boolean verifyReleaseExistenceByHash(String hashVal, int tenantId) throws ApplicationManagementDAOException { public boolean verifyReleaseExistenceByHash(String hashVal, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -732,4 +753,38 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
} }
} }
@Override
public boolean hasExistInstallableAppRelease(String releaseUuid, String installableStateName, int tenantId)
throws ApplicationManagementDAOException{
if (log.isDebugEnabled()) {
log.debug("Verifying application release existence in the installable state: :" + installableStateName);
}
Connection conn;
try {
conn = this.getDBConnection();
String sql = "SELECT AR.ID AS RELEASE_ID "
+ "FROM AP_APP_RELEASE AS AR "
+ "WHERE AR.CURRENT_STATE = ? AND "
+ "AR.AP_APP_ID = (SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID = ?) AND "
+ "AR.TENANT_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, installableStateName);
stmt.setString(2, releaseUuid);
stmt.setInt(3, tenantId);
try (ResultSet rs = stmt.executeQuery()) {
return rs.next();
}
}
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred while getting application release details in installable state: "
+ installableStateName, e);
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection to get application release data in installable "
+ "state.", e);
}
}
} }

@ -19,7 +19,7 @@
package org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate; package org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate;
import org.wso2.carbon.device.application.mgt.common.AppLifecycleState; import org.wso2.carbon.device.application.mgt.common.AppLifecycleState;
import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO; import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
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.common.Util; import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
@ -41,7 +41,7 @@ import java.util.List;
public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements LifecycleStateDAO { public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements LifecycleStateDAO {
@Override @Override
public LifecycleStateDTO getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException { public LifecycleState getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
@ -65,7 +65,7 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
} }
} }
public LifecycleStateDTO getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException{ public LifecycleState getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException{
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -122,40 +122,45 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
} }
@Override @Override
public List<LifecycleStateDTO> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException { public List<LifecycleState> getLifecycleStates(int appReleaseId, int tenantId) throws LifeCycleManagementDAOException {
List<LifecycleStateDTO> lifecycleStates = new ArrayList<>(); List<LifecycleState> lifecycleStates = new ArrayList<>();
Connection conn = null; Connection conn ;
PreparedStatement stmt = null;
ResultSet rs = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = "SELECT ID, CURRENT_STATE, PREVIOUS_STATE, TENANT_ID, UPDATED_AT, UPDATED_BY FROM " String sql = "SELECT "
+ "AP_APP_LIFECYCLE_STATE WHERE AP_APP_RELEASE_ID = ? ORDER BY UPDATED_AT ASC;"; + "CURRENT_STATE, "
stmt = conn.prepareStatement(sql); + "PREVIOUS_STATE, "
stmt.setInt(1,appReleaseId); + "UPDATED_AT, "
rs = stmt.executeQuery(); + "UPDATED_BY "
while (rs.next()) { + "FROM AP_APP_LIFECYCLE_STATE "
LifecycleStateDTO lifecycleState = new LifecycleStateDTO(); + "WHERE AP_APP_RELEASE_ID = ? AND "
lifecycleState.setId(rs.getInt("ID")); + "TENANT_ID = ? "
lifecycleState.setCurrentState(rs.getString("CURRENT_STATE")); + "ORDER BY UPDATED_AT ASC;";
lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE")); try (PreparedStatement stmt = conn.prepareStatement(sql)){
lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT")); stmt.setInt(1,appReleaseId);
lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY")); stmt.setInt(2, tenantId);
lifecycleStates.add(lifecycleState); try (ResultSet rs = stmt.executeQuery()){
while (rs.next()) {
LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE"));
lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT"));
lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY"));
lifecycleStates.add(lifecycleState);
}
}
} }
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection when getting " throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection when getting "
+ "lifecycle states for an application", e); + "lifecycle states for an application", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while retrieving lifecycle states.", e); throw new LifeCycleManagementDAOException("Error occurred while retrieving lifecycle states.", e);
} finally {
Util.cleanupResources(stmt, rs);
} }
return lifecycleStates; return lifecycleStates;
} }
@Override @Override
public void addLifecycleState(LifecycleStateDTO state, int appId, String uuid, int tenantId) throws LifeCycleManagementDAOException { public void addLifecycleState(LifecycleState state, int appReleaseId, int tenantId) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
@ -168,7 +173,7 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
+ "UPDATED_AT, " + "UPDATED_AT, "
+ "AP_APP_RELEASE_ID, " + "AP_APP_RELEASE_ID, "
+ "AP_APP_ID) " + "AP_APP_ID) "
+ "VALUES (?,?, ?, ?, ?, (SELECT ID FROM AP_APP_RELEASE WHERE UUID=?),?);"; + "VALUES (?, ?, ?, ?, ?, ?, (SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE ID = ?));";
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
Timestamp timestamp = new Timestamp(calendar.getTime().getTime()); Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
@ -179,10 +184,9 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.setString(4, state.getUpdatedBy()); stmt.setString(4, state.getUpdatedBy());
stmt.setTimestamp(5, timestamp); stmt.setTimestamp(5, timestamp);
stmt.setString(6, uuid); stmt.setInt(6, appReleaseId);
stmt.setInt(7, appId); stmt.setInt(7, appReleaseId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) { } catch (SQLException e) {
@ -193,32 +197,55 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
} }
@Override @Override
public void deleteLifecycleState(int identifier) throws LifeCycleManagementDAOException { public void deleteLifecycleStateByReleaseId(int releaseId) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = "DELETE FROM AP_APP_LIFECYCLE_STATE WHERE ID = ?"; String sql = "DELETE FROM " +
stmt = conn.prepareStatement(sql); "AP_APP_LIFECYCLE_STATE " +
stmt.setInt(1, identifier); "WHERE AP_APP_RELEASE_ID = ?";
stmt.executeUpdate(); try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, releaseId);
stmt.executeUpdate();
}
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while deleting lifecycle: " + identifier, e); throw new LifeCycleManagementDAOException("Error occurred while deleting lifecycle for application "
} finally { + "release ID: " + releaseId, e);
Util.cleanupResources(stmt, rs);
} }
} }
private LifecycleStateDTO constructLifecycle(ResultSet rs) throws LifeCycleManagementDAOException { @Override
LifecycleStateDTO lifecycleState = null; public void deleteLifecycleStates(List<Integer> appReleaseIds) throws LifeCycleManagementDAOException{
Connection conn;
try {
conn = this.getDBConnection();
String sql = "DELETE FROM " +
"AP_APP_LIFECYCLE_STATE " +
"WHERE AP_APP_RELEASE_ID = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
for (Integer releaseId : appReleaseIds) {
stmt.setInt(1, releaseId);
stmt.addBatch();
}
stmt.executeBatch();
}
} catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection for deleting "
+ "application life-cycle states for given application Ids.", e);
} catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while deleting life-cycle states for given "
+ "application releases.", e);
}
}
private LifecycleState constructLifecycle(ResultSet rs) throws LifeCycleManagementDAOException {
LifecycleState lifecycleState = null;
try { try {
if (rs !=null && rs.next()) { if (rs !=null && rs.next()) {
lifecycleState = new LifecycleStateDTO(); lifecycleState = new LifecycleState();
lifecycleState.setId(rs.getInt("ID"));
lifecycleState.setCurrentState(rs.getString("CURRENT_STATE")); lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE")); lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE"));
lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT")); lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT"));

@ -21,7 +21,7 @@ import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManage
/** /**
* Exception thrown during the ApplicationDTO Management DAO operations. * Exception thrown during the ApplicationDTO Management DAO operations.
*/ */
public class ApplicationManagementDAOException extends ApplicationManagementException { public class ApplicationManagementDAOException extends Exception {
public ApplicationManagementDAOException(String message, Throwable throwable) { public ApplicationManagementDAOException(String message, Throwable throwable) {
super(message, throwable); super(message, throwable);

@ -27,7 +27,6 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.AppLifecycleState;
import org.wso2.carbon.device.application.mgt.common.ApplicationArtifact; import org.wso2.carbon.device.application.mgt.common.ApplicationArtifact;
import org.wso2.carbon.device.application.mgt.common.ApplicationInstaller; import org.wso2.carbon.device.application.mgt.common.ApplicationInstaller;
import org.wso2.carbon.device.application.mgt.common.Pagination; import org.wso2.carbon.device.application.mgt.common.Pagination;
@ -40,7 +39,7 @@ import org.wso2.carbon.device.application.mgt.common.ApplicationType;
import org.wso2.carbon.device.application.mgt.common.dto.CategoryDTO; import org.wso2.carbon.device.application.mgt.common.dto.CategoryDTO;
import org.wso2.carbon.device.application.mgt.common.Filter; import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.dto.DeviceSubscriptionDTO; import org.wso2.carbon.device.application.mgt.common.dto.DeviceSubscriptionDTO;
import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO; import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.dto.TagDTO; import org.wso2.carbon.device.application.mgt.common.dto.TagDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; 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.ApplicationStorageManagementException;
@ -312,10 +311,10 @@ public class ApplicationManagerImpl implements ApplicationManager {
applicationReleaseDTO.setCurrentState(initialLifecycleState); applicationReleaseDTO.setCurrentState(initialLifecycleState);
applicationReleaseDTO = this.applicationReleaseDAO applicationReleaseDTO = this.applicationReleaseDAO
.createRelease(applicationReleaseDTO, appId, tenantId); .createRelease(applicationReleaseDTO, appId, tenantId);
LifecycleStateDTO lifecycleStateDTO = getLifecycleStateInstance(initialLifecycleState, LifecycleState lifecycleState = getLifecycleStateInstance(initialLifecycleState,
initialLifecycleState); initialLifecycleState);
this.lifecycleStateDAO this.lifecycleStateDAO
.addLifecycleState(lifecycleStateDTO, appId, applicationReleaseDTO.getUuid(), tenantId); .addLifecycleState(lifecycleState, applicationReleaseDTO.getId(), tenantId);
applicationReleaseEntities.add(applicationReleaseDTO); applicationReleaseEntities.add(applicationReleaseDTO);
applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities); applicationDTO.setApplicationReleaseDTOs(applicationReleaseEntities);
Application application = appDtoToAppResponse(applicationDTO); Application application = appDtoToAppResponse(applicationDTO);
@ -738,18 +737,19 @@ public class ApplicationManagerImpl implements ApplicationManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("ApplicationDTO release request is received for the application id: " + applicationId); log.debug("ApplicationDTO release request is received for the application id: " + applicationId);
} }
ApplicationDTO applicationDTO = getApplication(applicationId);
try { try {
ApplicationDTO applicationDTO = getApplication(applicationId);
ApplicationReleaseDTO applicationReleaseDTO = uploadReleaseArtifacts(applicationReleaseWrapper, ApplicationReleaseDTO applicationReleaseDTO = uploadReleaseArtifacts(applicationReleaseWrapper,
applicationDTO, applicationArtifact); applicationDTO, applicationArtifact);
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
String initialstate = lifecycleStateManager.getInitialState(); String initialstate = lifecycleStateManager.getInitialState();
applicationReleaseDTO.setCurrentState(initialstate); applicationReleaseDTO.setCurrentState(initialstate);
LifecycleStateDTO lifecycleState = getLifecycleStateInstance(initialstate, initialstate); LifecycleState lifecycleState = getLifecycleStateInstance(initialstate, initialstate);
applicationReleaseDTO = this.applicationReleaseDAO applicationReleaseDTO = this.applicationReleaseDAO
.createRelease(applicationReleaseDTO, applicationDTO.getId(), tenantId); .createRelease(applicationReleaseDTO, applicationDTO.getId(), tenantId);
this.lifecycleStateDAO this.lifecycleStateDAO
.addLifecycleState(lifecycleState, applicationId, applicationReleaseDTO.getUuid(), tenantId); .addLifecycleState(lifecycleState, applicationReleaseDTO.getId(), tenantId);
applicationRelease = releaseDtoToRelease(applicationReleaseDTO); applicationRelease = releaseDtoToRelease(applicationReleaseDTO);
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
return applicationRelease; return applicationRelease;
@ -820,11 +820,10 @@ public class ApplicationManagerImpl implements ApplicationManager {
public Application getApplicationById(int appId, String state) throws ApplicationManagementException { public Application getApplicationById(int appId, String state) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
ApplicationDTO applicationDTO;
boolean isVisibleApp = false; boolean isVisibleApp = false;
try { ApplicationDTO applicationDTO = getApplication(appId);
applicationDTO = getApplication(appId);
try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
List<ApplicationReleaseDTO> filteredApplicationReleaseDTOs = new ArrayList<>(); List<ApplicationReleaseDTO> filteredApplicationReleaseDTOs = new ArrayList<>();
for (ApplicationReleaseDTO applicationReleaseDTO : applicationDTO.getApplicationReleaseDTOs()) { for (ApplicationReleaseDTO applicationReleaseDTO : applicationDTO.getApplicationReleaseDTOs()) {
@ -873,6 +872,10 @@ public class ApplicationManagerImpl implements ApplicationManager {
String msg = "User-store exception while getting application with the application id " + appId; String msg = "User-store exception while getting application with the application id " + appId;
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occured when getting, either application tags or application categories";
log.error(msg);
throw new ApplicationManagementException(msg);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -919,6 +922,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
String msg = "User-store exception while getting application with the application release UUID: " + uuid; String msg = "User-store exception while getting application with the application release UUID: " + uuid;
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -961,6 +967,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new ApplicationManagementException( throw new ApplicationManagementException(
"User-store exception while getting application with the application release UUID " + uuid); "User-store exception while getting application with the application release UUID " + uuid);
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -1057,6 +1066,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new ApplicationManagementException( throw new ApplicationManagementException(
"User-store exception while getting application with the " + "application name " + appName); "User-store exception while getting application with the " + "application name " + appName);
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -1078,6 +1090,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new ApplicationManagementException( throw new ApplicationManagementException(
"User-store exception while getting application with the application UUID " + appReleaseUUID); "User-store exception while getting application with the application UUID " + appReleaseUUID);
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -1092,9 +1107,16 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.debug("Request is received to retrieve all the releases related with the application " + application log.debug("Request is received to retrieve all the releases related with the application " + application
.toString()); .toString());
} }
applicationReleases = this.applicationReleaseDAO.getReleases(application.getId(), tenantId); //todo
applicationReleases = null;
try {
applicationReleases = this.applicationReleaseDAO.getReleases(application.getId(), tenantId);
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
}
for (ApplicationReleaseDTO applicationRelease : applicationReleases) { for (ApplicationReleaseDTO applicationRelease : applicationReleases) {
LifecycleStateDTO lifecycleState = null; LifecycleState lifecycleState = null;
try { try {
lifecycleState = this.lifecycleStateDAO.getLatestLifeCycleStateByReleaseID(applicationRelease.getId()); lifecycleState = this.lifecycleStateDAO.getLatestLifeCycleStateByReleaseID(applicationRelease.getId());
} catch (LifeCycleManagementDAOException e) { } catch (LifeCycleManagementDAOException e) {
@ -1117,7 +1139,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
// //
// if (state != null && !state.isEmpty()) { // if (state != null && !state.isEmpty()) {
// for (ApplicationReleaseDTO applicationRelease : applicationReleases) { // for (ApplicationReleaseDTO applicationRelease : applicationReleases) {
// if (state.equals(applicationRelease.getLifecycleState().getCurrentState())) { // if (state.equals(applicationRelease.getLifecycleStateChangeFlow().getCurrentState())) {
// filteredReleases.add(applicationRelease); // filteredReleases.add(applicationRelease);
// } // }
// } // }
@ -1125,9 +1147,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
// if (AppLifecycleState.PUBLISHED.toString().equals(state) && filteredReleases.size() > 1) { // if (AppLifecycleState.PUBLISHED.toString().equals(state) && filteredReleases.size() > 1) {
// log.warn("There are more than one application releases is found which is in PUBLISHED state"); // log.warn("There are more than one application releases is found which is in PUBLISHED state");
// filteredReleases.sort((r1, r2) -> { // filteredReleases.sort((r1, r2) -> {
// if (r1.getLifecycleState().getUpdatedAt().after(r2.getLifecycleState().getUpdatedAt())) { // if (r1.getLifecycleStateChangeFlow().getUpdatedAt().after(r2.getLifecycleStateChangeFlow().getUpdatedAt())) {
// return -1; // return -1;
// } else if (r2.getLifecycleState().getUpdatedAt().after(r1.getLifecycleState().getUpdatedAt())) { // } else if (r2.getLifecycleStateChangeFlow().getUpdatedAt().after(r1.getLifecycleStateChangeFlow().getUpdatedAt())) {
// return 1; // return 1;
// } // }
// return 0; // return 0;
@ -1140,28 +1162,83 @@ public class ApplicationManagerImpl implements ApplicationManager {
@Override @Override
public void deleteApplication(int applicationId) throws ApplicationManagementException { public void deleteApplication(int applicationId) throws ApplicationManagementException {
if (log.isDebugEnabled()) {
log.debug("Request is received to delete applications which are related with the application id "
+ applicationId);
}
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager(); ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager();
List<String> storedLocations = new ArrayList<>(); ApplicationDTO applicationDTO = getApplication(applicationId);
ApplicationDTO applicationDTO; List<ApplicationReleaseDTO> applicationReleaseDTOs = applicationDTO.getApplicationReleaseDTOs();
for (ApplicationReleaseDTO applicationReleaseDTO : applicationReleaseDTOs) {
if (!lifecycleStateManager.isDeletableState(applicationReleaseDTO.getCurrentState())){
String msg = "Application release which has application release UUID: " +
applicationReleaseDTO.getUuid() + " is not in a deletable state. Therefore Application "
+ "deletion is not permitted. In order to delete the application, all application releases "
+ "of the application has to be in a deletable state.";
log.error(msg);
throw new ForbiddenException(msg);
}
}
try {
ConnectionManagerUtil.beginDBTransaction();
List<Integer> deletingAppReleaseIds = new ArrayList<>();
for (ApplicationReleaseDTO applicationReleaseDTO : applicationReleaseDTOs) {
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId);
if (!deviceSubscriptionDTOS.isEmpty()){
String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid() +
" either subscribed to device/s or it had subscribed to device/s. Therefore you are not "
+ "permitted to delete the application release.";
log.error(msg);
throw new ForbiddenException(msg);
}
applicationStorageManager.deleteApplicationReleaseArtifacts(applicationReleaseDTO.getAppHashValue());
deletingAppReleaseIds.add(applicationReleaseDTO.getId());
}
this.lifecycleStateDAO.deleteLifecycleStates(deletingAppReleaseIds);
this.applicationReleaseDAO.deleteReleases(deletingAppReleaseIds);
this.applicationDAO.deleteTagMapping(applicationId, tenantId);
this.applicationDAO.deleteCategoryMapping(applicationId, tenantId);
this.applicationDAO.deleteApplication(applicationId, tenantId);
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred when getting application data for application id: " + applicationId;
log.error(msg);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationStorageManagementException e) {
String msg = "Error occurred when deleting application artifacts in the file system. Application id: "
+ applicationId;
log.error(msg);
throw new ApplicationManagementException(msg);
} catch (LifeCycleManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured while deleting life-cycle state data of application releases of the application"
+ " which has application ID: " + applicationId;
log.error(msg);
throw new ApplicationManagementException(msg);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
public void retireApplication(int applicationId) throws ApplicationManagementException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request is received to delete applications which are related with the application id " log.debug("Request is received to delete applications which are related with the application id "
+ applicationId); + applicationId);
} }
ApplicationDTO applicationDTO = getApplication(applicationId);
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
applicationDTO = this.applicationDAO.getApplicationById(applicationId, tenantId);
if (applicationDTO == null) {
throw new NotFoundException("Couldn't found an application for Application ID: " + applicationId);
}
List<ApplicationReleaseDTO> applicationReleaseDTOs = applicationDTO.getApplicationReleaseDTOs(); List<ApplicationReleaseDTO> applicationReleaseDTOs = applicationDTO.getApplicationReleaseDTOs();
List<ApplicationReleaseDTO> activeApplicationReleaseDTOs = new ArrayList<>(); List<ApplicationReleaseDTO> activeApplicationReleaseDTOs = new ArrayList<>();
for (ApplicationReleaseDTO applicationReleaseDTO : applicationReleaseDTOs) { for (ApplicationReleaseDTO applicationReleaseDTO : applicationReleaseDTOs) {
if (!applicationReleaseDTO.getCurrentState().equals(lifecycleStateManager.getEndState())){ if (!applicationReleaseDTO.getCurrentState().equals(lifecycleStateManager.getEndState())) {
activeApplicationReleaseDTOs.add(applicationReleaseDTO); activeApplicationReleaseDTOs.add(applicationReleaseDTO);
} }
storedLocations.add(applicationReleaseDTO.getAppHashValue());
} }
if (!activeApplicationReleaseDTOs.isEmpty()) { if (!activeApplicationReleaseDTOs.isEmpty()) {
String msg = "There are application releases which are not in the state " + lifecycleStateManager String msg = "There are application releases which are not in the state " + lifecycleStateManager
@ -1169,18 +1246,12 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg); log.error(msg);
throw new ForbiddenException(msg); throw new ForbiddenException(msg);
} }
this.applicationDAO.deleteApplication(applicationId); this.applicationDAO.retireApplication(applicationId);
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
applicationStorageManager.deleteAllApplicationReleaseArtifacts(storedLocations);
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
String msg = "Error occurred when getting application data for application id: " + applicationId; String msg = "Error occurred when getting application data for application id: " + applicationId;
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (ApplicationStorageManagementException e) {
String msg = "Error occurred when deleting application artifacts in the file system. Application id: "
+ applicationId;
log.error(msg);
throw new ApplicationManagementException(msg);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -1201,7 +1272,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
if (currentNode.equals(finish)) { if (currentNode.equals(finish)) {
break; break;
} else { } else {
Set<String> nextStates = lifecycleStateManager.getNextLifecycleStates(currentNode); List<String> nextStates = lifecycleStateManager.getNextLifecycleStates(currentNode);
if (nextStates.contains(finish)) { if (nextStates.contains(finish)) {
queue = new LinkedList<>(); queue = new LinkedList<>();
queue.add(finish); queue.add(finish);
@ -1234,7 +1305,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
@Override @Override
public void deleteApplicationRelease(int applicationId, String releaseUuid) public void deleteApplicationRelease(String releaseUuid)
throws ApplicationManagementException { throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager(); ApplicationStorageManager applicationStorageManager = Util.getApplicationStorageManager();
@ -1248,77 +1319,38 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new NotFoundException(msg); throw new NotFoundException(msg);
} }
if (!applicationReleaseDTO.getCurrentState().equals(lifecycleStateManager.getInitialState())) { if (!lifecycleStateManager.isDeletableState(applicationReleaseDTO.getCurrentState())) {
String msg = "Application state is not in the initial state: " + lifecycleStateManager.getInitialState() String msg = "Application state is not in the deletable state. Therefore you are not permitted to "
+ ". Therefore you are not permitted to delete the application release."; + "delete the application release.";
log.error(msg); log.error(msg);
throw new ForbiddenException(msg); throw new ForbiddenException(msg);
} }
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId); .getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId);
for (DeviceSubscriptionDTO deviceSubscriptionDTO : deviceSubscriptionDTOS) { if (!deviceSubscriptionDTOS.isEmpty()){
if (!deviceSubscriptionDTO.isUnsubscribed()) { String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid() +
String msg = "This application is subscribed to device/s. Therefore you are not permitted to delete " " either subscribed to device/s or it had subscribed to device/s. Therefore you are not "
+ "the application release."; + "permitted to delete the application release.";
log.error(msg); log.error(msg);
throw new ForbiddenException(msg); throw new ForbiddenException(msg);
}
} }
//todo delete application release data ON delete cascade
applicationStorageManager.deleteApplicationReleaseArtifacts(applicationReleaseDTO.getAppHashValue()); applicationStorageManager.deleteApplicationReleaseArtifacts(applicationReleaseDTO.getAppHashValue());
lifecycleStateDAO.deleteLifecycleStateByReleaseId(applicationReleaseDTO.getId());
// LifecycleStateDTO appLifecycleState = this.lifecycleStateDAO applicationReleaseDAO.deleteRelease(applicationReleaseDTO.getId());
// .getLatestLifeCycleState(applicationId, releaseUuid); ConnectionManagerUtil.commitDBTransaction();
// if (appLifecycleState == null) {
// throw new NotFoundException(
// "Couldn't find an lifecycle sate for application ID: " + applicationId + " and UUID: "
// + releaseUuid);
// }
// String currentState = appLifecycleState.getCurrentState();
// if (AppLifecycleState.DEPRECATED.toString().equals(currentState) || AppLifecycleState.REJECTED.toString()
// .equals(currentState) || AppLifecycleState.UNPUBLISHED.toString().equals(currentState)) {
// LifecycleStateDTO newAppLifecycleState = getLifecycleStateInstance(AppLifecycleState.REMOVED.toString(),
// appLifecycleState.getCurrentState());
// if (lifecycleStateManager.isValidStateChange(newAppLifecycleState.getPreviousState(),
// newAppLifecycleState.getCurrentState(), userName, tenantId)) {
// this.lifecycleStateDAO
// .addLifecycleState(newAppLifecycleState, applicationId, applicationRelease.getUuid(),
// tenantId);
// ConnectionManagerUtil.commitDBTransaction();
// } else {
// List<String> lifecycleFlow = searchLifecycleStateFlow(currentState,
// AppLifecycleState.REMOVED.toString());
// for (String nextState : lifecycleFlow) {
// LifecycleStateDTO lifecycleState = getLifecycleStateInstance(nextState, currentState);
// if (lifecycleStateManager.isValidStateChange(currentState, nextState, userName, tenantId)) {
// this.lifecycleStateDAO
// .addLifecycleState(lifecycleState, applicationId, applicationRelease.getUuid(),
// tenantId);
// } else {
// ConnectionManagerUtil.rollbackDBTransaction();
// throw new ApplicationManagementException(
// "Can't delete the application release, You have to move the "
// + "lifecycle state from " + currentState + " to " + nextState);
// }
// currentState = nextState;
// }
// }
// } else {
// throw new ApplicationManagementException(
// "Can't delete the application release, You have to move the " + "lifecycle state from "
// + currentState + " to acceptable " + "state");
// }
// return applicationReleaseDTO.getAppHashValue();
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error ocured when getting application data or application release data for application id of " String msg = "Error occurred when application release data for application release UUID: " + releaseUuid;
+ applicationId + " application release UUID of the " + releaseUuid; throw new ApplicationManagementException(msg, e);
throw new ApplicationManagementDAOException(msg, e);
} catch (ApplicationStorageManagementException e) { } catch (ApplicationStorageManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Error occurred when deleting the application release artifact from the file system. "
String msg = "Error occured when deleteing the application release artifact from the file system. Application release UUID: " + releaseUuid; + "Application release UUID: " + releaseUuid;
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} catch (LifeCycleManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred when dleting lifecycle data for application release UUID: " + releaseUuid;
throw new ApplicationManagementException(msg, e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -1533,69 +1565,84 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
@Override @Override
public LifecycleStateDTO getLifecycleState(int applicationId, String releaseUuid) public List<LifecycleState> getLifecycleStateChangeFlow(String releaseUuid) throws ApplicationManagementException {
throws ApplicationManagementException { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
LifecycleStateDTO lifecycleState;
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
lifecycleState = this.lifecycleStateDAO.getLatestLifeCycleState(applicationId, releaseUuid); ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO
if (lifecycleState == null) { .getReleaseByUUID(releaseUuid, tenantId);
return null; if (applicationReleaseDTO == null) {
String msg = "Couldn't found an application release for application release UUID: " + releaseUuid;
log.error(msg);
throw new NotFoundException(msg);
} }
lifecycleState.setNextStates(new ArrayList<>(lifecycleStateManager.getNextLifecycleStates(lifecycleState.getCurrentState()))); return this.lifecycleStateDAO.getLifecycleStates(applicationReleaseDTO.getId(), tenantId);
} catch (LifeCycleManagementDAOException e) { } catch (LifeCycleManagementDAOException e) {
throw new ApplicationManagementException("Failed to get lifecycle state from database", e); String msg = "Failed to get lifecycle state for application release uuid " + releaseUuid;
log.error(msg);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg =
"Error occurred while getting application release for application release UUID: " + releaseUuid;
log.error(msg);
throw new ApplicationManagementException(msg, e);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
return lifecycleState;
} }
@Override @Override
public void changeLifecycleState(int applicationId, String releaseUuid, LifecycleStateDTO state) public void changeLifecycleState(String releaseUuid, String stateName)
throws ApplicationManagementException { throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
if (!this.applicationDAO.verifyApplicationExistenceById(applicationId, tenantId)) { ApplicationReleaseDTO applicationReleaseDTO = this.applicationReleaseDAO
throw new NotFoundException("Couldn't find application for the application Id: " + applicationId); .getReleaseByUUID(releaseUuid, tenantId);
}
if (!this.applicationReleaseDAO.verifyReleaseExistence(applicationId, releaseUuid, tenantId)) { if (applicationReleaseDTO == null) {
throw new NotFoundException("Couldn't find application release for the application Id: " + applicationId String msg = "Couldn't found an application release for the UUID: " + releaseUuid;
+ " application release uuid: " + releaseUuid); log.error(msg);
throw new NotFoundException(msg);
} }
LifecycleStateDTO currentState = this.lifecycleStateDAO.getLatestLifeCycleState(applicationId, releaseUuid);
if (currentState == null) { if (lifecycleStateManager
throw new ApplicationManagementException( .isValidStateChange(applicationReleaseDTO.getCurrentState(), stateName, userName, tenantId)) {
"Couldn't find latest lifecycle state for the appId: " + applicationId if (lifecycleStateManager.isInstallableState(stateName) && applicationReleaseDAO
+ " and application release UUID: " + releaseUuid); .hasExistInstallableAppRelease(applicationReleaseDTO.getUuid(),
} lifecycleStateManager.getInstallableState(), tenantId)) {
state.setPreviousState(currentState.getCurrentState()); String msg = "Installable application release is already registered for the application. "
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + "Therefore it is not permitted to change the lifecycle state from "
state.setUpdatedBy(userName); + applicationReleaseDTO.getCurrentState() + " to " + stateName;
log.error(msg);
if (state.getCurrentState() != null && state.getPreviousState() != null) { throw new ForbiddenException(msg);
if (lifecycleStateManager.isValidStateChange(state.getPreviousState(), state.getCurrentState(),
userName, tenantId)) {
//todo if current state of the adding lifecycle state is PUBLISHED, need to check whether is there
//todo any other application release in PUBLISHED state for the application( i.e for the appid)
this.lifecycleStateDAO.addLifecycleState(state, applicationId, releaseUuid, tenantId);
ConnectionManagerUtil.commitDBTransaction();
} else {
ConnectionManagerUtil.rollbackDBTransaction();
log.error("Invalid lifecycle state transition from '" + state.getPreviousState() + "'" + " to '"
+ state.getCurrentState() + "'");
throw new ApplicationManagementException(
"Lifecycle State Validation failed. ApplicationDTO Id: " + applicationId
+ " ApplicationDTO release UUID: " + releaseUuid);
} }
LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setCurrentState(stateName);
lifecycleState.setPreviousState(applicationReleaseDTO.getCurrentState());
lifecycleState.setUpdatedBy(userName);
applicationReleaseDTO.setCurrentState(stateName);
this.applicationReleaseDAO.updateRelease(applicationReleaseDTO, tenantId);
this.lifecycleStateDAO.addLifecycleState(lifecycleState, applicationReleaseDTO.getId(), tenantId);
ConnectionManagerUtil.commitDBTransaction();
} else {
String msg = "Invalid lifecycle state transition from '" + applicationReleaseDTO.getCurrentState() + "'"
+ " to '" + stateName + "'";
log.error(msg);
throw new ApplicationManagementException(msg);
} }
} catch (LifeCycleManagementDAOException e) { } catch (LifeCycleManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction(); ConnectionManagerUtil.rollbackDBTransaction();
throw new ApplicationManagementException( String msg = "Failed to add lifecycle state for Application release UUID: " + releaseUuid;
"Failed to add lifecycle state. ApplicationDTO Id: " + applicationId + " ApplicationDTO release UUID: " log.error(msg);
+ releaseUuid, e); throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred when accessing application release data of application release which has the "
+ "application release UUID: " + releaseUuid;
log.error(msg);
throw new ApplicationManagementException(msg);
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -1630,19 +1677,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
ApplicationDTO applicationDTO; ApplicationDTO applicationDTO = getApplication(applicationId);
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
applicationDTO = this.applicationDAO.getApplicationById(applicationId, tenantId);
if (applicationDTO == null) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Tried to update Application which is not in the publisher. Please verify "
+ "application details";
log.error(msg);
throw new NotFoundException(msg);
}
if (!StringUtils.isEmpty(applicationUpdateWrapper.getName())){ if (!StringUtils.isEmpty(applicationUpdateWrapper.getName())){
Filter filter = new Filter(); Filter filter = new Filter();
filter.setFullMatch(true); filter.setFullMatch(true);
@ -1873,11 +1910,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
* By invoking the method, it returns Lifecycle State Instance. * By invoking the method, it returns Lifecycle State Instance.
* @param currentState Current state of the lifecycle * @param currentState Current state of the lifecycle
* @param previousState Previouse state of the Lifecycle * @param previousState Previouse state of the Lifecycle
* @return {@link LifecycleStateDTO} * @return {@link LifecycleState}
*/ */
private LifecycleStateDTO getLifecycleStateInstance(String currentState, String previousState) { private LifecycleState getLifecycleStateInstance(String currentState, String previousState) {
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
LifecycleStateDTO lifecycleState = new LifecycleStateDTO(); LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setCurrentState(currentState); lifecycleState.setCurrentState(currentState);
lifecycleState.setPreviousState(previousState); lifecycleState.setPreviousState(previousState);
lifecycleState.setUpdatedBy(userName); lifecycleState.setUpdatedBy(userName);

@ -20,7 +20,7 @@ package org.wso2.carbon.device.application.mgt.core.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.State; import org.wso2.carbon.device.application.mgt.common.config.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; 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.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException; import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
@ -60,7 +60,7 @@ public class AppmDataHandlerImpl implements AppmDataHandler {
} }
@Override @Override
public Map<String, State> getLifecycleConfiguration() throws LifecycleManagementException { public Map<String, LifecycleState> getLifecycleConfiguration() throws LifecycleManagementException {
return lifecycleStateManager.getLifecycleConfig(); return lifecycleStateManager.getLifecycleConfig();
} }

@ -28,6 +28,7 @@ import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.core.dao.SubscriptionDAO; import org.wso2.carbon.device.application.mgt.core.dao.SubscriptionDAO;
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.ApplicationManagementDAOException;
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;
import org.wso2.carbon.device.application.mgt.core.util.HelperUtil; import org.wso2.carbon.device.application.mgt.core.util.HelperUtil;
@ -109,6 +110,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
subscriptionDAO.subscribeUserToApplication(tenantId, subscriber, userList, application.getId(), subscriptionDAO.subscribeUserToApplication(tenantId, subscriber, userList, application.getId(),
applicationReleaseId); applicationReleaseId);
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -150,6 +154,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
subscriptionDAO.subscribeRoleToApplication(tenantId, subscriber, roleList, application.getId(), subscriptionDAO.subscribeRoleToApplication(tenantId, subscriber, roleList, application.getId(),
applicationReleaseId); applicationReleaseId);
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -194,6 +201,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
subscriptionDAO.subscribeGroupToApplication(tenantId, subscriber, groupList, application.getId(), subscriptionDAO.subscribeGroupToApplication(tenantId, subscriber, groupList, application.getId(),
applicationReleaseId); applicationReleaseId);
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
@ -252,6 +262,9 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
} }
subscriptionDAO.subscribeDeviceToApplication(tenantId, subscriber, deviceList, application.getId(), subscriptionDAO.subscribeDeviceToApplication(tenantId, subscriber, deviceList, application.getId(),
applicationReleaseId, String.valueOf(AppOperation.InstallState.UNINSTALLED)); applicationReleaseId, String.valueOf(AppOperation.InstallState.UNINSTALLED));
} catch (ApplicationManagementDAOException e) {
//todo
throw new ApplicationManagementException("");
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }

@ -19,7 +19,6 @@ package org.wso2.carbon.device.application.mgt.core.lifecycle;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.State;
import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException; import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
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.common.config.LifecycleState; import org.wso2.carbon.device.application.mgt.common.config.LifecycleState;
@ -33,38 +32,36 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
/** /**
* This class represents the activities related to lifecycle management * This class represents the activities related to lifecycle management
*/ */
public class LifecycleStateManager { public class LifecycleStateManager {
private Map<String, State> lifecycleStates; private Map<String, LifecycleState> lifecycleStates;
private static Log log = LogFactory.getLog(LifecycleStateManager.class); private static Log log = LogFactory.getLog(LifecycleStateManager.class);
public void init(List<LifecycleState> states) throws LifecycleManagementException { public void init(List<LifecycleState> states) throws LifecycleManagementException {
lifecycleStates = new HashMap<>(); lifecycleStates = new HashMap<>();
for (LifecycleState s : states) { for (LifecycleState lifecycleState : states) {
if (s.getProceedingStates() != null) { if (lifecycleState.getProceedingStates() != null) {
s.getProceedingStates().replaceAll(String::toUpperCase); lifecycleState.getProceedingStates().replaceAll(String::toUpperCase);
} }
lifecycleStates.put(s.getName().toUpperCase(), new State(s.getName().toUpperCase(), lifecycleStates.put(lifecycleState.getName().toUpperCase(), lifecycleState);
s.getProceedingStates(), s.getPermission(), s.isAppUpdatable(), s.isAppInstallable(),
s.isInitialState(), s.isEndState()));
try { try {
PermissionUtils.putPermission(s.getPermission()); PermissionUtils.putPermission(lifecycleState.getPermission());
} catch (PermissionManagementException e) { } catch (PermissionManagementException e) {
String msg = "Error when adding permission " + s.getPermission() + " related to the state: " String msg =
+ s.getName(); "Error when adding permission " + lifecycleState.getPermission() + " related to the state: "
+ lifecycleState.getName();
log.error(msg, e); log.error(msg, e);
throw new LifecycleManagementException(msg, e); throw new LifecycleManagementException(msg, e);
} }
} }
} }
public Map<String, State> getLifecycleConfig() throws LifecycleManagementException { public Map<String, LifecycleState> getLifecycleConfig() throws LifecycleManagementException {
if (lifecycleStates == null){ if (lifecycleStates == null) {
String msg = "Lifecycle configuration in not initialized."; String msg = "Lifecycle configuration in not initialized.";
log.error(msg); log.error(msg);
throw new LifecycleManagementException(msg); throw new LifecycleManagementException(msg);
@ -72,29 +69,27 @@ public class LifecycleStateManager {
return lifecycleStates; return lifecycleStates;
} }
public List<String> getNextLifecycleStates(String currentLifecycleState) {
public Set<String> getNextLifecycleStates(String currentLifecycleState) {
return lifecycleStates.get(currentLifecycleState.toUpperCase()).getProceedingStates(); return lifecycleStates.get(currentLifecycleState.toUpperCase()).getProceedingStates();
} }
public boolean isValidStateChange(String currentState, String nextState, String username, int tenantId) throws public boolean isValidStateChange(String currentState, String nextState, String username, int tenantId)
LifecycleManagementException { throws LifecycleManagementException {
UserRealm userRealm; UserRealm userRealm;
String permission = getPermissionForStateChange(nextState); String permission = getPermissionForStateChange(nextState);
if (permission != null) { if (permission != null) {
try { try {
userRealm = DataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); userRealm = DataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
if (userRealm != null && userRealm.getAuthorizationManager() != null && if (userRealm != null && userRealm.getAuthorizationManager() != null && userRealm
userRealm.getAuthorizationManager().isUserAuthorized(username, .getAuthorizationManager()
PermissionUtils.getAbsolutePermissionPath(permission), .isUserAuthorized(username, PermissionUtils.getAbsolutePermissionPath(permission),
Constants.UI_EXECUTE)) { Constants.UI_EXECUTE)) {
if (currentState.equalsIgnoreCase(nextState)) { if (currentState.equalsIgnoreCase(nextState)) {
return true; return true;
} }
State state = getMatchingState(currentState); LifecycleState matchingState = getMatchingState(currentState);
if (state != null) { if (matchingState != null) {
return getMatchingNextState(state.getProceedingStates(), nextState); return getMatchingNextState(matchingState.getProceedingStates(), nextState);
} }
return false; return false;
} }
@ -105,24 +100,22 @@ public class LifecycleStateManager {
+ nextState + " with username : " + username + " and tenant Id : " + tenantId, e); + nextState + " with username : " + username + " and tenant Id : " + tenantId, e);
} }
} else { } else {
throw new LifecycleManagementException( throw new LifecycleManagementException("Required permissions cannot be found for the state : " + nextState);
"Required permissions cannot be found for the state : " + nextState);
} }
} }
private State getMatchingState(String currentState) { private LifecycleState getMatchingState(String currentState) {
for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) { for (Map.Entry<String, LifecycleState> lifecycyleState : lifecycleStates.entrySet()) {
if (stringStateEntry.getKey().equalsIgnoreCase(currentState)) { if (lifecycyleState.getKey().equalsIgnoreCase(currentState)) {
return lifecycleStates.get(stringStateEntry.getKey()); return lifecycyleState.getValue();
} }
} }
return null; return null;
} }
private boolean getMatchingNextState(List<String> proceedingStates, String nextState) {
private boolean getMatchingNextState(Set<String> proceedingStates, String nextState) { for (String stateName : proceedingStates) {
for (String state : proceedingStates) { if (stateName.equalsIgnoreCase(nextState)) {
if (state.equalsIgnoreCase(nextState)) {
return true; return true;
} }
} }
@ -130,21 +123,27 @@ public class LifecycleStateManager {
} }
private String getPermissionForStateChange(String nextState) { private String getPermissionForStateChange(String nextState) {
Iterator it = lifecycleStates.entrySet().iterator(); for (Map.Entry<String, LifecycleState> lifecycyleState : lifecycleStates.entrySet()) {
State nextLifecycleState; if (lifecycyleState.getKey().equalsIgnoreCase(nextState)) {
while (it.hasNext()) { return lifecycyleState.getValue().getPermission();
Map.Entry pair = (Map.Entry) it.next();
if (pair.getKey().toString().equalsIgnoreCase(nextState)) {
nextLifecycleState = lifecycleStates.get(nextState);
return nextLifecycleState.getPermission();
} }
it.remove();
} }
return null; return null;
} }
public boolean isDeletableState(String state) throws LifecycleManagementException {
LifecycleState currentState = getMatchingState(state);
if (currentState != null) {
return currentState.isDeletableState();
} else {
String msg = "Couldn't find a lifecycle state that matches with " + state + " state.";
log.error(msg);
throw new LifecycleManagementException(msg);
}
}
public boolean isUpdatableState(String state) throws LifecycleManagementException { public boolean isUpdatableState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state); LifecycleState currentState = getMatchingState(state);
if (currentState != null) { if (currentState != null) {
return currentState.isAppUpdatable(); return currentState.isAppUpdatable();
} else { } else {
@ -155,7 +154,7 @@ public class LifecycleStateManager {
} }
public boolean isInstallableState(String state) throws LifecycleManagementException { public boolean isInstallableState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state); LifecycleState currentState = getMatchingState(state);
if (currentState != null) { if (currentState != null) {
return currentState.isAppInstallable(); return currentState.isAppInstallable();
} else { } else {
@ -166,7 +165,7 @@ public class LifecycleStateManager {
} }
public boolean isInitialState(String state) throws LifecycleManagementException { public boolean isInitialState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state); LifecycleState currentState = getMatchingState(state);
if (currentState != null) { if (currentState != null) {
return currentState.isInitialState(); return currentState.isInitialState();
} else { } else {
@ -177,7 +176,7 @@ public class LifecycleStateManager {
} }
public boolean isEndState(String state) throws LifecycleManagementException { public boolean isEndState(String state) throws LifecycleManagementException {
State currentState = getMatchingState(state); LifecycleState currentState = getMatchingState(state);
if (currentState != null) { if (currentState != null) {
return currentState.isEndState(); return currentState.isEndState();
} else { } else {
@ -188,58 +187,55 @@ public class LifecycleStateManager {
} }
public String getInitialState() throws LifecycleManagementException { public String getInitialState() throws LifecycleManagementException {
String initialState = null; String initialState;
for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) { for (Map.Entry<String, LifecycleState> lifecycleState : lifecycleStates.entrySet()) {
if (stringStateEntry.getValue().isInitialState()) { if (lifecycleState.getValue().isInitialState()) {
initialState = stringStateEntry.getKey(); initialState = lifecycleState.getKey();
break; return initialState;
} }
} }
if (initialState == null){ String msg = "Haven't defined the initial state in the application-manager.xml. Please add initial state "
String msg = "Haven't defined the initial state in the application-manager.xml. Please add initial state " + "to the <LifecycleStates> section in the app-manager.xml";
+ "to the <LifecycleStates> section in the app-manager.xml"; log.error(msg);
log.error(msg); throw new LifecycleManagementException(msg);
throw new LifecycleManagementException(msg);
}
return initialState;
} }
public String getEndState() throws LifecycleManagementException { public String getEndState() throws LifecycleManagementException {
String endState = null; String endState = null;
for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) { for (Map.Entry<String, LifecycleState> stringStateEntry : lifecycleStates.entrySet()) {
if (stringStateEntry.getValue().isEndState()) { if (stringStateEntry.getValue().isEndState()) {
endState = stringStateEntry.getKey(); endState = stringStateEntry.getKey();
break; break;
} }
} }
if (endState == null){ if (endState == null) {
String msg = "Haven't defined the end state in the application-manager.xml. Please add end state " String msg = "Haven't defined the end state in the application-manager.xml. Please add end state "
+ "to the <LifecycleStates> section in the app-manager.xml"; + "to the <LifecycleStates> section in the app-manager.xml";
log.error(msg); log.error(msg);
throw new LifecycleManagementException(msg); throw new LifecycleManagementException(msg);
} }
return endState; return endState;
} }
public String getInstallableState() throws LifecycleManagementException { public String getInstallableState() throws LifecycleManagementException {
String installableState = null; String installableState = null;
for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) { for (Map.Entry<String, LifecycleState> stringStateEntry : lifecycleStates.entrySet()) {
if (stringStateEntry.getValue().isAppInstallable()) { if (stringStateEntry.getValue().isAppInstallable()) {
installableState = stringStateEntry.getKey(); installableState = stringStateEntry.getKey();
break; break;
} }
} }
if (installableState == null){ if (installableState == null) {
String msg = "Haven't defined the installable state in the application-manager.xml. Please add installable " String msg = "Haven't defined the installable state in the application-manager.xml. Please add installable "
+ "state to the <LifecycleStates> section in the app-manager.xml"; + "state to the <LifecycleStates> section in the app-manager.xml";
log.error(msg); log.error(msg);
throw new LifecycleManagementException(msg); throw new LifecycleManagementException(msg);
} }
return installableState; return installableState;
} }
public boolean isStateExist(String currentState) { public boolean isStateExist(String currentState) {
for (Map.Entry<String, State> stringStateEntry : lifecycleStates.entrySet()) { for (Map.Entry<String, LifecycleState> stringStateEntry : lifecycleStates.entrySet()) {
if (stringStateEntry.getKey().equalsIgnoreCase(currentState)) { if (stringStateEntry.getKey().equalsIgnoreCase(currentState)) {
return true; return true;
} }
@ -247,8 +243,7 @@ public class LifecycleStateManager {
return false; return false;
} }
public void setLifecycleStates(Map<String, LifecycleState> lifecycleStates) {
public void setLifecycleStates(Map<String, State> lifecycleStates) {
this.lifecycleStates = lifecycleStates; this.lifecycleStates = lifecycleStates;
} }
} }

@ -1,25 +1,22 @@
package org.wso2.carbon.device.application.mgt.core; package org.wso2.carbon.device.application.mgt.core;
import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManager; import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManager;
import org.wso2.carbon.device.application.mgt.common.State;
import org.wso2.carbon.device.application.mgt.common.config.LifecycleState; import org.wso2.carbon.device.application.mgt.common.config.LifecycleState;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
public class LifeCycleStateManagerTest extends LifecycleStateManager { class LifeCycleStateManagerTest extends LifecycleStateManager {
public void initializeLifeCycleDetails(List<LifecycleState> states) { void initializeLifeCycleDetails(List<LifecycleState> lifecycleStates) {
HashMap<String, State> lifecycleStates = new HashMap<>(); HashMap<String, LifecycleState> lifecycleStatesMap = new HashMap<>();
for (LifecycleState s : states) { for (LifecycleState lifecycleState : lifecycleStates) {
if (s.getProceedingStates() != null) { if (lifecycleState.getProceedingStates() != null) {
s.getProceedingStates().replaceAll(String::toUpperCase); lifecycleState.getProceedingStates().replaceAll(String::toUpperCase);
} }
lifecycleStates.put(s.getName().toUpperCase(), new State(s.getName().toUpperCase(), lifecycleStatesMap.put(lifecycleState.getName().toUpperCase(), lifecycleState);
s.getProceedingStates(), s.getPermission(), s.isAppUpdatable(), s.isAppInstallable(),
s.isInitialState(), s.isEndState()));
} }
setLifecycleStates(lifecycleStates); setLifecycleStates(lifecycleStatesMap);
} }
} }

@ -10,7 +10,6 @@ import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManag
import org.wso2.carbon.device.application.mgt.common.config.LifecycleState; import org.wso2.carbon.device.application.mgt.common.config.LifecycleState;
import java.util.List; import java.util.List;
import java.util.Set;
public class LifecycleManagementTest { public class LifecycleManagementTest {
@ -19,17 +18,16 @@ public class LifecycleManagementTest {
private final String CURRENT_STATE = "Approved"; private final String CURRENT_STATE = "Approved";
private final String NEXT_STATE = "Published"; private final String NEXT_STATE = "Published";
private final String BOGUS_STATE = "Removed"; private final String BOGUS_STATE = "Retired";
private final String UPDATABLE_STATE = "Created"; private final String UPDATABLE_STATE = "Created";
private final String NON_UPDATABLE_STATE = "Removed"; private final String NON_UPDATABLE_STATE = "Retired";
private final String INSTALLABLE_STATE = "Published"; private final String INSTALLABLE_STATE = "Published";
private final String UNINSTALlABLE_STATE = "Removed";
private final String INITIAL_STATE = "Created"; private final String INITIAL_STATE = "Created";
private final String END_STATE = "Removed"; private final String END_STATE = "Retired";
@BeforeClass @BeforeClass
public void init() throws LifecycleManagementException { public void init() {
ConfigurationManager configurationManager = ConfigurationManager.getInstance(); ConfigurationManager configurationManager = ConfigurationManager.getInstance();
Configuration configuration = configurationManager.getConfiguration(); Configuration configuration = configurationManager.getConfiguration();
lifecycleStates = configuration.getLifecycleStates(); lifecycleStates = configuration.getLifecycleStates();
@ -39,14 +37,14 @@ public class LifecycleManagementTest {
@Test @Test
public void checkValidNextLifecycleState() { public void checkValidNextLifecycleState() {
Set<String> proceedingStates = lifecycleStateManager.getNextLifecycleStates(CURRENT_STATE); List<String> proceedingStates = lifecycleStateManager.getNextLifecycleStates(CURRENT_STATE);
Assert.assertTrue("Invalid proceeding state of: " + CURRENT_STATE, Assert.assertTrue("Invalid proceeding state of: " + CURRENT_STATE,
proceedingStates.contains(NEXT_STATE.toUpperCase())); proceedingStates.contains(NEXT_STATE.toUpperCase()));
} }
@Test @Test
public void checkInvalidNextLifecycleState() { public void checkInvalidNextLifecycleState() {
Set<String> proceedingStates = lifecycleStateManager.getNextLifecycleStates(CURRENT_STATE); List<String> proceedingStates = lifecycleStateManager.getNextLifecycleStates(CURRENT_STATE);
Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE, Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE,
proceedingStates.contains(BOGUS_STATE.toUpperCase())); proceedingStates.contains(BOGUS_STATE.toUpperCase()));
} }
@ -70,12 +68,6 @@ public class LifecycleManagementTest {
Assert.assertTrue("Installable state: " + INSTALLABLE_STATE, isInstallable); Assert.assertTrue("Installable state: " + INSTALLABLE_STATE, isInstallable);
} }
@Test
public void CheckUnInstallableState() throws LifecycleManagementException {
boolean isInstallable = lifecycleStateManager.isInstallableState(UNINSTALlABLE_STATE);
Assert.assertFalse("UnInstallable state: " + UNINSTALlABLE_STATE, isInstallable);
}
@Test @Test
public void CheckGetInitialState() throws LifecycleManagementException { public void CheckGetInitialState() throws LifecycleManagementException {
boolean isInitialState = lifecycleStateManager.getInitialState().equalsIgnoreCase(INITIAL_STATE); boolean isInitialState = lifecycleStateManager.getInitialState().equalsIgnoreCase(INITIAL_STATE);
@ -126,7 +118,7 @@ public class LifecycleManagementTest {
@Test @Test
public void check() { public void check() {
Set<String> proceedingStates = lifecycleStateManager.getNextLifecycleStates(CURRENT_STATE); List<String> proceedingStates = lifecycleStateManager.getNextLifecycleStates(CURRENT_STATE);
Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE, Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE,
proceedingStates.contains(BOGUS_STATE.toUpperCase())); proceedingStates.contains(BOGUS_STATE.toUpperCase()));
} }

@ -76,58 +76,59 @@
<LifecycleState name="Created"> <LifecycleState name="Created">
<IsAppUpdatable>true</IsAppUpdatable> <IsAppUpdatable>true</IsAppUpdatable>
<IsInitialState>true</IsInitialState> <IsInitialState>true</IsInitialState>
<Permission>/device-mgt/applications/life-cycle/create</Permission> <IsDeletableState>true</IsDeletableState>
<Permission>/app-mgt/life-cycle/application/create</Permission>
<ProceedingStates> <ProceedingStates>
<State>In-Review</State> <State>In-Review</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="In-Review"> <LifecycleState name="In-Review">
<Permission>/device-mgt/applications/life-cycle/in-review</Permission> <Permission>/app-mgt/life-cycle/application/review</Permission>
<ProceedingStates> <ProceedingStates>
<State>Rejected</State> <State>Rejected</State>
<State>Approved</State> <State>Approved</State>
<State>Created</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Approved"> <LifecycleState name="Approved">
<Permission>/device-mgt/applications/life-cycle/approve</Permission> <Permission>/app-mgt/life-cycle/application/approve</Permission>
<ProceedingStates> <ProceedingStates>
<State>In-Review</State>
<State>Published</State> <State>Published</State>
<State>Created</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Rejected"> <LifecycleState name="Rejected">
<Permission>/device-mgt/applications/life-cycle/reject</Permission> <IsDeletableState>true</IsDeletableState>
<Permission>/app-mgt/life-cycle/application/reject</Permission>
<ProceedingStates> <ProceedingStates>
<State>Created</State> <State>In-Review</State>
<State>Removed</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Published"> <LifecycleState name="Published">
<IsAppInstallable>true</IsAppInstallable> <IsAppInstallable>true</IsAppInstallable>
<Permission>/device-mgt/applications/life-cycle/publish</Permission> <Permission>/app-mgt/life-cycle/application/publish</Permission>
<ProceedingStates> <ProceedingStates>
<State>Unpublished</State> <State>Blocked</State>
<State>Deprecated</State> <State>Deprecated</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Unpublished"> <LifecycleState name="Blocked">
<Permission>/device-mgt/applications/life-cycle/unpublish</Permission> <Permission>/app-mgt/life-cycle/application/block</Permission>
<ProceedingStates> <ProceedingStates>
<State>Published</State> <State>Published</State>
<State>In-Review</State> <State>Deprecated</State>
<State>Removed</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Deprecated"> <LifecycleState name="Deprecated">
<Permission>/device-mgt/applications/life-cycle/deprecate</Permission> <Permission>/app-mgt/life-cycle/application/deprecate</Permission>
<ProceedingStates> <ProceedingStates>
<State>Removed</State> <State>Published</State>
<State>In-Review</State> <State>Retired</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Removed"> <LifecycleState name="Retired">
<IsEndState>true</IsEndState> <IsEndState>true</IsEndState>
<Permission>/device-mgt/applications/life-cycle/remove</Permission> <Permission>/app-mgt/life-cycle/application/retire</Permission>
</LifecycleState> </LifecycleState>
</LifecycleStates> </LifecycleStates>

@ -45,7 +45,6 @@ import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper;
import java.util.List; import java.util.List;
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.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
@ -416,15 +415,15 @@ public interface ApplicationManagementPublisherAPI {
@Multipart(value = "screenshot3") Attachment screenshot3 @Multipart(value = "screenshot3") Attachment screenshot3
); );
@DELETE @PUT
@Consumes("application/json") @Consumes("application/json")
@Path("/{appId}") @Path("/retire/{appId}")
@ApiOperation( @ApiOperation(
consumes = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE", httpMethod = "PUT",
value = "Delete the application with the given UUID", value = "Retire the application with the given UUID",
notes = "This will delete the application with the given UUID", notes = "This will retire the application with the given UUID",
tags = "ApplicationDTO Management", tags = "ApplicationDTO Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ -449,8 +448,7 @@ public interface ApplicationManagementPublisherAPI {
code = 404, code = 404,
message = "Application not found"), message = "Application not found"),
}) })
//todo add new scope and permission Response retireApplication(
Response deleteApplication(
@ApiParam( @ApiParam(
name = "UUID", name = "UUID",
value = "Unique identifier of the ApplicationDTO", value = "Unique identifier of the ApplicationDTO",
@ -592,7 +590,7 @@ public interface ApplicationManagementPublisherAPI {
httpMethod = "PUT", httpMethod = "PUT",
value = "Update an application release", value = "Update an application release",
notes = "This will update a new application release", notes = "This will update a new application release",
tags = "ApplicationDTO Management", tags = "Application Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update") @ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
@ -668,7 +666,7 @@ public interface ApplicationManagementPublisherAPI {
@Multipart(value = "screenshot3") Attachment screenshot3); @Multipart(value = "screenshot3") Attachment screenshot3);
@GET @GET
@Path("/lifecycle/{appId}/{uuid}") @Path("/life-cycle/state-changes/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
@ -689,16 +687,22 @@ public interface ApplicationManagementPublisherAPI {
message = "OK. \n Successfully retrieved lifecycle states.", message = "OK. \n Successfully retrieved lifecycle states.",
response = List.class, response = List.class,
responseContainer = "List"), responseContainer = "List"),
@ApiResponse(
code = 404,
message = "NOT FOUND. \n Couldn't found an application release for application release UUID."),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while getting the lifecycle list.", message = "Internal Server Error. \n Error occurred while getting the lifecycle list.",
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response getLifecycleState(@PathParam("appId") int applicationId, Response getLifecycleStates(
@PathParam("uuid") String applicationUuid); @ApiParam(
name = "uuid",
value = "UUID of the application release.")
@PathParam("uuid") String applicationUuid);
@POST @POST
@Path("/lifecycle/{appId}/{uuid}") @Path("/life-cycle/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
@ -734,11 +738,6 @@ public interface ApplicationManagementPublisherAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response addLifecycleState( Response addLifecycleState(
@ApiParam(
name = "appId",
value = "Identifier of the ApplicationDTO",
required = true)
@PathParam("appId") int applicationId,
@ApiParam( @ApiParam(
name = "uuid", name = "uuid",
value = "UUID of the ApplicationDTO Release", value = "UUID of the ApplicationDTO Release",
@ -750,4 +749,39 @@ public interface ApplicationManagementPublisherAPI {
required = true) required = true)
@QueryParam("action") String action @QueryParam("action") String action
); );
@GET
@Path("/lifecycle-config")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "get application management UI configuration",
notes = "This will get all UI configuration of application management",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:app:publisher:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully got Lifecycle Config.",
response = ApplicationList.class),
@ApiResponse(
code = 404,
message = "Not Found. There doesn't have an defined <LifecycleStates> in app management "
+ "configuration file." +
"query."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the lifecycle config.",
response = ErrorResponse.class)
})
Response getLifecycleConfig();
} }

@ -77,7 +77,7 @@ public interface ApplicationManagementPublisherAdminAPI {
String SCOPE = "scope"; String SCOPE = "scope";
@DELETE @DELETE
@Path("/release/{appId}/{uuid}") @Path("/release/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
@ -108,14 +108,47 @@ public interface ApplicationManagementPublisherAdminAPI {
message = "Internal Server Error. \n Error occurred while deleting application release.", message = "Internal Server Error. \n Error occurred while deleting application release.",
response = ErrorResponse.class) response = ErrorResponse.class)
}) Response deleteApplicationRelease( }) Response deleteApplicationRelease(
@ApiParam(
name = "appId",
value = "application Id",
required = true)
@PathParam("appId") int applicationId,
@ApiParam( @ApiParam(
name = "uuid", name = "uuid",
value = "application release UUID", value = "application release UUID",
required = true) required = true)
@PathParam("uuid") String releaseUuid); @PathParam("uuid") String releaseUuid);
@DELETE
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Delete application release.",
notes = "This will delete application release for given UUID",
tags = "Application Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:admin:app:publisher:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully delete application release.",
response = ApplicationList.class),
@ApiResponse(
code = 404,
message = "Not Found. There doesn't have an application release for UUID" +
"query."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while deleting application release.",
response = ErrorResponse.class)
}) Response deleteApplication(
@ApiParam(
name = "appId",
value = "application ID",
required = true)
@PathParam("appId") int applicatioId);
} }

@ -1,33 +1,33 @@
/* /* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package org.wso2.carbon.device.application.mgt.publisher.api.services.impl; package org.wso2.carbon.device.application.mgt.publisher.api.services.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.wso2.carbon.device.application.mgt.common.*; import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO; import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException; import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.response.Application; import org.wso2.carbon.device.application.mgt.common.response.Application;
import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.services.AppmDataHandler;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationUpdateWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationUpdateWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper;
@ -37,7 +37,6 @@ import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import org.wso2.carbon.device.application.mgt.publisher.api.services.ApplicationManagementPublisherAPI; import org.wso2.carbon.device.application.mgt.publisher.api.services.ApplicationManagementPublisherAPI;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import java.io.IOException; import java.io.IOException;
@ -49,7 +48,6 @@ import java.util.Map;
import javax.activation.DataHandler; import javax.activation.DataHandler;
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.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
@ -167,18 +165,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
@Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) { @Multipart("screenshot3") Attachment screenshot3) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
List<Attachment> attachmentList = new ArrayList<>(); List<Attachment> attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3);
if (screenshot1 != null) {
attachmentList.add(screenshot1);
}
if (screenshot2 != null) {
attachmentList.add(screenshot2);
}
if (screenshot3 != null) {
attachmentList.add(screenshot3);
}
try { try {
applicationManager.validateAppCreatingRequest(applicationWrapper); applicationManager.validateAppCreatingRequest(applicationWrapper);
applicationManager.validateReleaseCreatingRequest(applicationWrapper.getApplicationReleaseWrappers().get(0), applicationManager.validateReleaseCreatingRequest(applicationWrapper.getApplicationReleaseWrappers().get(0),
@ -221,18 +208,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
@Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) { @Multipart("screenshot3") Attachment screenshot3) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
List<Attachment> attachmentList = new ArrayList<>(); List<Attachment> attachmentList = constructAttachmentList(screenshot1, screenshot2, screenshot3);
if (screenshot1 != null) {
attachmentList.add(screenshot1);
}
if (screenshot2 != null) {
attachmentList.add(screenshot2);
}
if (screenshot3 != null) {
attachmentList.add(screenshot3);
}
try { try {
applicationManager.validateReleaseCreatingRequest(applicationReleaseWrapper, appType); applicationManager.validateReleaseCreatingRequest(applicationReleaseWrapper, appType);
applicationManager.validateBinaryArtifact(binaryFile, appType); applicationManager.validateBinaryArtifact(binaryFile, appType);
@ -271,17 +247,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
@Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) { @Multipart("screenshot3") Attachment screenshot3) {
try { try {
List<Attachment> attachments = new ArrayList<>(); List<Attachment> attachments = constructAttachmentList(screenshot1, screenshot2, screenshot3);
if (screenshot1 != null) {
attachments.add(screenshot1);
}
if (screenshot2 != null) {
attachments.add(screenshot2);
}
if (screenshot3 != null) {
attachments.add(screenshot3);
}
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
applicationManager.validateImageArtifacts(iconFile, bannerFile, attachments); applicationManager.validateImageArtifacts(iconFile, bannerFile, attachments);
applicationManager.updateApplicationImageArtifact(applicationReleaseUuid, applicationManager.updateApplicationImageArtifact(applicationReleaseUuid,
@ -385,16 +351,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
@Multipart("screenshot2") Attachment screenshot2, @Multipart("screenshot2") Attachment screenshot2,
@Multipart("screenshot3") Attachment screenshot3) { @Multipart("screenshot3") Attachment screenshot3) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
List<Attachment> screenshots = new ArrayList<>(); List<Attachment> screenshots = constructAttachmentList(screenshot1, screenshot2, screenshot3);
if (screenshot1 != null){
screenshots.add(screenshot1);
}
if (screenshot2 != null) {
screenshots.add(screenshot2);
}
if (screenshot3 != null) {
screenshots.add(screenshot3);
}
try { try {
applicationManager.validateBinaryArtifact(binaryFile, appType); applicationManager.validateBinaryArtifact(binaryFile, appType);
applicationManager.validateImageArtifacts(iconFile, bannerFile, screenshots); applicationManager.validateImageArtifacts(iconFile, bannerFile, screenshots);
@ -433,12 +390,13 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
} }
@DELETE @PUT
@Path("/{appId}") @Path("/retire/{appId}")
public Response deleteApplication(@PathParam("appId") int applicationId) { public Response retireApplication(
@PathParam("appId") int applicationId) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
applicationManager.deleteApplication(applicationId); applicationManager.retireApplication(applicationId);
return Response.status(Response.Status.OK) return Response.status(Response.Status.OK)
.entity("Successfully deleted the application for application ID: " + applicationId).build(); .entity("Successfully deleted the application for application ID: " + applicationId).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
@ -457,52 +415,42 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
} }
} }
/*
//todo ----------------------
*/
@GET @GET
@Path("/lifecycle/{appId}/{uuid}") @Path("/life-cycle/state-changes/{uuid}")
public Response getLifecycleState( public Response getLifecycleStates(
@PathParam("appId") int applicationId, @PathParam("uuid") String releaseUuid) {
@PathParam("uuid") String applicationUuid) {
LifecycleStateDTO lifecycleState;
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
lifecycleState = applicationManager.getLifecycleState(applicationId, applicationUuid); List<LifecycleState> lifecycleStates = applicationManager.getLifecycleStateChangeFlow(releaseUuid);
if (lifecycleState == null) { return Response.status(Response.Status.OK).entity(lifecycleStates).build();
String msg = "Couldn't found application lifecycle details for appid: " + applicationId } catch (NotFoundException e) {
+ " and app release UUID: " + applicationUuid; String msg = "Couldn't found an application release for UUID: " + releaseUuid;
log.error(msg); log.error(msg);
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while getting lifecycle state."; String msg =
"Error occurred while getting lifecycle states for application release UUID: " + releaseUuid;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} }
return Response.status(Response.Status.OK).entity(lifecycleState).build();
} }
@POST @POST
@Path("/lifecycle/{appId}/{uuid}") @Path("/life-cycle/{uuid}")
public Response addLifecycleState( public Response addLifecycleState(
@PathParam("appId") int applicationId,
@PathParam("uuid") String applicationUuid, @PathParam("uuid") String applicationUuid,
@QueryParam("action") String action) { @QueryParam("action") String action) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
if (action == null || action.isEmpty()) { if (StringUtils.isEmpty(action)) {
String msg = "The Action is null or empty. Please check the request"; String msg = "The Action is null or empty. Please verify the request.";
log.error(msg); log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.BAD_REQUEST).build();
} }
LifecycleStateDTO state = new LifecycleStateDTO();
state.setCurrentState(action); applicationManager.changeLifecycleState( applicationUuid, action);
applicationManager.changeLifecycleState(applicationId, applicationUuid, state);
} catch (NotFoundException e) { } catch (NotFoundException e) {
String msg = "Could,t find application release for application id: " + applicationId String msg = "Could,t find application release for application release uuid: " + applicationUuid;
+ " and application release uuid: " + applicationUuid;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
@ -513,6 +461,44 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
return Response.status(Response.Status.CREATED).entity("Lifecycle state added successfully.").build(); return Response.status(Response.Status.CREATED).entity("Lifecycle state added successfully.").build();
} }
@GET
@Override
@Consumes("application/json")
@Path("/lifecycle-config")
public Response getLifecycleConfig() {
AppmDataHandler dataHandler = APIUtil.getDataHandler();
try {
return Response.status(Response.Status.OK).entity(dataHandler.getLifecycleConfiguration()).build();
} catch (LifecycleManagementException e) {
String msg = "Error Occurred while accessing lifecycle manager.";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/***
* Construct the screenshot list by evaluating the availability of each screenshot.
*
* @param screenshot1 First Screenshot
* @param screenshot2 Second Screenshot
* @param screenshot3 Third Screenshot
* @return List of {@link Attachment}
*/
private List<Attachment> constructAttachmentList(Attachment screenshot1, Attachment screenshot2,
Attachment screenshot3) {
List<Attachment> attachments = new ArrayList<>();
if (screenshot1 != null) {
attachments.add(screenshot1);
}
if (screenshot2 != null) {
attachments.add(screenshot2);
}
if (screenshot3 != null) {
attachments.add(screenshot3);
}
return attachments;
}
/*** /***
* *
* @param binaryFile binary file of the application release * @param binaryFile binary file of the application release
@ -618,7 +604,5 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
log.error(msg, e); log.error(msg, e);
throw new ApplicationManagementException(msg); throw new ApplicationManagementException(msg);
} }
} }
} }

@ -20,49 +20,18 @@ package org.wso2.carbon.device.application.mgt.publisher.api.services.impl.admin
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.wso2.carbon.device.application.mgt.common.ApplicationArtifact;
import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.ApplicationType;
import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.dto.LifecycleStateDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.response.Application;
import org.wso2.carbon.device.application.mgt.common.response.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationReleaseWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationUpdateWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationWrapper;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException; import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil; import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import org.wso2.carbon.device.application.mgt.publisher.api.services.ApplicationManagementPublisherAPI;
import org.wso2.carbon.device.application.mgt.publisher.api.services.admin.ApplicationManagementPublisherAdminAPI; import org.wso2.carbon.device.application.mgt.publisher.api.services.admin.ApplicationManagementPublisherAdminAPI;
import javax.activation.DataHandler;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* Implementation of Application Management related APIs. * Implementation of Application Management related APIs.
@ -74,31 +43,55 @@ public class ApplicationManagementPublisherAdminAPIImpl implements ApplicationMa
private static Log log = LogFactory.getLog(ApplicationManagementPublisherAdminAPIImpl.class); private static Log log = LogFactory.getLog(ApplicationManagementPublisherAdminAPIImpl.class);
@DELETE @DELETE
@Path("/release/{appId}/{uuid}") @Path("/release/{uuid}")
public Response deleteApplicationRelease( public Response deleteApplicationRelease(
@PathParam("appId") int applicationId,
@PathParam("uuid") String releaseUuid) { @PathParam("uuid") String releaseUuid) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
applicationManager.deleteApplicationRelease(applicationId, releaseUuid); applicationManager.deleteApplicationRelease(releaseUuid);
String responseMsg = "Successfully deleted the application release for uuid: " + releaseUuid + ""; String responseMsg = "Successfully deleted the application release for uuid: " + releaseUuid + "";
return Response.status(Response.Status.OK).entity(responseMsg).build(); return Response.status(Response.Status.OK).entity(responseMsg).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
String msg = "Couldn't found application release which is having application id: " + applicationId String msg =
+ " and application release UUID:" + releaseUuid; "Couldn't found application release which is having application release UUID:" + releaseUuid;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ForbiddenException e) { } catch (ForbiddenException e) {
String msg = String msg = "You don't have require permission to delete the application release which has UUID "
"You don't have require permission to delete the application release which has UUID " + releaseUuid + releaseUuid;
+ " and application ID " + applicationId;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build(); return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
}catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while deleting the application: " + applicationId; String msg = "Error occurred while deleting the application release for application release UUID:: "
+ releaseUuid;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@DELETE
@Path("/{appId}")
public Response deleteApplication(
@PathParam("appId") int applicatioId) {
ApplicationManager applicationManager = APIUtil.getApplicationManager();
try {
applicationManager.deleteApplication(applicatioId);
String responseMsg = "Successfully deleted the application which has ID: " + applicatioId + "";
return Response.status(Response.Status.OK).entity(responseMsg).build();
} catch (NotFoundException e) {
String msg =
"Couldn't found application release which is having the ID:" + applicatioId;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ForbiddenException e) {
String msg = "You don't have require permission to delete the application which has ID: " + applicatioId;
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while deleting the application which has application ID:: " + applicatioId;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
} }

@ -76,58 +76,59 @@
<LifecycleState name="Created"> <LifecycleState name="Created">
<IsAppUpdatable>true</IsAppUpdatable> <IsAppUpdatable>true</IsAppUpdatable>
<IsInitialState>true</IsInitialState> <IsInitialState>true</IsInitialState>
<Permission>/device-mgt/applications/life-cycle/create</Permission> <IsDeletableState>true</IsDeletableState>
<Permission>/app-mgt/life-cycle/application/create</Permission>
<ProceedingStates> <ProceedingStates>
<State>In-Review</State> <State>In-Review</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="In-Review"> <LifecycleState name="In-Review">
<Permission>/device-mgt/applications/life-cycle/in-review</Permission> <Permission>/app-mgt/life-cycle/application/review</Permission>
<ProceedingStates> <ProceedingStates>
<State>Rejected</State> <State>Rejected</State>
<State>Approved</State> <State>Approved</State>
<State>Created</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Approved"> <LifecycleState name="Approved">
<Permission>/device-mgt/applications/life-cycle/approve</Permission> <Permission>/app-mgt/life-cycle/application/approve</Permission>
<ProceedingStates> <ProceedingStates>
<State>In-Review</State>
<State>Published</State> <State>Published</State>
<State>Created</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Rejected"> <LifecycleState name="Rejected">
<Permission>/device-mgt/applications/life-cycle/reject</Permission> <IsDeletableState>true</IsDeletableState>
<Permission>/app-mgt/life-cycle/application/reject</Permission>
<ProceedingStates> <ProceedingStates>
<State>Created</State> <State>In-Review</State>
<State>Removed</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Published"> <LifecycleState name="Published">
<IsAppInstallable>true</IsAppInstallable> <IsAppInstallable>true</IsAppInstallable>
<Permission>/device-mgt/applications/life-cycle/publish</Permission> <Permission>/app-mgt/life-cycle/application/publish</Permission>
<ProceedingStates> <ProceedingStates>
<State>Unpublished</State> <State>Blocked</State>
<State>Deprecated</State> <State>Deprecated</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Unpublished"> <LifecycleState name="Blocked">
<Permission>/device-mgt/applications/life-cycle/unpublish</Permission> <Permission>/app-mgt/life-cycle/application/block</Permission>
<ProceedingStates> <ProceedingStates>
<State>Published</State> <State>Published</State>
<State>In-Review</State> <State>Deprecated</State>
<State>Removed</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Deprecated"> <LifecycleState name="Deprecated">
<Permission>/device-mgt/applications/life-cycle/deprecate</Permission> <Permission>/app-mgt/life-cycle/application/deprecate</Permission>
<ProceedingStates> <ProceedingStates>
<State>Removed</State> <State>Published</State>
<State>In-Review</State> <State>Retired</State>
</ProceedingStates> </ProceedingStates>
</LifecycleState> </LifecycleState>
<LifecycleState name="Removed"> <LifecycleState name="Retired">
<IsEndState>true</IsEndState> <IsEndState>true</IsEndState>
<Permission>/device-mgt/applications/life-cycle/remove</Permission> <Permission>/app-mgt/life-cycle/application/retire</Permission>
</LifecycleState> </LifecycleState>
</LifecycleStates> </LifecycleStates>

@ -157,7 +157,7 @@ VALUES ('PUBLISHED', 'PUBLISHED', 'State in which Application is in published st
/ /
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('UNPUBLISHED', 'UNPUBLISHED', 'State in which Application is in un published state.') VALUES ('BLOCKED', 'BLOCKED', 'State in which Application is in un published state.')
/ /
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)

@ -87,7 +87,7 @@ VALUES ('REJECTED', 'REJECTED', 'State in which Application is rejected after re
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('PUBLISHED', 'PUBLISHED', 'State in which Application is in published state.'); VALUES ('PUBLISHED', 'PUBLISHED', 'State in which Application is in published state.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('UNPUBLISHED', 'UNPUBLISHED', 'State in which Application is in un published state.'); VALUES ('BLOCKED', 'BLOCKED', 'State in which Application is in un published state.');
INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION)
VALUES ('RETIRED', 'RETIRED', 'Retiring an application to indicate end of life state,'); VALUES ('RETIRED', 'RETIRED', 'Retiring an application to indicate end of life state,');

Loading…
Cancel
Save