From 41fa1cb52447ea8861e4f8875e404ef11e4e1791 Mon Sep 17 00:00:00 2001 From: megala21 Date: Mon, 14 Aug 2017 00:06:50 +0530 Subject: [PATCH 1/2] Adding fixed life-cyle related operations for application --- .../services/ApplicationManagementAPI.java | 65 +++++++- .../impl/ApplicationManagementAPIImpl.java | 68 +++++++-- .../common/services/ApplicationManager.java | 20 ++- .../pom.xml | 7 +- .../mgt/core/dao/ApplicationDAO.java | 14 +- .../application/mgt/core/dao/common/Util.java | 2 + .../AbstractApplicationDAOImpl.java | 130 ++++++++++++++++ .../application/H2ApplicationDAOImpl.java | 53 ------- .../application/MySQLApplicationDAOImpl.java | 93 ------------ .../mgt/core/impl/ApplicationManagerImpl.java | 142 ++++++++++++++++-- .../application/mgt/core/util/Constants.java | 11 +- .../dbscripts/cdm/application-mgt/h2.sql | 4 +- 12 files changed, 425 insertions(+), 184 deletions(-) diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/ApplicationManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/ApplicationManagementAPI.java index 4ddbb34f84..9e5927eb1e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/ApplicationManagementAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/ApplicationManagementAPI.java @@ -69,6 +69,13 @@ import java.util.List; key = "perm:application:create", permissions = {"/device-mgt/application/create"} ), + @Scope( + name = "Create an Application", + description = "Create an application", + key = "perm:application-mgt:login", + permissions = {"/device-mgt/application-mgt/login"} + ) + } ) @Path("/applications") @@ -132,6 +139,45 @@ public interface ApplicationManagementAPI { @QueryParam("searchQuery") String searchQuery ); + @GET + @Path("/{uuid}") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "get the application specified by the UUID", + notes = "This will get the application identified by the UUID, if exists", + tags = "Application Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:application:get") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully retrieved relevant application.", + response = Application.class), + @ApiResponse( + code = 404, + message = "Application not found"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while getting relevant application.", + response = ErrorResponse.class) + }) + Response getApplication( + @ApiParam( + name = "uuid", + value = "UUID of the application", + required = true) + @PathParam("uuid") String uuid + ); + @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -157,7 +203,8 @@ public interface ApplicationManagementAPI { @ApiResponse( code = 304, message = "Not Modified. \n " + - "Empty body because the client already has the latest version of the requested resource."), + "Empty body because the client already has the latest version of the requested " + + "resource."), @ApiResponse( code = 500, message = "Internal Server Error. \n Error occurred while getting the application list.", @@ -179,7 +226,12 @@ public interface ApplicationManagementAPI { httpMethod = "PUT", value = "Change the life cycle state of the application", notes = "This will change the life-cycle state of the application", - tags = "Application Management" + tags = "Application Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:application-mgt:login") + }) + } ) @ApiResponses( value = { @@ -213,7 +265,12 @@ public interface ApplicationManagementAPI { value = "Change the life cycle state of the application", notes = "This will retrieve the next life cycle states of the application based on the user and the " + "current state", - tags = "Application Management" + tags = "Application Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:application-mgt:login") + }) + } ) @ApiResponses( value = { @@ -226,7 +283,7 @@ public interface ApplicationManagementAPI { message = "Internal Server Error. \n Error occurred while getting the life-cycle states.", response = ErrorResponse.class) }) - Response getLifeCycleStates( + Response getNextLifeCycleStates( @ApiParam( name = "UUID", value = "Unique identifier of the Application", diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java index 8158956e3c..ef6e4209fc 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java @@ -20,27 +20,36 @@ package org.wso2.carbon.device.application.mgt.api.services.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.application.mgt.api.APIUtil; import org.wso2.carbon.device.application.mgt.api.services.ApplicationManagementAPI; -import org.wso2.carbon.device.application.mgt.common.*; +import org.wso2.carbon.device.application.mgt.common.Application; +import org.wso2.carbon.device.application.mgt.common.ApplicationList; +import org.wso2.carbon.device.application.mgt.common.Filter; +import org.wso2.carbon.device.application.mgt.common.User; 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.api.APIUtil; -import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.util.Constants; +import java.util.Arrays; import javax.validation.Valid; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; -import java.util.Date; + @Produces({"application/json"}) @Consumes({"application/json"}) @Path("/applications") -public class ApplicationManagementAPIImpl implements ApplicationManagementAPI{ - - public static final int DEFAULT_LIMIT = 20; - - public static final String APPLICATION_UPLOAD_EXTENSION = "ApplicationUploadExtension"; +public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { + private static final int DEFAULT_LIMIT = 20; private static Log log = LogFactory.getLog(ApplicationManagementAPIImpl.class); @GET @@ -71,20 +80,39 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI{ @Path("/{uuid}") public Response getApplication(@PathParam("uuid") String uuid) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - return null; + try { + Application application = applicationManager.getApplication(uuid); + if (application == null) { + return Response.status(Response.Status.NOT_FOUND) + .entity("Application with UUID " + uuid + " not found").build(); + } + return Response.status(Response.Status.OK).entity(application).build(); + } catch (ApplicationManagementException e) { + log.error("Error occurred while getting application with the uuid " + uuid, e); + return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); + } } @PUT @Consumes("application/json") @Path("/{uuid}/lifecycle") - public Response changeLifecycleState(@PathParam("uuid") String applicationUUID, @QueryParam("state") String state) { + public Response changeLifecycleState(@PathParam("uuid") String applicationUUID, + @QueryParam("state") String state) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); + + if (!Arrays.asList(Constants.LIFE_CYCLES).contains(state)) { + log.warn("Provided lifecycle state " + state + " is not valid. Please select one from" + + Arrays.toString(Constants.LIFE_CYCLES)); + return Response.status(Response.Status.BAD_REQUEST) + .entity("Provided lifecycle state " + state + " is not valid. Please select one from " + + Arrays.toString(Constants.LIFE_CYCLES)).build(); + } try { applicationManager.changeLifecycle(applicationUUID, state); } catch (ApplicationManagementException e) { String msg = "Error occurred while changing the lifecycle of application: " + applicationUUID; log.error(msg, e); - return Response.status(Response.Status.BAD_REQUEST).build(); + return APIUtil.getResponse(e, Response.Status.BAD_REQUEST); } return Response.status(Response.Status.OK) .entity("Successfully changed the lifecycle state of the application: " + applicationUUID).build(); @@ -93,9 +121,21 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI{ @GET @Path("/{uuid}/lifecycle") @Override - public Response getLifeCycleStates(String applicationUUID) { + public Response getNextLifeCycleStates(@PathParam("uuid") String applicationUUID) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); try { + if (applicationManager.getApplication(applicationUUID) == null) { + if (log.isDebugEnabled()) { + log.debug("Application with the UUID '" + applicationUUID + "' is not found."); + } + return Response.status(Response.Status.NOT_FOUND).entity("Application with the UUID '" + + applicationUUID + "' is not found.").build(); + } + + if (log.isDebugEnabled()) { + log.debug("Application with UUID '" + applicationUUID + "' is found. Request received for getting " + + "next life-cycle states for the particular application."); + } return Response.status(Response.Status.OK).entity(applicationManager.getLifeCycleStates(applicationUUID)) .build(); } catch (ApplicationManagementException e) { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java index b9be209eba..0bbd63c1ca 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java @@ -59,7 +59,15 @@ public interface ApplicationManager { */ public ApplicationList getApplications(Filter filter) throws ApplicationManagementException; - void changeLifecycle(String applicationUUID, String lifecycleIdentifier) throws ApplicationManagementException; + /** + * To change the lifecycle of the Application. + * + * @param applicationUUID UUID of the Application + * @param lifecycleIdentifier New life-cycle that need to be changed. + * @throws ApplicationManagementException Application Management Exception. + */ + public void changeLifecycle(String applicationUUID, String lifecycleIdentifier) throws + ApplicationManagementException; /** * To get the next possible life-cycle states for the application. @@ -70,4 +78,14 @@ public interface ApplicationManager { */ public List getLifeCycleStates(String applicationUUID) throws ApplicationManagementException; + + /** + * To get Application with the given UUID. + * + * @param uuid UUID of the Application + * @return the Application identified by the UUID + * @throws ApplicationManagementException Application Management Exception. + */ + public Application getApplication(String uuid) throws ApplicationManagementException; + } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml index a971d147e6..495bc9c973 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml @@ -74,7 +74,8 @@ org.apache.axis2.*, org.wso2.carbon.user.core.*, org.wso2.carbon.user.api.*, - org.wso2.carbon.ndatasource.core + org.wso2.carbon.ndatasource.core, + org.wso2.carbon !org.wso2.carbon.device.application.mgt.core.internal.*, @@ -158,6 +159,10 @@ org.wso2.carbon org.wso2.carbon.ndatasource.core + + org.wso2.carbon + org.wso2.carbon.core + diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java index f6bdbde5c5..450c90001f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java @@ -18,12 +18,19 @@ */ package org.wso2.carbon.device.application.mgt.core.dao; -import org.wso2.carbon.device.application.mgt.common.*; +import org.wso2.carbon.device.application.mgt.common.Application; +import org.wso2.carbon.device.application.mgt.common.ApplicationList; +import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; +import org.wso2.carbon.device.application.mgt.common.Filter; +import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import java.util.List; import java.util.Map; +/** + * ApplicationDAO is responsible for handling all the Database related operations related with Application Management. + */ public interface ApplicationDAO { Application createApplication(Application application) throws ApplicationManagementDAOException; @@ -48,11 +55,10 @@ public interface ApplicationDAO { void deleteTags(int applicationId) throws ApplicationManagementDAOException; - void changeLifeCycle(LifecycleState lifecycleState) throws ApplicationManagementDAOException; - void addRelease(ApplicationRelease release) throws ApplicationManagementDAOException; - void changeLifecycle(String applicationUUID, String lifecycleIdentifier) throws ApplicationManagementDAOException; + void changeLifecycle(String applicationUUID, String lifecycleIdentifier, String username) throws + ApplicationManagementDAOException; List getNextLifeCycleStates(String applicationUUID, int tenantId) throws ApplicationManagementDAOException; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java index aebcd3e22c..ddc60a1d49 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java @@ -24,6 +24,7 @@ import org.json.JSONException; import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.Category; import org.wso2.carbon.device.application.mgt.common.Platform; +import org.wso2.carbon.device.application.mgt.common.User; import org.wso2.carbon.device.application.mgt.core.util.JSONUtil; import java.sql.PreparedStatement; @@ -54,6 +55,7 @@ public class Util { application.setScreenshots(JSONUtil.jsonArrayStringToList(rs.getString("SCREENSHOTS"))); application.setCreatedAt(rs.getDate("CREATED_AT")); application.setModifiedAt(rs.getDate("MODIFIED_AT")); + application.setUser(new User(rs.getString("CREATED_AT"), rs.getInt("TENANT_ID"))); Platform platform = new Platform(); platform.setName(rs.getString("APL_NAME")); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/AbstractApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/AbstractApplicationDAOImpl.java index 6370a2f7cb..784220f53e 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/AbstractApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/AbstractApplicationDAOImpl.java @@ -20,8 +20,10 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.application; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.json.JSONException; import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.Filter; +import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO; import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; @@ -31,7 +33,9 @@ import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.JSONUtil; import java.sql.*; +import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import java.util.Map; public abstract class AbstractApplicationDAOImpl extends AbstractDAOImpl implements ApplicationDAO { @@ -182,4 +186,130 @@ public abstract class AbstractApplicationDAOImpl extends AbstractDAOImpl impleme } return count; } + + @Override + public Application getApplication(String uuid) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Getting application with the UUID(" + uuid + ") from the database"); + } + Connection conn = null; + PreparedStatement stmt = null; + ResultSet rs = null; + String sql = ""; + Application application = null; + try { + + conn = this.getDBConnection(); + sql += "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, " + + "CAT.ID AS CAT_ID, CAT.NAME AS CAT_NAME FROM APPM_APPLICATION AS APP INNER JOIN APPM_PLATFORM AS " + + "APL ON APP.PLATFORM_ID = APL.ID INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON " + + "APP.APPLICATION_CATEGORY_ID = CAT.ID WHERE UUID = ?"; + + stmt = conn.prepareStatement(sql); + stmt.setString(1, uuid); + rs = stmt.executeQuery(); + + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved basic details of the application with the UUID " + uuid); + } + + if (rs.next()) { + application = new Application(); + //Getting properties + sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, rs.getInt("ID")); + ResultSet rsProperties = stmt.executeQuery(); + + //Getting tags + sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, rs.getInt("ID")); + ResultSet rsTags = stmt.executeQuery(); + + application = Util.loadApplication(rs, rsProperties, rsTags); + Util.cleanupResources(null, rsProperties); + Util.cleanupResources(null, rsTags); + } + } catch (SQLException e) { + throw new ApplicationManagementDAOException("Error occurred while getting application List", e); + } catch (JSONException e) { + throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } finally { + Util.cleanupResources(stmt, rs); + } + return application; + } + + @Override + public void changeLifecycle(String applicationUUID, String lifecycleIdentifier, String userName) throws + ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Change Life cycle status change " + lifecycleIdentifier + "request received to the DAO " + + "level for the application with " + "the UUID '" + applicationUUID + "' from the user " + + userName); + } + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getDBConnection(); + String sql = "UPDATE APPM_APPLICATION SET " + + "LIFECYCLE_STATE_ID = (SELECT ID FROM APPM_LIFECYCLE_STATE WHERE IDENTIFIER = ?), " + + "LIFECYCLE_STATE_MODIFIED_BY = ?, LIFECYCLE_STATE_MODIFIED_AT = ? WHERE UUID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, lifecycleIdentifier); + stmt.setString(2, userName); + stmt.setDate(3, new Date(System.currentTimeMillis())); + stmt.setString(4, applicationUUID); + stmt.executeUpdate(); + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "Error occurred while changing lifecycle of application: " + applicationUUID + " to: " + + lifecycleIdentifier + " state.", e); + } finally { + Util.cleanupResources(stmt, null); + } + } + + @Override + public List getNextLifeCycleStates(String applicationUUID, int tenantId) + throws ApplicationManagementDAOException { + Connection connection = null; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + String sql = "SELECT STATE.NAME, TRANSITION.DESCRIPTION, TRANSITION.PERMISSION FROM ( SELECT * FROM " + + "APPM_LIFECYCLE_STATE ) STATE RIGHT JOIN (SELECT * FROM APPM_LIFECYCLE_STATE_TRANSITION WHERE " + + "INITIAL_STATE = (SELECT LIFECYCLE_STATE_ID FROM APPM_APPLICATION WHERE UUID = ?)) " + + "TRANSITION ON TRANSITION.NEXT_STATE = STATE.ID"; + + try { + connection = this.getDBConnection(); + preparedStatement = connection.prepareStatement(sql); + preparedStatement.setString(1, applicationUUID); + resultSet = preparedStatement.executeQuery(); + + List lifecycleStateTransitions = new ArrayList<>(); + + while(resultSet.next()) { + LifecycleStateTransition lifecycleStateTransition = new LifecycleStateTransition(); + lifecycleStateTransition.setDescription(resultSet.getString(2)); + lifecycleStateTransition.setNextState(resultSet.getString(1)); + lifecycleStateTransition.setPermission(resultSet.getString(3)); + lifecycleStateTransitions.add(lifecycleStateTransition); + } + return lifecycleStateTransitions; + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error while getting the DBConnection for getting the life " + + "cycle states for the application with the UUID : " + applicationUUID, e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException("SQL exception while executing the query '" + sql + "'.", e); + } finally { + Util.cleanupResources(preparedStatement, resultSet); + } + } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/H2ApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/H2ApplicationDAOImpl.java index 709a0c8e65..025d96ea2d 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/H2ApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/H2ApplicationDAOImpl.java @@ -42,49 +42,6 @@ public class H2ApplicationDAOImpl extends AbstractApplicationDAOImpl { private static final Log log = LogFactory.getLog(H2ApplicationDAOImpl.class); - @Override - public void changeLifecycle(String applicationUUID, String lifecycleIdentifier) throws ApplicationManagementDAOException { - - } - - @Override - public List getNextLifeCycleStates(String applicationUUID, int tenantId) - throws ApplicationManagementDAOException { - Connection connection = null; - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - - String sql = "SELECT STATE.NAME, TRANSITION.DESCRIPTION, TRANSITION.PERMISSION FROM ( SELECT * FROM " - + "APPM_LIFECYCLE_STATE ) STATE RIGHT JOIN (SELECT * FROM APPM_LIFECYCLE_STATE_TRANSITION WHERE " - + "INITIAL_STATE = (SELECT LIFECYCLE_STATE_ID FROM APPM_APPLICATION WHERE UUID = ?)) " - + "TRANSITION ON TRANSITION.NEXT_STATE = STATE.ID"; - - try { - connection = this.getDBConnection(); - preparedStatement = connection.prepareStatement(sql); - preparedStatement.setString(1, applicationUUID); - resultSet = preparedStatement.executeQuery(); - - List lifecycleStateTransitions = new ArrayList<>(); - - while(resultSet.next()) { - LifecycleStateTransition lifecycleStateTransition = new LifecycleStateTransition(); - lifecycleStateTransition.setDescription(resultSet.getString(2)); - lifecycleStateTransition.setNextState(resultSet.getString(1)); - lifecycleStateTransition.setPermission(resultSet.getString(3)); - lifecycleStateTransitions.add(lifecycleStateTransition); - } - return lifecycleStateTransitions; - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error while getting the DBConnection for getting the life " - + "cycle states for the application with the UUID : " + applicationUUID, e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("SQL exception while executing the query '" + sql + "'.", e); - } finally { - Util.cleanupResources(preparedStatement, resultSet); - } - } - @Override public ApplicationList getApplications(Filter filter) throws ApplicationManagementDAOException { @@ -173,11 +130,6 @@ public class H2ApplicationDAOImpl extends AbstractApplicationDAOImpl { return applicationList; } - @Override - public Application getApplication(String uuid) throws ApplicationManagementDAOException { - return null; - } - @Override public int getApplicationId(String uuid) throws ApplicationManagementDAOException { return 0; @@ -213,11 +165,6 @@ public class H2ApplicationDAOImpl extends AbstractApplicationDAOImpl { } - @Override - public void changeLifeCycle(LifecycleState lifecycleState) throws ApplicationManagementDAOException { - - } - @Override public void addRelease(ApplicationRelease release) throws ApplicationManagementDAOException { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/MySQLApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/MySQLApplicationDAOImpl.java index 73bdb55dd1..bbf30ab2fb 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/MySQLApplicationDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/MySQLApplicationDAOImpl.java @@ -134,60 +134,6 @@ public class MySQLApplicationDAOImpl extends AbstractApplicationDAOImpl { return applicationList; } - @Override - public Application getApplication(String uuid) throws ApplicationManagementDAOException { - if (log.isDebugEnabled()) { - log.debug("Getting application data from the database"); - } - - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - String sql = ""; - Application application = new Application(); - try { - - conn = this.getConnection(); - - sql += "SELECT SQL_CALC_FOUND_ROWS APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, "; - sql += "CAT.ID AS CAT_ID, CAT.NAME AS CAT_NAME "; - sql += "FROM APPM_APPLICATION AS APP "; - sql += "INNER JOIN APPM_PLATFORM AS APL ON APP.PLATFORM_ID = APL.ID "; - sql += "INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON APP.APPLICATION_CATEGORY_ID = CAT.ID "; - sql += "WHERE UUID = ?"; - - stmt = conn.prepareStatement(sql); - stmt.setString(1, uuid); - rs = stmt.executeQuery(); - - if (rs.next()) { - //Getting properties - sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, rs.getInt("ID")); - ResultSet rsProperties = stmt.executeQuery(); - - //Getting tags - sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, rs.getInt("ID")); - ResultSet rsTags = stmt.executeQuery(); - - application = Util.loadApplication(rs, rsProperties, rsTags); - Util.cleanupResources(null, rsProperties); - Util.cleanupResources(null, rsTags); - } - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while getting application List", e); - } catch (JSONException e) { - throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } finally { - Util.cleanupResources(stmt, rs); - } - return application; - } @Override public void deleteApplication(String uuid) throws ApplicationManagementDAOException { @@ -373,40 +319,6 @@ public class MySQLApplicationDAOImpl extends AbstractApplicationDAOImpl { } } - @Override - public void changeLifecycle(String applicationUUID, String lifecycleIdentifier) throws ApplicationManagementDAOException { - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getDBConnection(); - String sql = "UPDATE APPM_APPLICATION SET " + - "LIFECYCLE_STATE_ID = (SELECT ID FROM APPM_LIFECYCLE_STATE WHERE IDENTIFIER = ?), " + - "LIFECYCLE_STATE_MODIFIED_BY = ?, " + - "LIFECYCLE_STATE_MODIFIED_AT = ? " + - "WHERE UUID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, lifecycleIdentifier); - stmt.setString(2, "admin"); - stmt.setDate(3, new Date(System.currentTimeMillis())); - stmt.setString(4, applicationUUID); - stmt.executeUpdate(); - - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while changing lifecycle of application: " + applicationUUID + " to: " + lifecycleIdentifier + " state.", e); - } finally { - Util.cleanupResources(stmt, rs); - } - } - - @Override - public List getNextLifeCycleStates(String applicationUUID, int tenantId) - throws ApplicationManagementDAOException { - return null; - } - @Override public void deleteTags(int applicationId) throws ApplicationManagementDAOException { @@ -429,11 +341,6 @@ public class MySQLApplicationDAOImpl extends AbstractApplicationDAOImpl { } } - @Override - public void changeLifeCycle(LifecycleState lifecycleState) throws ApplicationManagementDAOException { - - } - @Override public void addRelease(ApplicationRelease release) throws ApplicationManagementDAOException { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java index e4139c74a1..358770320d 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.application.mgt.core.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.ApplicationList; @@ -38,16 +39,21 @@ import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.exception.ValidationException; +import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.HelperUtil; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import java.util.ArrayList; import java.util.Date; import java.util.List; public class ApplicationManagerImpl implements ApplicationManager { private static final Log log = LogFactory.getLog(ApplicationManagerImpl.class); - public static final String CREATED = "CREATED"; + private static final String CREATED = "CREATED"; @Override public Application createApplication(Application application) throws ApplicationManagementException { @@ -154,21 +160,45 @@ public class ApplicationManagerImpl implements ApplicationManager { public ApplicationList getApplications(Filter filter) throws ApplicationManagementException { try { - ConnectionManagerUtil.openConnection(); + ConnectionManagerUtil.openDBConnection(); ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO(); return applicationDAO.getApplications(filter); } finally { - ConnectionManagerUtil.closeConnection(); + ConnectionManagerUtil.closeDBConnection(); } } @Override - public void changeLifecycle(String applicationUUID, String lifecycleIdentifier) throws ApplicationManagementException { + public void changeLifecycle(String applicationUUID, String lifecycleIdentifier) throws + ApplicationManagementException { + boolean isAvailableNextState = false; + String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + List nextLifeCycles = getLifeCycleStates(applicationUUID); + + for (LifecycleStateTransition lifecycleStateTransition : nextLifeCycles) { + if (log.isDebugEnabled()) { + log.debug("Lifecycle state of the application " + applicationUUID + " can be changed to" + + lifecycleStateTransition.getNextState()); + } + if (lifecycleStateTransition.getNextState().equalsIgnoreCase(lifecycleIdentifier)) { + isAvailableNextState = true; + break; + } + } + if (!isAvailableNextState) { + throw new ApplicationManagementException("User " + userName + " does not have the permission to change " + + "the lifecycle state of the application " + applicationUUID + " to lifecycle state " + + lifecycleIdentifier); + } try { - ConnectionManagerUtil.openDBConnection(); + ConnectionManagerUtil.beginDBTransaction(); ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO(); - applicationDAO.changeLifecycle(applicationUUID, lifecycleIdentifier); + applicationDAO.changeLifecycle(applicationUUID, lifecycleIdentifier, userName); + ConnectionManagerUtil.commitDBTransaction(); + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw e; } finally { ConnectionManagerUtil.closeDBConnection(); } @@ -177,15 +207,109 @@ public class ApplicationManagerImpl implements ApplicationManager { @Override public List getLifeCycleStates(String applicationUUID) throws ApplicationManagementException { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + boolean isAdminOrApplicationOwner = isApplicationOwnerOrAdmin(applicationUUID, userName, tenantId); + + if (log.isDebugEnabled()) { + log.debug("User " + userName + " in tenant " + tenantId + " is an Admin or Application owner of the " + + "application " + applicationUUID); + } + try { + ConnectionManagerUtil.openDBConnection(); + List transitions = DAOFactory.getApplicationDAO() + .getNextLifeCycleStates(applicationUUID, tenantId); + List filteredTransitions = new ArrayList<>(); + + if (log.isDebugEnabled()) { + log.debug("Lifecycle of the application with UUID : " + applicationUUID + " can be changed to " + + transitions.size() + ". The number may vary according to the permission level of user : " + + userName + " of tenant " + tenantId); + } + for (LifecycleStateTransition transition : transitions) { + String permission = transition.getPermission(); + if (permission != null) { + if (log.isDebugEnabled()) { + log.debug("In order to make the state change to " + transition.getNextState() + " permission " + + permission + " is required"); + } + if (isAuthorized(userName, tenantId, permission)) { + filteredTransitions.add(transition); + } else { + if (log.isDebugEnabled()) { + log.debug("User " + userName + " does not have the permission " + permission + " to " + + "change the life-cycle state to " + transition.getNextState() + " of the " + + "application " + applicationUUID); + } + } + } else if (isAdminOrApplicationOwner) { + filteredTransitions.add(transition); + } + } + if (log.isDebugEnabled()) { + log.debug("User " + userName + " can do " + filteredTransitions.size() + " life-cyle state changes " + + "currently on application with the UUID " + applicationUUID); + } + return filteredTransitions; + } catch (UserStoreException e) { + throw new ApplicationManagementException( + "Userstore exception while checking whether user " + userName + " from tenant " + tenantId + + " is authorized to do a life-cycle status change in an application ", e); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + @Override + public Application getApplication(String uuid) throws ApplicationManagementException { + try { + ConnectionManagerUtil.openDBConnection(); + return DAOFactory.getApplicationDAO().getApplication(uuid); + } finally { + ConnectionManagerUtil.closeDBConnection(); + } + } + + /** + * To check whether current user is application owner or admin. + * + * @param applicationUUID UUID of the Application. + * @return true if the current user is application owner or admin, unless false. + * @throws ApplicationManagementException Application Management Exception. + */ + private boolean isApplicationOwnerOrAdmin(String applicationUUID, String userName, int tenantId) + throws ApplicationManagementException { try { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { + return true; + } + } catch (UserStoreException e) { + throw new ApplicationManagementException("Userstore exception while checking whether user is an admin", e); + } try { ConnectionManagerUtil.openDBConnection(); - return DAOFactory.getApplicationDAO().getNextLifeCycleStates(applicationUUID, tenantId); + Application application = DAOFactory.getApplicationDAO().getApplication(applicationUUID); + return application.getUser().getUserName().equals(userName) + && application.getUser().getTenantId() == tenantId; } finally { ConnectionManagerUtil.closeDBConnection(); } } + /** + * To check whether current user has the permission to do some secured operation. + * + * @param username Name of the User. + * @param tenantId ID of the tenant. + * @param permission Permission that need to be checked. + * @return true if the current user has the permission, otherwise false. + * @throws UserStoreException UserStoreException + */ + private boolean isAuthorized (String username, int tenantId, String permission) throws UserStoreException { + UserRealm userRealm = DataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId); + return userRealm != null && userRealm.getAuthorizationManager() != null && userRealm.getAuthorizationManager() + .isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), + permission, CarbonConstants.UI_PERMISSION_ACTION); + } /** * To validate the application * @@ -210,7 +334,5 @@ public class ApplicationManagerImpl implements ApplicationManager { if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) { throw new ValidationException("Platform identifier cannot be empty"); } - - } } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java index ace8622010..192fd11324 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java @@ -31,11 +31,12 @@ public class Constants { public static final String PLATFORMS_DEPLOYMENT_DIR_NAME = "platforms"; public static final String PLATFORM_DEPLOYMENT_EXT = ".xml"; + /** + * Database types supported by Application Management. + */ public static final class DataBaseTypes { - private DataBaseTypes() { } - public static final String DB_TYPE_MYSQL = "MySQL"; public static final String DB_TYPE_ORACLE = "Oracle"; public static final String DB_TYPE_MSSQL = "Microsoft SQL Server"; @@ -43,4 +44,10 @@ public class Constants { public static final String DB_TYPE_H2 = "H2"; public static final String DB_TYPE_POSTGRESQL = "PostgreSQL"; } + + /** + * Lifecycle states of the application life-cycle. + */ + public static final String[] LIFE_CYCLES = {"CREATED", "IN REVIEW", "APPROVED", "REJECTED", "PUBLISHED", + "UNPUBLISHED", "RETIRED"}; } diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql index fdfe7ef13d..c2b9a615b4 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/h2.sql @@ -67,7 +67,7 @@ CREATE TABLE IF NOT EXISTS APPM_LIFECYCLE_STATE ( INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) VALUES ('CREATED', 'CREATED', 'Application creation initial state'); INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) -VALUES ('IN REVIEW', 'IN REFVIEW', 'Application is in in-review state'); +VALUES ('IN REVIEW', 'IN REVIEW', 'Application is in in-review state'); INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) VALUES ('APPROVED', 'APPROVED', 'State in which Application is approved after reviewing.'); INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) @@ -139,7 +139,7 @@ CREATE TABLE IF NOT EXISTS `APPM_APPLICATION` ( `LIFECYCLE_STATE_ID` INT NOT NULL, `LIFECYCLE_STATE_MODIFIED_BY` VARCHAR(255) NULL, `LIFECYCLE_STATE_MODIFIED_AT` DATETIME NULL, - `TENANT_ID` INT NULL, + `TENANT_ID` INT NOT NULL, `PLATFORM_ID` INT NOT NULL, PRIMARY KEY (`ID`, `APPLICATION_CATEGORY_ID`, `LIFECYCLE_STATE_ID`, `PLATFORM_ID`), UNIQUE INDEX `UUID_UNIQUE` (`UUID` ASC), From 9ec12587c744e50317f5ae8702820ad4b1b9eb16 Mon Sep 17 00:00:00 2001 From: megala21 Date: Mon, 14 Aug 2017 17:39:45 +0530 Subject: [PATCH 2/2] Fixing issues with Application Management with mysql --- .../services/ApplicationManagementAPI.java | 84 ++- .../impl/ApplicationManagementAPIImpl.java | 10 +- .../src/main/webapp/META-INF/permissions.xml | 18 + .../mgt/core/dao/ApplicationDAO.java | 2 +- .../mgt/core/dao/common/DAOFactory.java | 6 +- .../application/mgt/core/dao/common/Util.java | 39 +- .../AbstractApplicationDAOImpl.java | 315 --------- .../GenericApplicationDAOImpl.java | 600 ++++++++++++++++++ .../application/H2ApplicationDAOImpl.java | 174 ----- .../application/MySQLApplicationDAOImpl.java | 348 ---------- .../impl/platform/GenericPlatformDAOImpl.java | 6 +- .../mgt/core/impl/ApplicationManagerImpl.java | 48 +- .../dbscripts/cdm/application-mgt/mysql.sql | 69 +- 13 files changed, 833 insertions(+), 886 deletions(-) delete mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/AbstractApplicationDAOImpl.java create mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java delete mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/H2ApplicationDAOImpl.java delete mode 100644 components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/MySQLApplicationDAOImpl.java diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/ApplicationManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/ApplicationManagementAPI.java index 9e5927eb1e..8feb8e2c4f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/ApplicationManagementAPI.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/ApplicationManagementAPI.java @@ -52,7 +52,8 @@ import java.util.List; } ), tags = { - @Tag(name = "application_management", description = "Application Management related APIs") + @Tag(name = "application_management, device_management", description = "Application Management related " + + "APIs") } ) @Scopes( @@ -69,11 +70,23 @@ import java.util.List; key = "perm:application:create", permissions = {"/device-mgt/application/create"} ), + @Scope( + name = "Update an Application", + description = "Update an application", + key = "perm:application:update", + permissions = {"/device-mgt/application/update"} + ), @Scope( name = "Create an Application", description = "Create an application", key = "perm:application-mgt:login", permissions = {"/device-mgt/application-mgt/login"} + ), + @Scope( + name = "Delete an Application", + description = "Delete an application", + key = "perm:application:delete", + permissions = {"/device-mgt/application/delete"} ) } @@ -178,6 +191,41 @@ public interface ApplicationManagementAPI { @PathParam("uuid") String uuid ); + @PUT + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Edit an application", + notes = "This will edit the new application", + tags = "Application Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:application:update") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 201, + message = "OK. \n Successfully edited the application.", + response = Application.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while editing the application.", + response = ErrorResponse.class) + }) + Response editApplication( + @ApiParam( + name = "application", + value = "The application that need to be edited.", + required = true) + @Valid Application application); + + @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -289,4 +337,38 @@ public interface ApplicationManagementAPI { value = "Unique identifier of the Application", required = true) @PathParam("uuid") String applicationUUID); + + @DELETE + @Consumes("application/json") + @Path("/{appuuid}") + @ApiOperation( + consumes = MediaType.APPLICATION_JSON, + produces = MediaType.APPLICATION_JSON, + httpMethod = "DELETE", + value = "Delete the application with the given UUID", + notes = "This will delete the application with the given UUID", + tags = "Application Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = SCOPE, value = "perm:application:delete") + }) + } + ) + @ApiResponses( + value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully deleted the application identified by UUID.", + response = List.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Error occurred while deleteing the application.", + response = ErrorResponse.class) + }) + Response deleteApplication( + @ApiParam( + name = "UUID", + value = "Unique identifier of the Application", + required = true) + @PathParam("appuuid") String applicationUUID); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java index ef6e4209fc..f5a0228ad6 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java @@ -165,18 +165,13 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { public Response editApplication(@Valid Application application) { ApplicationManager applicationManager = APIUtil.getApplicationManager(); - - //TODO : Get username and tenantId - User user = new User("admin", -1234); - application.setUser(user); - try { application = applicationManager.editApplication(application); } catch (ApplicationManagementException e) { String msg = "Error occurred while creating the application"; log.error(msg, e); - return Response.status(Response.Status.BAD_REQUEST).build(); + return APIUtil.getResponse(e, Response.Status.BAD_REQUEST); } return Response.status(Response.Status.OK).entity(application).build(); } @@ -187,11 +182,10 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { ApplicationManager applicationManager = APIUtil.getApplicationManager(); try { applicationManager.deleteApplication(uuid); - } catch (ApplicationManagementException e) { String msg = "Error occurred while deleting the application: " + uuid; log.error(msg, e); - return Response.status(Response.Status.BAD_REQUEST).build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } String responseMsg = "Successfully deleted the application: " + uuid; return Response.status(Response.Status.OK).entity(responseMsg).build(); diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/webapp/META-INF/permissions.xml index 0a4e39c82b..8cc36248a1 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -43,6 +43,24 @@ /application-mgt/applications POST + + Edit Application + /device-mgt/application/update + /application-mgt/applications + PUT + + + Login to Application Management + /device-mgt/application-mgt/login + /application-mgt/applications + PUT + + + Login to Application Management + device-mgt/application/delete + /application-mgt/applications/* + DELETE + diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java index 450c90001f..3fbd9ea56b 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java @@ -41,7 +41,7 @@ public interface ApplicationDAO { int getApplicationId(String uuid) throws ApplicationManagementDAOException; - Application editApplication(Application application) throws ApplicationManagementDAOException; + Application editApplication(Application application, int tenantId) throws ApplicationManagementDAOException; void deleteApplication(String uuid) throws ApplicationManagementDAOException; diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/DAOFactory.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/DAOFactory.java index c70e9c8c00..87b485527f 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/DAOFactory.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/DAOFactory.java @@ -25,8 +25,7 @@ import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO; import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO; import org.wso2.carbon.device.application.mgt.core.dao.PlatformDAO; -import org.wso2.carbon.device.application.mgt.core.dao.impl.application.H2ApplicationDAOImpl; -import org.wso2.carbon.device.application.mgt.core.dao.impl.application.MySQLApplicationDAOImpl; +import org.wso2.carbon.device.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate.GenericLifecycleStateImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.platform.GenericPlatformDAOImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.platform.OracleMsSQLPlatformDAOImpl; @@ -58,9 +57,8 @@ public class DAOFactory { if (databaseEngine != null) { switch (databaseEngine) { case Constants.DataBaseTypes.DB_TYPE_H2: - return new H2ApplicationDAOImpl(); case Constants.DataBaseTypes.DB_TYPE_MYSQL: - return new MySQLApplicationDAOImpl(); + return new GenericApplicationDAOImpl(); default: throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java index ddc60a1d49..5b1e0dfaeb 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java @@ -21,10 +21,7 @@ package org.wso2.carbon.device.application.mgt.core.dao.common; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; -import org.wso2.carbon.device.application.mgt.common.Application; -import org.wso2.carbon.device.application.mgt.common.Category; -import org.wso2.carbon.device.application.mgt.common.Platform; -import org.wso2.carbon.device.application.mgt.common.User; +import org.wso2.carbon.device.application.mgt.common.*; import org.wso2.carbon.device.application.mgt.core.util.JSONUtil; import java.sql.PreparedStatement; @@ -35,13 +32,25 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +/** + * This class is responsible for handling the utils of the Application Management DAO. + */ public class Util { private static final Log log = LogFactory.getLog(Util.class); + /** + * To create application object from the result set retrieved from the Database. + * + * @param rs ResultSet + * @param rsProperties Properties resultset. + * @param rsTags Tags resultset + * @return Application that is retrieved from the Database. + * @throws SQLException SQL Exception + * @throws JSONException JSONException. + */ public static Application loadApplication(ResultSet rs, ResultSet rsProperties, ResultSet rsTags) throws SQLException, JSONException { - Application application = new Application(); application.setId(rs.getInt("ID")); application.setName(rs.getString("NAME")); @@ -55,7 +64,7 @@ public class Util { application.setScreenshots(JSONUtil.jsonArrayStringToList(rs.getString("SCREENSHOTS"))); application.setCreatedAt(rs.getDate("CREATED_AT")); application.setModifiedAt(rs.getDate("MODIFIED_AT")); - application.setUser(new User(rs.getString("CREATED_AT"), rs.getInt("TENANT_ID"))); + application.setUser(new User(rs.getString("CREATED_BY"), rs.getInt("TENANT_ID"))); Platform platform = new Platform(); platform.setName(rs.getString("APL_NAME")); @@ -69,7 +78,7 @@ public class Util { application.setProperties(properties); List tags = new ArrayList<>(); - while ((rsTags.next())){ + while ((rsTags.next())) { tags.add(rsTags.getString("NAME")); } application.setTags(tags); @@ -78,9 +87,25 @@ public class Util { category.setId(rs.getInt("CAT_ID")); category.setName(rs.getString("CAT_NAME")); application.setCategory(category); + + LifecycleState lifecycleState = new LifecycleState(); + lifecycleState.setId(rs.getInt("LIFECYCLE_STATE_ID")); + lifecycleState.setName(rs.getString("LS_NAME")); + lifecycleState.setIdentifier(rs.getString("LS_IDENTIFIER")); + lifecycleState.setDescription(rs.getString("LS_DESCRIPTION")); + + Lifecycle lifecycle = new Lifecycle(); + lifecycle.setLifecycleState(lifecycleState); + application.setCurrentLifecycle(lifecycle); return application; } + /** + * Cleans up the statement and resultset after executing the query + * + * @param stmt Statement executed. + * @param rs Resultset retrived. + */ public static void cleanupResources(PreparedStatement stmt, ResultSet rs) { if (rs != null) { try { diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/AbstractApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/AbstractApplicationDAOImpl.java deleted file mode 100644 index 784220f53e..0000000000 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/AbstractApplicationDAOImpl.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.application.mgt.core.dao.impl.application; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONException; -import org.wso2.carbon.device.application.mgt.common.Application; -import org.wso2.carbon.device.application.mgt.common.Filter; -import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition; -import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; -import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO; -import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; -import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; -import org.wso2.carbon.device.application.mgt.core.dao.common.Util; -import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; -import org.wso2.carbon.device.application.mgt.core.util.JSONUtil; - -import java.sql.*; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -public abstract class AbstractApplicationDAOImpl extends AbstractDAOImpl implements ApplicationDAO { - - private static final Log log = LogFactory.getLog(AbstractApplicationDAOImpl.class); - - public Application createApplication(Application application) throws ApplicationManagementDAOException { - if (log.isDebugEnabled()) { - log.debug("Request received in DAO Layer to create an application"); - log.debug("Application Details : "); - log.debug("UUID : " + application.getUuid() + " Name : " + application.getName() + " User name : " - + application.getUser().getUserName()); - } - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - String sql = ""; - boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported(); - - try { - conn = this.getDBConnection(); - sql += "INSERT INTO APPM_APPLICATION (UUID, IDENTIFIER, NAME, SHORT_DESCRIPTION, DESCRIPTION, ICON_NAME, " - + "BANNER_NAME, VIDEO_NAME, SCREENSHOTS, CREATED_BY, CREATED_AT, MODIFIED_AT, " - + "APPLICATION_CATEGORY_ID, PLATFORM_ID, TENANT_ID, LIFECYCLE_STATE_ID, " - + "LIFECYCLE_STATE_MODIFIED_AT, LIFECYCLE_STATE_MODIFIED_BY) VALUES " - + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - - stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - stmt.setString(1, application.getUuid()); - stmt.setString(2, application.getIdentifier()); - stmt.setString(3, application.getName()); - stmt.setString(4, application.getShortDescription()); - stmt.setString(5, application.getDescription()); - stmt.setString(6, application.getIconName()); - stmt.setString(7, application.getBannerName()); - stmt.setString(8, application.getVideoName()); - stmt.setString(9, JSONUtil.listToJsonArrayString(application.getScreenshots())); - stmt.setString(10, application.getUser().getUserName()); - stmt.setDate(11, new Date(application.getCreatedAt().getTime())); - stmt.setDate(12, new Date(application.getModifiedAt().getTime())); - stmt.setInt(13, application.getCategory().getId()); - stmt.setInt(14, application.getPlatform().getId()); - stmt.setInt(15, application.getUser().getTenantId()); - stmt.setInt(16, application.getCurrentLifecycle().getLifecycleState().getId()); - stmt.setDate(17, new Date( - application.getCurrentLifecycle().getLifecycleStateModifiedAt().getTime())); - stmt.setString(18, application.getCurrentLifecycle().getGetLifecycleStateModifiedBy()); - stmt.executeUpdate(); - - rs = stmt.getGeneratedKeys(); - if (rs.next()) { - application.setId(rs.getInt(1)); - } - - if (application.getTags() != null && application.getTags().size() > 0) { - sql = "INSERT INTO APPM_APPLICATION_TAG (NAME, APPLICATION_ID) VALUES (?, ?); "; - stmt = conn.prepareStatement(sql); - for (String tag : application.getTags()) { - stmt.setString(1, tag); - stmt.setInt(2, application.getId()); - - if (isBatchExecutionSupported) { - stmt.addBatch(); - } else { - stmt.execute(); - } - } - if (isBatchExecutionSupported) { - stmt.executeBatch(); - } - } - - if (application.getProperties() != null && application.getProperties().size() > 0) { - sql = "INSERT INTO APPM_APPLICATION_PROPERTY (PROP_KEY, PROP_VAL, APPLICATION_ID) VALUES (?, ?, ?); "; - stmt = conn.prepareStatement(sql); - Iterator it = application.getProperties().entrySet().iterator(); - while (it.hasNext()) { - Map.Entry property = (Map.Entry) it.next(); - stmt.setString(1, property.getKey()); - stmt.setString(2, property.getValue()); - stmt.setInt(3, application.getId()); - if (isBatchExecutionSupported) { - stmt.addBatch(); - } else { - stmt.execute(); - } - } - if (isBatchExecutionSupported) { - stmt.executeBatch(); - } - } - - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while adding the application", e); - } finally { - Util.cleanupResources(stmt, rs); - } - - return application; - } - - @Override - public int getApplicationCount(Filter filter) throws ApplicationManagementDAOException { - if(log.isDebugEnabled()){ - log.debug("Getting application count from the database"); - log.debug(String.format("Filter: limit=%s, offset=%", filter.getLimit(), filter.getOffset())); - } - - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - String sql = ""; - int count = 0; - - if (filter == null) { - throw new ApplicationManagementDAOException("Filter need to be instantiated"); - } - - try { - conn = this.getConnection(); - sql += "SELECT COUNT(APP.ID) AS APP_COUNT "; - sql += "FROM APPM_APPLICATION AS APP "; - sql += "INNER JOIN APPM_PLATFORM AS APL ON APP.PLATFORM_ID = APL.ID "; - sql += "INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON APP.APPLICATION_CATEGORY_ID = CAT.ID "; - - if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { - sql += "WHERE APP.NAME LIKE ? "; - } - sql += ";"; - - stmt = conn.prepareStatement(sql); - int index = 0; - if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { - stmt.setString(++index, "%" + filter.getSearchQuery() + "%"); - } - rs = stmt.executeQuery(); - if (rs.next()) { - count = rs.getInt("APP_COUNT"); - } - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while getting application List", e); - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } finally { - Util.cleanupResources(stmt, rs); - } - return count; - } - - @Override - public Application getApplication(String uuid) throws ApplicationManagementDAOException { - if (log.isDebugEnabled()) { - log.debug("Getting application with the UUID(" + uuid + ") from the database"); - } - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - String sql = ""; - Application application = null; - try { - - conn = this.getDBConnection(); - sql += "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, " - + "CAT.ID AS CAT_ID, CAT.NAME AS CAT_NAME FROM APPM_APPLICATION AS APP INNER JOIN APPM_PLATFORM AS " - + "APL ON APP.PLATFORM_ID = APL.ID INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON " - + "APP.APPLICATION_CATEGORY_ID = CAT.ID WHERE UUID = ?"; - - stmt = conn.prepareStatement(sql); - stmt.setString(1, uuid); - rs = stmt.executeQuery(); - - if (log.isDebugEnabled()) { - log.debug("Successfully retrieved basic details of the application with the UUID " + uuid); - } - - if (rs.next()) { - application = new Application(); - //Getting properties - sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, rs.getInt("ID")); - ResultSet rsProperties = stmt.executeQuery(); - - //Getting tags - sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, rs.getInt("ID")); - ResultSet rsTags = stmt.executeQuery(); - - application = Util.loadApplication(rs, rsProperties, rsTags); - Util.cleanupResources(null, rsProperties); - Util.cleanupResources(null, rsTags); - } - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while getting application List", e); - } catch (JSONException e) { - throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } finally { - Util.cleanupResources(stmt, rs); - } - return application; - } - - @Override - public void changeLifecycle(String applicationUUID, String lifecycleIdentifier, String userName) throws - ApplicationManagementDAOException { - if (log.isDebugEnabled()) { - log.debug("Change Life cycle status change " + lifecycleIdentifier + "request received to the DAO " - + "level for the application with " + "the UUID '" + applicationUUID + "' from the user " - + userName); - } - Connection conn; - PreparedStatement stmt = null; - try { - conn = this.getDBConnection(); - String sql = "UPDATE APPM_APPLICATION SET " - + "LIFECYCLE_STATE_ID = (SELECT ID FROM APPM_LIFECYCLE_STATE WHERE IDENTIFIER = ?), " - + "LIFECYCLE_STATE_MODIFIED_BY = ?, LIFECYCLE_STATE_MODIFIED_AT = ? WHERE UUID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, lifecycleIdentifier); - stmt.setString(2, userName); - stmt.setDate(3, new Date(System.currentTimeMillis())); - stmt.setString(4, applicationUUID); - stmt.executeUpdate(); - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException( - "Error occurred while changing lifecycle of application: " + applicationUUID + " to: " - + lifecycleIdentifier + " state.", e); - } finally { - Util.cleanupResources(stmt, null); - } - } - - @Override - public List getNextLifeCycleStates(String applicationUUID, int tenantId) - throws ApplicationManagementDAOException { - Connection connection = null; - PreparedStatement preparedStatement = null; - ResultSet resultSet = null; - - String sql = "SELECT STATE.NAME, TRANSITION.DESCRIPTION, TRANSITION.PERMISSION FROM ( SELECT * FROM " - + "APPM_LIFECYCLE_STATE ) STATE RIGHT JOIN (SELECT * FROM APPM_LIFECYCLE_STATE_TRANSITION WHERE " - + "INITIAL_STATE = (SELECT LIFECYCLE_STATE_ID FROM APPM_APPLICATION WHERE UUID = ?)) " - + "TRANSITION ON TRANSITION.NEXT_STATE = STATE.ID"; - - try { - connection = this.getDBConnection(); - preparedStatement = connection.prepareStatement(sql); - preparedStatement.setString(1, applicationUUID); - resultSet = preparedStatement.executeQuery(); - - List lifecycleStateTransitions = new ArrayList<>(); - - while(resultSet.next()) { - LifecycleStateTransition lifecycleStateTransition = new LifecycleStateTransition(); - lifecycleStateTransition.setDescription(resultSet.getString(2)); - lifecycleStateTransition.setNextState(resultSet.getString(1)); - lifecycleStateTransition.setPermission(resultSet.getString(3)); - lifecycleStateTransitions.add(lifecycleStateTransition); - } - return lifecycleStateTransitions; - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error while getting the DBConnection for getting the life " - + "cycle states for the application with the UUID : " + applicationUUID, e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("SQL exception while executing the query '" + sql + "'.", e); - } finally { - Util.cleanupResources(preparedStatement, resultSet); - } - } -} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java new file mode 100644 index 0000000000..ac92cddb1d --- /dev/null +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java @@ -0,0 +1,600 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.application.mgt.core.dao.impl.application; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONException; +import org.wso2.carbon.device.application.mgt.common.*; +import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; +import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO; +import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; +import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; +import org.wso2.carbon.device.application.mgt.core.dao.common.Util; +import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; +import org.wso2.carbon.device.application.mgt.core.util.JSONUtil; + +import java.sql.*; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class GenericApplicationDAOImpl extends AbstractDAOImpl implements ApplicationDAO { + + private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class); + + public Application createApplication(Application application) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Request received in DAO Layer to create an application"); + log.debug("Application Details : "); + log.debug("UUID : " + application.getUuid() + " Name : " + application.getName() + " User name : " + + application.getUser().getUserName()); + } + Connection conn = null; + PreparedStatement stmt = null; + ResultSet rs = null; + String sql = ""; + boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported(); + + try { + conn = this.getDBConnection(); + sql += "INSERT INTO APPM_APPLICATION (UUID, IDENTIFIER, NAME, SHORT_DESCRIPTION, DESCRIPTION, ICON_NAME, " + + "BANNER_NAME, VIDEO_NAME, SCREENSHOTS, CREATED_BY, CREATED_AT, MODIFIED_AT, " + + "APPLICATION_CATEGORY_ID, PLATFORM_ID, TENANT_ID, LIFECYCLE_STATE_ID, " + + "LIFECYCLE_STATE_MODIFIED_AT, LIFECYCLE_STATE_MODIFIED_BY) VALUES " + + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + stmt.setString(1, application.getUuid()); + stmt.setString(2, application.getIdentifier()); + stmt.setString(3, application.getName()); + stmt.setString(4, application.getShortDescription()); + stmt.setString(5, application.getDescription()); + stmt.setString(6, application.getIconName()); + stmt.setString(7, application.getBannerName()); + stmt.setString(8, application.getVideoName()); + stmt.setString(9, JSONUtil.listToJsonArrayString(application.getScreenshots())); + stmt.setString(10, application.getUser().getUserName()); + stmt.setDate(11, new Date(application.getCreatedAt().getTime())); + stmt.setDate(12, new Date(application.getModifiedAt().getTime())); + stmt.setInt(13, application.getCategory().getId()); + stmt.setInt(14, application.getPlatform().getId()); + stmt.setInt(15, application.getUser().getTenantId()); + stmt.setInt(16, application.getCurrentLifecycle().getLifecycleState().getId()); + stmt.setDate(17, new Date( + application.getCurrentLifecycle().getLifecycleStateModifiedAt().getTime())); + stmt.setString(18, application.getCurrentLifecycle().getGetLifecycleStateModifiedBy()); + stmt.executeUpdate(); + + rs = stmt.getGeneratedKeys(); + if (rs.next()) { + application.setId(rs.getInt(1)); + } + insertApplicationTagsAndProperties(application, stmt, conn, isBatchExecutionSupported); + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException("Error occurred while adding the application", e); + } finally { + Util.cleanupResources(stmt, rs); + } + + return application; + } + + + @Override + public ApplicationList getApplications(Filter filter) throws ApplicationManagementDAOException { + if(log.isDebugEnabled()){ + log.debug("Getting application data from the database"); + log.debug(String.format("Filter: limit=%s, offset=%", filter.getLimit(), filter.getOffset())); + } + + Connection conn = null; + PreparedStatement stmt = null; + ResultSet rs = null; + String sql = ""; + ApplicationList applicationList = new ApplicationList(); + List applications = new ArrayList<>(); + Pagination pagination = new Pagination(); + + if (filter == null) { + throw new ApplicationManagementDAOException("Filter need to be instantiated"); + } else { + pagination.setLimit(filter.getLimit()); + pagination.setOffset(filter.getOffset()); + } + + try { + conn = this.getDBConnection(); + sql += "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, " + + "CAT.ID AS CAT_ID, CAT.NAME AS CAT_NAME, LS.NAME AS LS_NAME, LS.IDENTIFIER AS LS_IDENTIFIER, " + + "LS.DESCRIPTION AS LS_DESCRIPTION FROM APPM_APPLICATION AS APP INNER JOIN APPM_PLATFORM AS " + + "APL ON APP.PLATFORM_ID = APL.ID INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON " + + "APP.APPLICATION_CATEGORY_ID = CAT.ID INNER JOIN APPM_LIFECYCLE_STATE AS " + + "LS ON APP.LIFECYCLE_STATE_ID = LS.ID "; + + if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { + sql += "WHERE APP.NAME LIKE ? "; + } + sql += "LIMIT ?,?;"; + + stmt = conn.prepareStatement(sql); + int index = 0; + if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { + stmt.setString(++index, "%" + filter.getSearchQuery() + "%"); + } + stmt.setInt(++index, filter.getOffset()); + stmt.setInt(++index, filter.getLimit()); + + rs = stmt.executeQuery(); + + int length = 0; + + while (rs.next()) { + //Getting properties + sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, rs.getInt("ID")); + ResultSet rsProperties = stmt.executeQuery(); + + //Getting tags + sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, rs.getInt("ID")); + ResultSet rsTags = stmt.executeQuery(); + + applications.add(Util.loadApplication(rs, rsProperties, rsTags)); + Util.cleanupResources(null, rsProperties); + Util.cleanupResources(null, rsTags); + length++; + } + + pagination.setSize(length); + pagination.setCount(this.getApplicationCount(filter)); + applicationList.setApplications(applications); + applicationList.setPagination(pagination); + } catch (SQLException e) { + throw new ApplicationManagementDAOException("Error occurred while getting application List", e); + } catch (JSONException e) { + throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } finally { + Util.cleanupResources(stmt, rs); + } + return applicationList; + } + + @Override + public int getApplicationCount(Filter filter) throws ApplicationManagementDAOException { + if(log.isDebugEnabled()){ + log.debug("Getting application count from the database"); + log.debug(String.format("Filter: limit=%s, offset=%", filter.getLimit(), filter.getOffset())); + } + + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + String sql = ""; + int count = 0; + + if (filter == null) { + throw new ApplicationManagementDAOException("Filter need to be instantiated"); + } + + try { + conn = this.getConnection(); + sql += "SELECT COUNT(APP.ID) AS APP_COUNT "; + sql += "FROM APPM_APPLICATION AS APP "; + sql += "INNER JOIN APPM_PLATFORM AS APL ON APP.PLATFORM_ID = APL.ID "; + sql += "INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON APP.APPLICATION_CATEGORY_ID = CAT.ID "; + + if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { + sql += "WHERE APP.NAME LIKE ? "; + } + sql += ";"; + + stmt = conn.prepareStatement(sql); + int index = 0; + if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { + stmt.setString(++index, "%" + filter.getSearchQuery() + "%"); + } + rs = stmt.executeQuery(); + if (rs.next()) { + count = rs.getInt("APP_COUNT"); + } + } catch (SQLException e) { + throw new ApplicationManagementDAOException("Error occurred while getting application List", e); + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } finally { + Util.cleanupResources(stmt, rs); + } + return count; + } + + @Override + public Application getApplication(String uuid) throws ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Getting application with the UUID(" + uuid + ") from the database"); + } + Connection conn = null; + PreparedStatement stmt = null; + ResultSet rs = null; + String sql = ""; + Application application = null; + try { + + conn = this.getDBConnection(); + sql += "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, " + + "CAT.ID AS CAT_ID, CAT.NAME AS CAT_NAME, LS.NAME AS LS_NAME, LS.IDENTIFIER AS LS_IDENTIFIER, " + + "LS.DESCRIPTION AS LS_DESCRIPTION FROM APPM_APPLICATION AS APP INNER JOIN APPM_PLATFORM AS " + + "APL ON APP.PLATFORM_ID = APL.ID INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON " + + "APP.APPLICATION_CATEGORY_ID = CAT.ID INNER JOIN APPM_LIFECYCLE_STATE AS " + + "LS ON APP.LIFECYCLE_STATE_ID = LS.ID WHERE UUID = ?"; + + stmt = conn.prepareStatement(sql); + stmt.setString(1, uuid); + rs = stmt.executeQuery(); + + if (log.isDebugEnabled()) { + log.debug("Successfully retrieved basic details of the application with the UUID " + uuid); + } + + if (rs.next()) { + //Getting properties + sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, rs.getInt("ID")); + ResultSet rsProperties = stmt.executeQuery(); + + //Getting tags + sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, rs.getInt("ID")); + ResultSet rsTags = stmt.executeQuery(); + + application = Util.loadApplication(rs, rsProperties, rsTags); + Util.cleanupResources(null, rsProperties); + Util.cleanupResources(null, rsTags); + } + } catch (SQLException e) { + throw new ApplicationManagementDAOException("Error occurred while getting application details with UUID " + + uuid, e); + } catch (JSONException e) { + throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } finally { + Util.cleanupResources(stmt, rs); + } + return application; + } + + @Override + public void changeLifecycle(String applicationUUID, String lifecycleIdentifier, String userName) throws + ApplicationManagementDAOException { + if (log.isDebugEnabled()) { + log.debug("Change Life cycle status change " + lifecycleIdentifier + "request received to the DAO " + + "level for the application with " + "the UUID '" + applicationUUID + "' from the user " + + userName); + } + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getDBConnection(); + String sql = "UPDATE APPM_APPLICATION SET " + + "LIFECYCLE_STATE_ID = (SELECT ID FROM APPM_LIFECYCLE_STATE WHERE IDENTIFIER = ?), " + + "LIFECYCLE_STATE_MODIFIED_BY = ?, LIFECYCLE_STATE_MODIFIED_AT = ? WHERE UUID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, lifecycleIdentifier); + stmt.setString(2, userName); + stmt.setDate(3, new Date(System.currentTimeMillis())); + stmt.setString(4, applicationUUID); + stmt.executeUpdate(); + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "Error occurred while changing lifecycle of application: " + applicationUUID + " to: " + + lifecycleIdentifier + " state.", e); + } finally { + Util.cleanupResources(stmt, null); + } + } + + @Override + public List getNextLifeCycleStates(String applicationUUID, int tenantId) + throws ApplicationManagementDAOException { + Connection connection = null; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + String sql = "SELECT STATE.NAME, TRANSITION.DESCRIPTION, TRANSITION.PERMISSION FROM ( SELECT * FROM " + + "APPM_LIFECYCLE_STATE ) STATE RIGHT JOIN (SELECT * FROM APPM_LIFECYCLE_STATE_TRANSITION WHERE " + + "INITIAL_STATE = (SELECT LIFECYCLE_STATE_ID FROM APPM_APPLICATION WHERE UUID = ?)) " + + "TRANSITION ON TRANSITION.NEXT_STATE = STATE.ID"; + + try { + connection = this.getDBConnection(); + preparedStatement = connection.prepareStatement(sql); + preparedStatement.setString(1, applicationUUID); + resultSet = preparedStatement.executeQuery(); + + List lifecycleStateTransitions = new ArrayList<>(); + + while(resultSet.next()) { + LifecycleStateTransition lifecycleStateTransition = new LifecycleStateTransition(); + lifecycleStateTransition.setDescription(resultSet.getString(2)); + lifecycleStateTransition.setNextState(resultSet.getString(1)); + lifecycleStateTransition.setPermission(resultSet.getString(3)); + lifecycleStateTransitions.add(lifecycleStateTransition); + } + return lifecycleStateTransitions; + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error while getting the DBConnection for getting the life " + + "cycle states for the application with the UUID : " + applicationUUID, e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException("SQL exception while executing the query '" + sql + "'.", e); + } finally { + Util.cleanupResources(preparedStatement, resultSet); + } + } + + @Override + public Application editApplication(Application application, int tenantId) throws ApplicationManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + ResultSet rs = null; + String sql = ""; + boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported(); + try { + conn = this.getDBConnection(); + int index = 0; + sql += "UPDATE APPM_APPLICATION SET NAME = IFNULL (?, NAME), SHORT_DESCRIPTION = IFNULL " + + "(?, SHORT_DESCRIPTION), DESCRIPTION = IFNULL (?, DESCRIPTION), ICON_NAME = IFNULL (?, ICON_NAME)" + + ", BANNER_NAME = IFNULL (?, BANNER_NAME), VIDEO_NAME = IFNULL (?, VIDEO_NAME), " + + "SCREENSHOTS = IFNULL (?, SCREENSHOTS), MODIFIED_AT = IFNULL (?, MODIFIED_AT), "; + + if (application.getPayment() != null) { + sql += " IS_FREE = IFNULL (?, IS_FREE), "; + if (application.getPayment().getPaymentCurrency() != null) { + sql += "PAYMENT_CURRENCY = IFNULL (?, PAYMENT_CURRENCY), "; + } + sql += "PAYMENT_PRICE = IFNULL (?, PAYMENT_PRICE), "; + } + if (application.getCategory() != null && application.getCategory().getId() != 0) { + sql += "APPLICATION_CATEGORY_ID = IFNULL (?, APPLICATION_CATEGORY_ID), "; + } + if (application.getPlatform() != null && application.getPlatform().getId() != 0) { + sql += "PLATFORM_ID = IFNULL (?, PLATFORM_ID), "; + } + + sql += "TENANT_ID = IFNULL (?, TENANT_ID) WHERE UUID = ?"; + + stmt = conn.prepareStatement(sql); + stmt.setString(++index, application.getName()); + stmt.setString(++index, application.getShortDescription()); + stmt.setString(++index, application.getDescription()); + stmt.setString(++index, application.getIconName()); + stmt.setString(++index, application.getBannerName()); + stmt.setString(++index, application.getVideoName()); + stmt.setString(++index, JSONUtil.listToJsonArrayString(application.getScreenshots())); + stmt.setDate(++index, new Date(application.getModifiedAt().getTime())); + if (application.getPayment() != null) { + stmt.setBoolean(++index, application.getPayment().isFreeApp()); + if (application.getPayment().getPaymentCurrency() != null) { + stmt.setString(++index, application.getPayment().getPaymentCurrency()); + } + stmt.setFloat(++index, application.getPayment().getPaymentPrice()); + } + + if (application.getCategory() != null && application.getCategory().getId() != 0) { + stmt.setInt(++index, application.getCategory().getId()); + } + if (application.getPlatform() != null && application.getPlatform().getId() != 0) { + stmt.setInt(++index, application.getPlatform().getId()); + } + stmt.setInt(++index, tenantId); + stmt.setString(++index, application.getUuid()); + stmt.executeUpdate(); + + application.setId(getApplicationId(application.getUuid())); + + sql = "DELETE FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, application.getId()); + stmt.executeUpdate(); + + // delete existing properties and add new ones. if no properties are set, existing ones will be deleted. + sql = "DELETE FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, application.getId()); + stmt.executeUpdate(); + + insertApplicationTagsAndProperties(application, stmt, conn, isBatchExecutionSupported); + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException("Error occurred while adding the application", e); + } + + return application; + } + + /** + * To insert application properties and Tags + * + * @param application Application in which the properties and tags need to be inserted + */ + private void insertApplicationTagsAndProperties (Application application, PreparedStatement stmt, Connection + conn, boolean isBatchExecutionSupported) throws SQLException { + String sql; + if (application.getTags() != null && application.getTags().size() > 0) { + sql = "INSERT INTO APPM_APPLICATION_TAG (NAME, APPLICATION_ID) VALUES (?, ?); "; + stmt = conn.prepareStatement(sql); + for (String tag : application.getTags()) { + stmt.setString(1, tag); + stmt.setInt(2, application.getId()); + + if (isBatchExecutionSupported) { + stmt.addBatch(); + } else { + stmt.execute(); + } + } + if (isBatchExecutionSupported) { + stmt.executeBatch(); + } + } + + if (application.getProperties() != null && application.getProperties().size() > 0) { + sql = "INSERT INTO APPM_APPLICATION_PROPERTY (PROP_KEY, PROP_VAL, APPLICATION_ID) VALUES (?, ?, ?); "; + stmt = conn.prepareStatement(sql); + Iterator it = application.getProperties().entrySet().iterator(); + while (it.hasNext()) { + Map.Entry property = (Map.Entry) it.next(); + stmt.setString(1, property.getKey()); + stmt.setString(2, property.getValue()); + stmt.setInt(3, application.getId()); + if (isBatchExecutionSupported) { + stmt.addBatch(); + } else { + stmt.execute(); + } + } + if (isBatchExecutionSupported) { + stmt.executeBatch(); + } + } + } + + @Override + public void deleteApplication(String uuid) throws ApplicationManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getDBConnection(); + String sql = "DELETE FROM APPM_APPLICATION WHERE UUID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, uuid); + stmt.executeUpdate(); + + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException("Error occurred while deleting the application: " + uuid, e); + } finally { + Util.cleanupResources(stmt, null); + } + } + + @Override + public void deleteProperties(int applicationId) throws ApplicationManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = this.getDBConnection(); + String sql = "DELETE FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, applicationId); + stmt.executeUpdate(); + + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "Error occurred while deleting properties of application: " + applicationId, e); + } finally { + Util.cleanupResources(stmt, null); + } + } + + @Override + public void deleteTags(int applicationId) throws ApplicationManagementDAOException { + + Connection conn = null; + PreparedStatement stmt = null; + ResultSet rs = null; + try { + conn = this.getDBConnection(); + String sql = "DELETE FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, applicationId); + stmt.executeUpdate(); + + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException( + "Error occurred while deleting tags of application: " + applicationId, e); + } finally { + Util.cleanupResources(stmt, rs); + } + } + + @Override + public int getApplicationId(String uuid) throws ApplicationManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + ResultSet rs = null; + String sql = ""; + + int id = 0; + + try { + conn = this.getDBConnection(); + sql += "SELECT ID FROM APPM_APPLICATION WHERE UUID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, uuid); + rs = stmt.executeQuery(); + if (rs.next()) { + id = rs.getInt(1); + } + } catch (DBConnectionException e) { + throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); + } catch (SQLException e) { + throw new ApplicationManagementDAOException("Error occurred while getting application List", e); + } finally { + Util.cleanupResources(stmt, rs); + } + + return id; + } + + + @Override + public void addProperties(Map properties) throws ApplicationManagementDAOException { + + } + + @Override + public void editProperties(Map properties) throws ApplicationManagementDAOException { + + } + + @Override + public void addRelease(ApplicationRelease release) throws ApplicationManagementDAOException { + + } + + +} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/H2ApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/H2ApplicationDAOImpl.java deleted file mode 100644 index 025d96ea2d..0000000000 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/H2ApplicationDAOImpl.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.application.mgt.core.dao.impl.application; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONException; -import org.wso2.carbon.device.application.mgt.common.*; -import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; -import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; -import org.wso2.carbon.device.application.mgt.core.dao.common.Util; -import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * This class holds the generic implementation of ApplicationDAO which can be used to support ANSI db syntax. - */ -public class H2ApplicationDAOImpl extends AbstractApplicationDAOImpl { - - private static final Log log = LogFactory.getLog(H2ApplicationDAOImpl.class); - - @Override - public ApplicationList getApplications(Filter filter) throws ApplicationManagementDAOException { - - if(log.isDebugEnabled()){ - log.debug("Getting application data from the database"); - log.debug(String.format("Filter: limit=%s, offset=%", filter.getLimit(), filter.getOffset())); - } - - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - String sql = ""; - ApplicationList applicationList = new ApplicationList(); - List applications = new ArrayList<>(); - Pagination pagination = new Pagination(); - - if (filter == null) { - throw new ApplicationManagementDAOException("Filter need to be instantiated"); - } else { - pagination.setLimit(filter.getLimit()); - pagination.setOffset(filter.getOffset()); - } - - try { - - conn = this.getConnection(); - - sql += "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER," + - " CAT.NAME AS CAT_NAME "; - sql += "FROM APPM_APPLICATION AS APP "; - sql += "INNER JOIN APPM_PLATFORM_APPLICATION_MAPPING AS APM ON APP.PLATFORM_APPLICATION_MAPPING_ID = APM.ID "; - sql += "INNER JOIN APPM_PLATFORM AS APL ON APM.PLATFORM_ID = APL.ID "; - sql += "INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON APP.APPLICATION_CATEGORY_ID = CAT.ID "; - - if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { - sql += "WHERE APP.NAME LIKE ? "; - } - sql += "LIMIT ?,?;"; - - stmt = conn.prepareStatement(sql); - int index = 0; - if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { - stmt.setString(++index, "%" + filter.getSearchQuery() + "%"); - } - stmt.setInt(++index, filter.getOffset()); - stmt.setInt(++index, filter.getLimit()); - - rs = stmt.executeQuery(); - - int length = 0; - - while (rs.next()) { - - //Getting properties - sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, rs.getInt("ID")); - ResultSet rsProperties = stmt.executeQuery(); - - //Getting tags - sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, rs.getInt("ID")); - ResultSet rsTags = stmt.executeQuery(); - - applications.add(Util.loadApplication(rs, rsProperties, rsTags)); - Util.cleanupResources(null, rsProperties); - Util.cleanupResources(null, rsTags); - length++; - } - - pagination.setSize(length); - pagination.setCount(this.getApplicationCount(filter)); - applicationList.setApplications(applications); - applicationList.setPagination(pagination); - - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while getting application List", e); - } catch (JSONException e) { - throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } finally { - Util.cleanupResources(stmt, rs); - } - return applicationList; - } - - @Override - public int getApplicationId(String uuid) throws ApplicationManagementDAOException { - return 0; - } - - @Override - public void deleteApplication(String uuid) throws ApplicationManagementDAOException { - - } - - @Override - public void deleteProperties(int applicationId) throws ApplicationManagementDAOException { - - } - - @Override - public void deleteTags(int applicationId) throws ApplicationManagementDAOException { - - } - - @Override - public Application editApplication(Application application) throws ApplicationManagementDAOException { - return null; - } - - @Override - public void addProperties(Map properties) throws ApplicationManagementDAOException { - - } - - @Override - public void editProperties(Map properties) throws ApplicationManagementDAOException { - - } - - @Override - public void addRelease(ApplicationRelease release) throws ApplicationManagementDAOException { - - } - - -} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/MySQLApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/MySQLApplicationDAOImpl.java deleted file mode 100644 index bbf30ab2fb..0000000000 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/MySQLApplicationDAOImpl.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.application.mgt.core.dao.impl.application; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONException; -import org.wso2.carbon.device.application.mgt.common.*; -import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; -import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; -import org.wso2.carbon.device.application.mgt.core.dao.common.Util; -import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; -import org.wso2.carbon.device.application.mgt.core.util.JSONUtil; - -import java.sql.*; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * This class holds the generic implementation of ApplicationDAO which can be used to support ANSI db syntax. - */ -public class MySQLApplicationDAOImpl extends AbstractApplicationDAOImpl { - - private static final Log log = LogFactory.getLog(MySQLApplicationDAOImpl.class); - - @Override - public ApplicationList getApplications(Filter filter) throws ApplicationManagementDAOException { - - if (log.isDebugEnabled()) { - log.debug("Getting application data from the database"); - log.debug(String.format("Filter: limit=%s, offset=%", filter.getLimit(), filter.getOffset())); - } - - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - String sql = ""; - ApplicationList applicationList = new ApplicationList(); - List applications = new ArrayList<>(); - Pagination pagination = new Pagination(); - - if (filter == null) { - throw new ApplicationManagementDAOException("Filter need to be instantiated"); - } else { - pagination.setLimit(filter.getLimit()); - pagination.setOffset(filter.getOffset()); - } - - try { - - conn = this.getConnection(); - - sql += "SELECT SQL_CALC_FOUND_ROWS APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, "; - sql += "CAT.ID AS CAT_ID, CAT.NAME AS CAT_NAME "; - sql += "FROM APPM_APPLICATION AS APP "; - sql += "INNER JOIN APPM_PLATFORM AS APL ON APP.PLATFORM_ID = APL.ID "; - sql += "INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON APP.APPLICATION_CATEGORY_ID = CAT.ID "; - - if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { - sql += "WHERE APP.NAME LIKE ? "; - } - sql += "LIMIT ?,?;"; - - stmt = conn.prepareStatement(sql); - int index = 0; - if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { - stmt.setString(++index, "%" + filter.getSearchQuery() + "%"); - } - stmt.setInt(++index, filter.getOffset()); - stmt.setInt(++index, filter.getLimit()); - - rs = stmt.executeQuery(); - - int length = 0; - sql = "SELECT FOUND_ROWS() AS COUNT;"; //TODO: from which tables???? - stmt = conn.prepareStatement(sql); - ResultSet rsCount = stmt.executeQuery(); - if (rsCount.next()) { - pagination.setCount(rsCount.getInt("COUNT")); - } - - while (rs.next()) { - - //Getting properties - sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, rs.getInt("ID")); - ResultSet rsProperties = stmt.executeQuery(); - - //Getting tags - sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, rs.getInt("ID")); - ResultSet rsTags = stmt.executeQuery(); - - applications.add(Util.loadApplication(rs, rsProperties, rsTags)); - Util.cleanupResources(null, rsProperties); - Util.cleanupResources(null, rsTags); - length++; - } - - pagination.setSize(length); - - applicationList.setApplications(applications); - applicationList.setPagination(pagination); - - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while getting application List", e); - } catch (JSONException e) { - throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } finally { - Util.cleanupResources(stmt, rs); - } - return applicationList; - } - - - @Override - public void deleteApplication(String uuid) throws ApplicationManagementDAOException { - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getDBConnection(); - String sql = "DELETE FROM APPM_APPLICATION WHERE UUID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, uuid); - stmt.executeUpdate(); - - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while deleting the application: " + uuid, e); - } finally { - Util.cleanupResources(stmt, rs); - } - } - - @Override - public int getApplicationId(String uuid) throws ApplicationManagementDAOException { - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - String sql = ""; - - int id = 0; - - try { - conn = this.getDBConnection(); - sql += "SELECT ID FROM APPM_APPLICATION WHERE UUID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setString(1, uuid); - rs = stmt.executeQuery(); - if (rs.next()) { - id = rs.getInt(1); - } - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while getting application List", e); - } finally { - Util.cleanupResources(stmt, rs); - } - - return id; - } - - @Override - public Application editApplication(Application application) throws ApplicationManagementDAOException { - - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - String sql = ""; - - try { - conn = this.getConnection(); - sql += "UPDATE APPM_APPLICATION SET "; - sql += "NAME = IFNULL (?, NAME), "; - sql += "SHORT_DESCRIPTION = IFNULL (?, SHORT_DESCRIPTION), DESCRIPTION = IFNULL (?, DESCRIPTION), "; - sql += "ICON_NAME = IFNULL (?, ICON_NAME), BANNER_NAME = IFNULL (?, BANNER_NAME), "; - sql += "VIDEO_NAME = IFNULL (?, VIDEO_NAME), SCREENSHOTS = IFNULL (?, SCREENSHOTS), "; - sql += "MODIFIED_AT = IFNULL (?, MODIFIED_AT), "; - if (application.getPayment() != null) { - sql += " IS_FREE = IFNULL (?, IS_FREE), "; - if (application.getPayment().getPaymentCurrency() != null) { - sql += "PAYMENT_CURRENCY = IFNULL (?, PAYMENT_CURRENCY), "; - } - sql += "PAYMENT_PRICE = IFNULL (?, PAYMENT_PRICE), "; - } - if (application.getCategory() != null && application.getCategory().getId() != 0) { - sql += "APPLICATION_CATEGORY_ID = IFNULL (?, APPLICATION_CATEGORY_ID), "; - } - if (application.getPlatform() != null && application.getPlatform().getId() != 0) { - sql += "PLATFORM_ID = IFNULL (?, PLATFORM_ID), "; - } - - sql += "TENANT_ID = IFNULL (?, TENANT_ID) "; - sql += "WHERE UUID = ?"; - - int i = 0; - stmt = conn.prepareStatement(sql); - stmt.setString(++i, application.getName()); - stmt.setString(++i, application.getShortDescription()); - stmt.setString(++i, application.getDescription()); - stmt.setString(++i, application.getIconName()); - stmt.setString(++i, application.getBannerName()); - stmt.setString(++i, application.getVideoName()); - stmt.setString(++i, JSONUtil.listToJsonArrayString(application.getScreenshots())); - stmt.setDate(++i, new Date(application.getModifiedAt().getTime())); - if (application.getPayment() != null) { - stmt.setBoolean(++i, application.getPayment().isFreeApp()); - if (application.getPayment().getPaymentCurrency() != null) { - stmt.setString(++i, application.getPayment().getPaymentCurrency()); - } - stmt.setFloat(++i, application.getPayment().getPaymentPrice()); - } - - if (application.getCategory() != null && application.getCategory().getId() != 0) { - stmt.setInt(++i, application.getCategory().getId()); - } - if (application.getPlatform() != null && application.getPlatform().getId() != 0) { - stmt.setInt(++i, application.getPlatform().getId()); - } - stmt.setInt(++i, application.getUser().getTenantId()); - stmt.setString(++i, application.getUuid()); - stmt.executeUpdate(); - - application.setId(getApplicationId(application.getUuid())); - - if (application.getTags() != null && application.getTags().size() > 0) { - sql = "DELETE FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, application.getId()); - stmt.executeUpdate(); - - sql = "INSERT INTO APPM_APPLICATION_TAG (NAME, APPLICATION_ID) VALUES (?, ?); "; - stmt = conn.prepareStatement(sql); - for (String tag : application.getTags()) { - stmt.setString(1, tag); - stmt.setInt(2, application.getId()); - stmt.addBatch(); - } - stmt.executeBatch(); - } - - // delete existing properties and add new ones. if no properties are set, existing ones will be deleted. - sql = "DELETE FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, application.getId()); - stmt.executeUpdate(); - - sql = "INSERT INTO APPM_APPLICATION_PROPERTY (PROP_KEY, PROP_VAL, APPLICATION_ID) VALUES (?, ?, ?); "; - stmt = conn.prepareStatement(sql); - for (String propKey : application.getProperties().keySet()) { - stmt.setString(1, propKey); - stmt.setString(2, application.getProperties().get(propKey)); - stmt.setInt(3, application.getId()); - stmt.addBatch(); - } - stmt.executeBatch(); - - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while adding the application", e); - } - - return application; - } - - @Override - public void addProperties(Map properties) throws ApplicationManagementDAOException { - - } - - @Override - public void editProperties(Map properties) throws ApplicationManagementDAOException { - - } - - @Override - public void deleteProperties(int applicationId) throws ApplicationManagementDAOException { - Connection conn = null; - PreparedStatement stmt = null; - try { - conn = this.getDBConnection(); - String sql = "DELETE FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, applicationId); - stmt.executeUpdate(); - - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while deleting properties of application: " + applicationId, e); - } finally { - Util.cleanupResources(stmt, null); - } - } - - @Override - public void deleteTags(int applicationId) throws ApplicationManagementDAOException { - - Connection conn = null; - PreparedStatement stmt = null; - ResultSet rs = null; - try { - conn = this.getDBConnection(); - String sql = "DELETE FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID = ?"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, applicationId); - stmt.executeUpdate(); - - } catch (DBConnectionException e) { - throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e); - } catch (SQLException e) { - throw new ApplicationManagementDAOException("Error occurred while deleting tags of application: " + applicationId, e); - } finally { - Util.cleanupResources(stmt, rs); - } - } - - @Override - public void addRelease(ApplicationRelease release) throws ApplicationManagementDAOException { - - } -} diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/GenericPlatformDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/GenericPlatformDAOImpl.java index 25f2d05d3a..de980fd5ed 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/GenericPlatformDAOImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/GenericPlatformDAOImpl.java @@ -227,13 +227,14 @@ public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformD public void unregister(int tenantId, String platformIdenfier, boolean isFileBased) throws PlatformManagementDAOException { PreparedStatement preparedStatement = null; + String deletePlatform = null; try { Platform platform = getPlatform(tenantId, platformIdenfier); if (platform != null) { if (isFileBased == platform.isFileBased()) { Connection connection = this.getDBConnection(); - String deletePlatform = "DELETE FROM APPM_PLATFORM WHERE ID = ?"; + deletePlatform = "DELETE FROM APPM_PLATFORM WHERE ID = ?"; preparedStatement = connection.prepareStatement(deletePlatform); preparedStatement.setInt(1, platform.getId()); preparedStatement.execute(); @@ -255,7 +256,8 @@ public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformD "Unable to obtain the connection while trying to register the platform - " + platformIdenfier + " for tenant - " + tenantId, e); } catch (SQLException e) { - throw new PlatformManagementDAOException("Error while executing the SQL query. ", e); + throw new PlatformManagementDAOException("Error while executing the SQL query : " + deletePlatform + " " + + "while trying to un-register the platform with identifier " + platformIdenfier, e); } finally { Util.cleanupResources(preparedStatement, null); } diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java index 358770320d..05afbb555c 100644 --- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java +++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java @@ -89,7 +89,6 @@ public class ApplicationManagerImpl implements ApplicationManager { } Lifecycle lifecycle = new Lifecycle(); lifecycle.setLifecycleState(lifecycleState); - lifecycle.setLifecycleState(lifecycleState); lifecycle.setLifecycleStateModifiedAt(new Date()); lifecycle.setGetLifecycleStateModifiedBy(application.getUser().getUserName()); application.setCurrentLifecycle(lifecycle); @@ -107,50 +106,63 @@ public class ApplicationManagerImpl implements ApplicationManager { @Override public Application editApplication(Application application) throws ApplicationManagementException { - + String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); if (application.getUuid() == null) { throw new ValidationException("Application UUID cannot be empty"); } + if (!isApplicationOwnerOrAdmin(application.getUuid(), userName, tenantId)) { + throw new ApplicationManagementException("User " + userName + " does not have permissions to edit the " + + "application with the UUID " + application.getUuid()); + } try { - ConnectionManagerUtil.openConnection(); - ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO(); - - if (application.getPlatform()!= null && application.getPlatform().getIdentifier() != null) { + ConnectionManagerUtil.beginDBTransaction(); + if (application.getPlatform() != null && application.getPlatform().getIdentifier() != null) { PlatformDAO platformDAO = DAOFactory.getPlatformDAO(); - Platform platform = platformDAO.getPlatform(application.getUser().getTenantId(), application.getPlatform() - .getIdentifier()); - application.setPlatform(platform); + Platform platform = platformDAO + .getPlatform(tenantId, application.getPlatform().getIdentifier()); if (platform == null) { - throw new NotFoundException("Invalid platform"); + ConnectionManagerUtil.commitDBTransaction(); + throw new NotFoundException( + "Platform specified by identifier " + application.getPlatform().getIdentifier() + + " is not found. Please give a valid platform identifier."); } + application.setPlatform(platform); } - + ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO(); application.setModifiedAt(new Date()); - - return applicationDAO.editApplication(application); + Application modifiedApplication = applicationDAO.editApplication(application, tenantId); + ConnectionManagerUtil.commitDBTransaction(); + return modifiedApplication; + } catch (ApplicationManagementDAOException e) { + ConnectionManagerUtil.rollbackDBTransaction(); + throw e; } finally { - ConnectionManagerUtil.closeConnection(); + ConnectionManagerUtil.closeDBConnection(); } - } @Override public void deleteApplication(String uuid) throws ApplicationManagementException { + String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); + if (!isApplicationOwnerOrAdmin(uuid, userName, tenantId)) { + throw new ApplicationManagementException("User '" + userName + "' of tenant - " + tenantId + " does have" + + " the permission to delete the application with UUID " + uuid); + } try { ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO(); - int appId = applicationDAO.getApplicationId(uuid); ConnectionManagerUtil.beginDBTransaction(); + int appId = applicationDAO.getApplicationId(uuid); applicationDAO.deleteTags(appId); applicationDAO.deleteProperties(appId); applicationDAO.deleteApplication(uuid); ConnectionManagerUtil.commitDBTransaction(); - } catch (ApplicationManagementDAOException e) { ConnectionManagerUtil.rollbackDBTransaction(); String msg = "Failed to delete application: " + uuid; throw new ApplicationManagementException(msg, e); - } finally { ConnectionManagerUtil.closeDBConnection(); } diff --git a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql index d1dcd6a516..40766adc0c 100644 --- a/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql +++ b/features/application-mgt/org.wso2.carbon.device.application.mgt.server.feature/src/main/resources/dbscripts/cdm/application-mgt/mysql.sql @@ -49,19 +49,72 @@ CREATE TABLE IF NOT EXISTS `APPM_APPLICATION_CATEGORY` ( ENGINE = InnoDB COMMENT = 'This table contains the data related to the application category'; +INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION, PUBLISHED) VALUES ('Enterprise', 'Enterprise level +applications which the artifacts need to be provided', 1); +INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION, PUBLISHED) VALUES ('Public', 'Public category in which the +application need to be downloaded from the public application store', 1); -- ----------------------------------------------------- -- Table `APPM_LIFECYCLE_STATE` -- ----------------------------------------------------- -CREATE TABLE IF NOT EXISTS `APPM_LIFECYCLE_STATE` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `NAME` VARCHAR(100) NOT NULL, - `IDENTIFIER` VARCHAR(100) NOT NULL, - `DESCRIPTION` TEXT NULL, - PRIMARY KEY (`ID`), - UNIQUE INDEX `IDENTIFIER_UNIQUE` (`IDENTIFIER` ASC)) - ENGINE = InnoDB; +CREATE TABLE IF NOT EXISTS APPM_LIFECYCLE_STATE ( + ID INT NOT NULL AUTO_INCREMENT UNIQUE, + NAME VARCHAR(100) NOT NULL, + IDENTIFIER VARCHAR(100) NOT NULL, + DESCRIPTION TEXT NULL, + PRIMARY KEY (ID), + UNIQUE INDEX APPM_LIFECYCLE_STATE_IDENTIFIER_UNIQUE (IDENTIFIER ASC)); + +INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) VALUES ('CREATED', 'CREATED', 'Application creation +initial state'); +INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) +VALUES ('IN REVIEW', 'IN REVIEW', 'Application is in in-review state'); +INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) +VALUES ('APPROVED', 'APPROVED', 'State in which Application is approved after reviewing.'); +INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) +VALUES ('REJECTED', 'REJECTED', 'State in which Application is rejected after reviewing.'); +INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) +VALUES ('PUBLISHED', 'PUBLISHED', 'State in which Application is in published state.'); +INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) +VALUES ('UNPUBLISHED', 'UNPUBLISHED', 'State in which Application is in un published state.'); +INSERT INTO APPM_LIFECYCLE_STATE (NAME, IDENTIFIER, DESCRIPTION) +VALUES ('RETIRED', 'RETIRED', 'Retiring an application to indicate end of life state,'); + + +CREATE TABLE IF NOT EXISTS APPM_LIFECYCLE_STATE_TRANSITION +( + ID INT NOT NULL AUTO_INCREMENT UNIQUE, + INITIAL_STATE INT, + NEXT_STATE INT, + PERMISSION VARCHAR(1024), + DESCRIPTION VARCHAR(2048), + PRIMARY KEY (INITIAL_STATE, NEXT_STATE), + FOREIGN KEY (INITIAL_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE, + FOREIGN KEY (NEXT_STATE) REFERENCES APPM_LIFECYCLE_STATE(ID) ON DELETE CASCADE +); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (1, 2, null, 'Submit for review'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (2, 1, null, 'Revoke from review'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (2, 3, '/permission/admin/manage/device-mgt/application/review', 'APPROVE'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (2, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (3, 4, '/permission/admin/manage/device-mgt/application/review', 'REJECT'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (3, 5, null, 'PUBLISH'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (5, 6, null, 'UN PUBLISH'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (6, 5, null, 'PUBLISH'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (4, 1, null, 'Return to CREATE STATE'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (6, 1, null, 'Return to CREATE STATE'); +INSERT INTO APPM_LIFECYCLE_STATE_TRANSITION(INITIAL_STATE, NEXT_STATE, PERMISSION, DESCRIPTION) VALUES + (6, 7, null, 'Retire'); -- ----------------------------------------------------- -- Table `APPM_APPLICATION`