Merge pull request #878 from Megala21/appm_new

Fixing minor issues in PlatformManagement
feature/appm-store/pbac
Megala Uthayakumar 8 years ago committed by GitHub
commit fbef98b2b3

@ -34,6 +34,7 @@ import org.wso2.carbon.device.application.mgt.common.Platform;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
@ -82,6 +83,12 @@ import javax.ws.rs.core.Response;
description = "Update a platform", description = "Update a platform",
key = "perm:platform:update", key = "perm:platform:update",
permissions = {"/device-mgt/platform/update"} permissions = {"/device-mgt/platform/update"}
),
@org.wso2.carbon.apimgt.annotations.api.Scope(
name = "Remove a platform",
description = "Remove a platform",
key = "perm:platform:remove",
permissions = {"/device-mgt/platform/remove"}
) )
} }
) )
@ -251,4 +258,43 @@ public interface PlatformManagementAPI {
String identifier String identifier
); );
@DELETE
@Path("/{identifier}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
value = "Remove Platform",
notes = "This will remove the relevant platform.",
tags = "Platform Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:platform:remove")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully updated the platform"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request parameters passed."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error occurred while getting the platform list.",
response = ErrorResponse.class)
})
Response removePlatform(
@ApiParam(
name = "identifier",
required = true)
@PathParam("identifier")
@Size(max = 45)
String identifier
);
} }

@ -29,6 +29,7 @@ import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementD
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
@ -37,6 +38,9 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
/**
* Implementation of PlatformManagement APIs.
*/
@Path("/platforms") @Path("/platforms")
public class PlatformManagementAPIImpl implements PlatformManagementAPI { public class PlatformManagementAPIImpl implements PlatformManagementAPI {
@ -49,13 +53,13 @@ public class PlatformManagementAPIImpl implements PlatformManagementAPI {
@GET @GET
@Override @Override
public Response getPlatforms(@QueryParam("status") String status) { public Response getPlatforms(@QueryParam("status") String status) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("API request received for getting the platforms with the status " + status); log.debug("API request received for getting the platforms with the status " + status);
} }
try { try {
List<Platform> platforms = APIUtil.getPlatformManager().getPlatforms(tenantDomain); List<Platform> platforms = APIUtil.getPlatformManager().getPlatforms(tenantID);
List<Platform> results; List<Platform> results;
if (status != null) { if (status != null) {
if (status.contentEquals(ALL_STATUS)) { if (status.contentEquals(ALL_STATUS)) {
@ -85,7 +89,7 @@ public class PlatformManagementAPIImpl implements PlatformManagementAPI {
} }
return Response.status(Response.Status.OK).entity(results).build(); return Response.status(Response.Status.OK).entity(results).build();
} catch (PlatformManagementException e) { } catch (PlatformManagementException e) {
log.error("Error while getting the platforms for tenant - " + tenantDomain, e); log.error("Error while getting the platforms for tenant - " + tenantID, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }
@ -94,13 +98,17 @@ public class PlatformManagementAPIImpl implements PlatformManagementAPI {
@Override @Override
@Path("/{identifier}") @Path("/{identifier}")
public Response getPlatform(@PathParam("identifier") String id) { public Response getPlatform(@PathParam("identifier") String id) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try { try {
Platform platform = APIUtil.getPlatformManager().getPlatform(tenantDomain, id); Platform platform = APIUtil.getPlatformManager().getPlatform(tenantId, id);
return Response.status(Response.Status.OK).entity(platform).build(); return Response.status(Response.Status.OK).entity(platform).build();
} catch (PlatformManagementDAOException e) { } catch (PlatformManagementDAOException e) {
log.error("Error while trying the get the platform with the identifier : " + id + " for the tenant :"
+ tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} catch (PlatformManagementException e) { } catch (PlatformManagementException e) {
log.error("Error while trying the get the platform with the identifier : " + id + " for the tenant :"
+ tenantId, e);
return APIUtil.getResponse(e, Response.Status.NOT_FOUND); return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
} }
} }
@ -108,14 +116,15 @@ public class PlatformManagementAPIImpl implements PlatformManagementAPI {
@POST @POST
@Override @Override
public Response addPlatform(Platform platform) { public Response addPlatform(Platform platform) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try { try {
if (platform != null) { if (platform != null) {
if (platform.validate()) { if (platform.validate()) {
APIUtil.getPlatformManager().register(tenantDomain, platform); APIUtil.getPlatformManager().register(tenantId, platform);
return Response.status(Response.Status.CREATED).build(); return Response.status(Response.Status.CREATED).build();
} else { } else {
return APIUtil.getResponse("Invxalid payload! Platform ID and names are mandatory fields!", return APIUtil
.getResponse("Invalid payload! Platform 'identifier' and 'name' are mandatory fields!",
Response.Status.BAD_REQUEST); Response.Status.BAD_REQUEST);
} }
} else { } else {
@ -123,6 +132,8 @@ public class PlatformManagementAPIImpl implements PlatformManagementAPI {
Response.Status.BAD_REQUEST); Response.Status.BAD_REQUEST);
} }
} catch (PlatformManagementException e) { } catch (PlatformManagementException e) {
log.error("Platform Management Exception while trying to add the platform with identifier : " + platform
.getIdentifier() + " for the tenant : " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }
@ -131,12 +142,27 @@ public class PlatformManagementAPIImpl implements PlatformManagementAPI {
@Path("/{identifier}") @Path("/{identifier}")
@Override @Override
public Response updatePlatform(Platform platform, @PathParam("identifier") @Size(max = 45) String id) { public Response updatePlatform(Platform platform, @PathParam("identifier") @Size(max = 45) String id) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try { try {
APIUtil.getPlatformManager().update(tenantDomain, id, platform); APIUtil.getPlatformManager().update(tenantId, id, platform);
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} catch (PlatformManagementException e) { } catch (PlatformManagementException e) {
log.error("Error while updating the platform - " + id + " for tenant domain - " + tenantDomain, e); log.error("Error while updating the platform - " + id + " for tenant domain - " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
}
}
@DELETE
@Path("/{identifier}")
@Override
public Response removePlatform(@PathParam("identifier") @Size(max = 45) String id) {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
try {
APIUtil.getPlatformManager().unregister(tenantId, id, false);
return Response.status(Response.Status.OK).build();
} catch (PlatformManagementException e) {
log.error("Platform Management Exception while trying to un-register the platform with the identifier : "
+ id + " for the tenant : " + tenantId, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
} }
} }

@ -63,6 +63,10 @@
<url>/application-mgt/platforms/*</url> <url>/application-mgt/platforms/*</url>
<method>PUT</method> <method>PUT</method>
</Permission> </Permission>
<Permission>
<name>Remove Platform</name>
<path>/device-mgt/platform/remove</path>
<url>/application-mgt/platforms/*</url>
<method>DELETE</method>
</Permission>
</PermissionConfiguration> </PermissionConfiguration>

@ -26,6 +26,7 @@ http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="applicationMgtService" address="/"> <jaxrs:server id="applicationMgtService" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<ref bean="applicationMgtServiceBean"/> <ref bean="applicationMgtServiceBean"/>
<ref bean="platformMgtServiceBean"/>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>
<ref bean="jsonProvider"/> <ref bean="jsonProvider"/>
@ -33,7 +34,7 @@ http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
</jaxrs:server> </jaxrs:server>
<bean id="applicationMgtServiceBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.ApplicationManagementAPIImpl"/> <bean id="applicationMgtServiceBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.ApplicationManagementAPIImpl"/>
<!--<bean id="platformManagementAPIBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.PlatformManagementAPIImpl" />--> <bean id="platformMgtServiceBean" class="org.wso2.carbon.device.application.mgt.api.services.impl.PlatformManagementAPIImpl" />
<bean id="jsonProvider" class="org.wso2.carbon.device.application.mgt.api.JSONMessageHandler"/> <bean id="jsonProvider" class="org.wso2.carbon.device.application.mgt.api.JSONMessageHandler"/>
</beans> </beans>

@ -37,7 +37,7 @@
</session-config> </session-config>
<context-param> <context-param>
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>false</param-value> <param-value>true</param-value>
</context-param> </context-param>
<!--publish to apim--> <!--publish to apim-->

@ -29,24 +29,24 @@ import java.util.List;
*/ */
public interface PlatformManager { public interface PlatformManager {
void initialize(String tenantDomain) throws PlatformManagementException; void initialize(int tenantId) throws PlatformManagementException;
List<Platform> getPlatforms(String tenantDomain) throws PlatformManagementException; List<Platform> getPlatforms(int tenantId) throws PlatformManagementException;
Platform getPlatform(String tenantDomain, String platformIdentifier) throws PlatformManagementException; Platform getPlatform(int tenantId, String platformIdentifier) throws PlatformManagementException;
void register(String tenantDomain, Platform platform) throws PlatformManagementException; void register(int tenantId, Platform platform) throws PlatformManagementException;
void update(String tenantDomain, String oldPlatformIdentifier, Platform platform) void update(int tenantId, String oldPlatformIdentifier, Platform platform)
throws PlatformManagementException; throws PlatformManagementException;
void unregister(String tenantDomain, String platformIdentifier, boolean isFileBased) void unregister(int tenantId, String platformIdentifier, boolean isFileBased)
throws PlatformManagementException; throws PlatformManagementException;
void addMapping(String tenantDomain, List<String> platformIdentifiers) throws PlatformManagementException; void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementException;
void addMapping(String tenantDomain, String platformIdentifier) throws PlatformManagementException; void addMapping(int tenantId, String platformIdentifier) throws PlatformManagementException;
void removeMapping(String tenantDomain, String platformIdentifier) throws PlatformManagementException; void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementException;
} }

@ -74,8 +74,7 @@
org.apache.axis2.*, org.apache.axis2.*,
org.wso2.carbon.user.core.*, org.wso2.carbon.user.core.*,
org.wso2.carbon.user.api.*, org.wso2.carbon.user.api.*,
org.wso2.carbon.ndatasource.core, org.wso2.carbon.ndatasource.core
org.apache.axiom.om.*; version="${axiom.osgi.version.range}"
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.device.application.mgt.core.internal.*, !org.wso2.carbon.device.application.mgt.core.internal.*,

@ -22,16 +22,11 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException; import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurationException;
import org.wso2.carbon.device.application.mgt.core.deployer.Platform;
import org.wso2.carbon.device.application.mgt.core.deployer.Property;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.Constants; import org.wso2.carbon.device.application.mgt.core.util.Constants;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import java.io.File; import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ConfigurationManager { public class ConfigurationManager {

@ -19,30 +19,31 @@
package org.wso2.carbon.device.application.mgt.core.dao; package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.Platform; import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
import java.util.List; import java.util.List;
/**
* PlatformDAO defines set of DAO operations that are needed for Platform Management.
*/
public interface PlatformDAO { public interface PlatformDAO {
int register(String tenantDomain, Platform platform) throws PlatformManagementDAOException; int register(int tenantId, Platform platform) throws PlatformManagementDAOException;
void update(String tenantDomain, String oldPlatformIdentifier, Platform platform) throws PlatformManagementDAOException; void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws PlatformManagementDAOException;
void unregister(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException; void unregister(int tenantId, String platformIdentifier, boolean isFileBased) throws PlatformManagementDAOException;
void addMapping(String tenantDomain, List<String> platformIdentifiers) throws PlatformManagementDAOException; void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementDAOException;
void removeMapping(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException; void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementDAOException;
void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException; void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException;
List<Platform> getPlatforms(String tenantDomain) throws PlatformManagementDAOException; List<Platform> getPlatforms(int tenantId) throws PlatformManagementDAOException;
Platform getPlatform(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException; Platform getPlatform(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException;
Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException; Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException;
} }

@ -18,11 +18,8 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao.common; package org.wso2.carbon.device.application.mgt.core.dao.common;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.exception.UnsupportedDatabaseEngineException; import org.wso2.carbon.device.application.mgt.common.exception.UnsupportedDatabaseEngineException;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager; 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.ApplicationDAO;
@ -33,18 +30,11 @@ import org.wso2.carbon.device.application.mgt.core.dao.impl.application.MySQLApp
import org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate.GenericLifecycleStateImpl; 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.GenericPlatformDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ApplicationMgtDatabaseCreator; import org.wso2.carbon.device.application.mgt.core.util.ApplicationMgtDatabaseCreator;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.ndatasource.core.CarbonDataSource; import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator; import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import javax.sql.DataSource;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import java.sql.SQLException; import java.sql.SQLException;
/** /**
@ -63,7 +53,7 @@ public class DAOFactory {
databaseEngine = ConnectionManagerUtil.getDatabaseType(); databaseEngine = ConnectionManagerUtil.getDatabaseType();
} }
public static ApplicationDAO getApplicationDAO(){ public static ApplicationDAO getApplicationDAO() {
if (databaseEngine != null) { if (databaseEngine != null) {
switch (databaseEngine) { switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2: case Constants.DataBaseTypes.DB_TYPE_H2:
@ -77,7 +67,7 @@ public class DAOFactory {
throw new IllegalStateException("Database engine has not initialized properly."); throw new IllegalStateException("Database engine has not initialized properly.");
} }
public static PlatformDAO getPlatformDAO(){ public static PlatformDAO getPlatformDAO() {
if (databaseEngine != null) { if (databaseEngine != null) {
switch (databaseEngine) { switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2: case Constants.DataBaseTypes.DB_TYPE_H2:
@ -90,7 +80,7 @@ public class DAOFactory {
throw new IllegalStateException("Database engine has not initialized properly."); throw new IllegalStateException("Database engine has not initialized properly.");
} }
public static LifecycleStateDAO getLifecycleStateDAO(){ public static LifecycleStateDAO getLifecycleStateDAO() {
if (databaseEngine != null) { if (databaseEngine != null) {
switch (databaseEngine) { switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2: case Constants.DataBaseTypes.DB_TYPE_H2:
@ -105,29 +95,20 @@ public class DAOFactory {
/** /**
* This method initializes the databases by creating the database. * This method initializes the databases by creating the database.
*
* @throws ApplicationManagementDAOException Exceptions thrown during the creation of the tables * @throws ApplicationManagementDAOException Exceptions thrown during the creation of the tables
*/ */
public static void initDatabases() throws ApplicationManagementDAOException { public static void initDatabases() throws ApplicationManagementDAOException {
CarbonDataSource carbonDataSource = null; String dataSourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName();
DataSource dataSource = null; String validationQuery = "SELECT * from APPM_PLATFORM";
String dataSourceName = ConfigurationManager.getInstance()
.getConfiguration().getDatasourceName();
DataSourceService service = DataHolder.getInstance().getDataSourceService();
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
try { try {
carbonDataSource = service.getDataSource(dataSourceName);
dataSource = (DataSource) carbonDataSource.getDSObject();
if (System.getProperty("setup") == null) { if (System.getProperty("setup") == null) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Application Management Database schema initialization check was skipped since " log.debug("Application Management Database schema initialization check was skipped since "
+ "\'setup\' variable was not given during startup"); + "\'setup\' variable was not given during startup");
} }
} else { } else {
DatabaseCreator databaseCreator = new ApplicationMgtDatabaseCreator(dataSource); DatabaseCreator databaseCreator = new ApplicationMgtDatabaseCreator(dataSourceName);
String validationQuery = getValidationQuery(
(String) carbonDataSource.getDSMInfo().getDefinition().getDsXMLConfiguration());
if (!databaseCreator.isDatabaseStructureCreated(validationQuery)) { if (!databaseCreator.isDatabaseStructureCreated(validationQuery)) {
databaseCreator.createRegistryDatabase(); databaseCreator.createRegistryDatabase();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -136,34 +117,11 @@ public class DAOFactory {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error while creating application-mgt database during the " throw new ApplicationManagementDAOException(
+ "startup ", e); "Error while creating application-mgt database during the " + "startup ", e);
} catch (Exception e) { } catch (Exception e) {
throw new ApplicationManagementDAOException("Error while creating application-mgt database in the " throw new ApplicationManagementDAOException(
+ "startup ", e); "Error while creating application-mgt database in the " + "startup ", e);
} }
} }
/**
* To get the the validation query to make sure whether the tables exist already in application management databse
* @param dsXMLConfiguration Datasource XML configurations
* @return Validation query
*/
private static String getValidationQuery(String dsXMLConfiguration) {
String DEFAULT_VALIDATION_QUERY = "SELECT 1";
try {
OMElement omElement = AXIOMUtil.stringToOM(dsXMLConfiguration);
return omElement.getFirstChildWithName(new QName("validationQuery")).getText();
} catch (XMLStreamException e) {
log.error("Error while reading the validation query from the data source configuration of "
+ "application-mgt (application-mgt-datasources.xml", e);
if (log.isDebugEnabled()) {
log.debug("Due to fail to read the validation query from application-mgt datasources, using the "
+ "default validation query : " + DEFAULT_VALIDATION_QUERY);
}
return DEFAULT_VALIDATION_QUERY;
}
}
} }

@ -20,17 +20,19 @@ package org.wso2.carbon.device.application.mgt.core.dao.common;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.Category; 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.core.util.JSONUtil; import org.wso2.carbon.device.application.mgt.core.util.JSONUtil;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Util { public class Util {
@ -93,6 +95,4 @@ public class Util {
} }
} }
} }
} }

@ -24,6 +24,7 @@ import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException; import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
import org.wso2.carbon.device.application.mgt.core.dao.PlatformDAO; import org.wso2.carbon.device.application.mgt.core.dao.PlatformDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
@ -36,22 +37,25 @@ import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* Generic Implementation for handling Platform management related database operations.
*/
public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformDAO { public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformDAO {
private static Log log = LogFactory.getLog(GenericPlatformDAOImpl.class); private static Log log = LogFactory.getLog(GenericPlatformDAOImpl.class);
@Override @Override
public int register(String tenantDomain, Platform platform) throws PlatformManagementDAOException { public int register(int tenantId, Platform platform) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
try { try {
ConnectionManagerUtil.beginTransaction(); int platformId = getPlatformId(tenantId, platform.getIdentifier());
int platformId = getPlatformId(tenantDomain, platform.getIdentifier());
if (platformId == -1) { if (platformId == -1) {
Connection connection = ConnectionManagerUtil.getConnection(); Connection connection = this.getConnection();
if (!platform.isFileBased()) { if (!platform.isFileBased()) {
String insertToPlatform = "INSERT INTO APPM_PLATFORM (IDENTIFIER, TENANT_DOMAIN, NAME, FILE_BASED, DESCRIPTION, IS_SHARED, ICON_NAME)" + String insertToPlatform = "INSERT INTO APPM_PLATFORM (IDENTIFIER, TENANT_ID, NAME, FILE_BASED, "
" VALUES (?, ?, ?, ?, ?, ?, ?)"; + "DESCRIPTION, IS_SHARED, ICON_NAME)" + " VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertToPlatform); preparedStatement = connection.prepareStatement(insertToPlatform);
preparedStatement.setString(1, platform.getIdentifier()); preparedStatement.setString(1, platform.getIdentifier());
preparedStatement.setString(2, tenantDomain); preparedStatement.setInt(2, tenantId);
preparedStatement.setString(3, platform.getName()); preparedStatement.setString(3, platform.getName());
preparedStatement.setBoolean(4, false); preparedStatement.setBoolean(4, false);
preparedStatement.setString(5, platform.getDescription()); preparedStatement.setString(5, platform.getDescription());
@ -59,9 +63,12 @@ public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformD
preparedStatement.setString(7, platform.getIconName()); preparedStatement.setString(7, platform.getIconName());
preparedStatement.execute(); preparedStatement.execute();
platformId = getPlatformId(tenantDomain, platform.getIdentifier()); platformId = getPlatformId(tenantId, platform.getIdentifier());
String insertPlatformProps = "INSERT INTO APPM_PLATFORM_PROPERTIES (PLATFORM_ID, PROP_NAME, OPTIONAL, DEFAULT_VALUE) VALUES " + String insertPlatformProps =
"( ? , ?, ? , ?)"; "INSERT INTO APPM_PLATFORM_PROPERTIES (PLATFORM_ID, PROP_NAME, OPTIONAL, "
+ "DEFAULT_VALUE) VALUES ( ? , ?, ? , ?)";
if (platform.getProperties() != null) {
for (Platform.Property property : platform.getProperties()) { for (Platform.Property property : platform.getProperties()) {
preparedStatement = connection.prepareStatement(insertPlatformProps); preparedStatement = connection.prepareStatement(insertPlatformProps);
preparedStatement.setInt(1, platformId); preparedStatement.setInt(1, platformId);
@ -70,74 +77,91 @@ public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformD
preparedStatement.setString(4, property.getDefaultValue()); preparedStatement.setString(4, property.getDefaultValue());
preparedStatement.execute(); preparedStatement.execute();
} }
}
} else { } else {
String insertToPlatform = "INSERT INTO APPM_PLATFORM (IDENTIFIER, TENANT_DOMAIN, FILE_BASED)" + String insertToPlatform =
" VALUES (?, ?, ?)"; "INSERT INTO APPM_PLATFORM (IDENTIFIER, TENANT_ID, FILE_BASED)" + " VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertToPlatform); preparedStatement = connection.prepareStatement(insertToPlatform);
preparedStatement.setString(1, platform.getIdentifier()); preparedStatement.setString(1, platform.getIdentifier());
preparedStatement.setString(2, tenantDomain); preparedStatement.setInt(2, tenantId);
preparedStatement.setBoolean(3, true); preparedStatement.setBoolean(3, true);
preparedStatement.execute(); preparedStatement.execute();
} }
if (platformId == -1) { if (platformId == -1) {
platformId = getPlatformId(tenantDomain, platform.getIdentifier()); platformId = getPlatformId(tenantId, platform.getIdentifier());
} }
ConnectionManagerUtil.commitTransaction();
return platformId; return platformId;
} else { } else {
if (!platform.isFileBased()) { if (!platform.isFileBased()) {
ConnectionManagerUtil.rollbackTransaction(); throw new PlatformManagementDAOException(
throw new PlatformManagementDAOException("Platform - " + platform.getIdentifier() "Platform - " + platform.getIdentifier() + " is already registered for tenant - "
+ " is already registered for tenant - " + tenantDomain); + tenantId);
} else { } else {
return platformId; return platformId;
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException("Error while executing the SQL query. ", e); throw new PlatformManagementDAOException("Error while executing the SQL query. ", e);
} catch (PlatformManagementDAOException ex) {
ConnectionManagerUtil.rollbackTransaction();
throw ex;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction(); throw new PlatformManagementDAOException(
throw new PlatformManagementDAOException("Unable to obtain the connection while trying to register the platform - " "Unable to obtain the connection while trying to register the platform - " + platform
+ platform.getIdentifier() + " for tenant - " + tenantDomain, e); .getIdentifier() + " for tenant - " + tenantId, e);
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException("Error occurred while performing the transaction on the database " +
"for adding the platform - " + platform.getIdentifier() + " , tenant domain - " + tenantDomain);
} finally { } finally {
ConnectionManagerUtil.closeConnection(); Util.cleanupResources(preparedStatement, null);
} }
} }
@Override @Override
public void update(String tenantDomain, String oldPlatformIdentifier, Platform platform) throws PlatformManagementDAOException { public void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws
PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
try { try {
ConnectionManagerUtil.beginTransaction(); int platformId = getPlatformId(tenantId, oldPlatformIdentifier);
int platformId = getPlatformId(tenantDomain, oldPlatformIdentifier); boolean isIdentifierNull = platform.getIdentifier() == null;
boolean isNameNull = platform.getName() == null;
if (platformId != -1) { if (platformId != -1) {
Connection connection = ConnectionManagerUtil.getConnection(); Connection connection = this.getConnection();
if (!platform.isFileBased()) { if (!platform.isFileBased()) {
String insertToPlatform = "UPDATE APPM_PLATFORM SET IDENTIFIER = ?, NAME =?, DESCRIPTION=?, " + String insertToPlatform = "UPDATE APPM_PLATFORM SET DESCRIPTION=?, IS_SHARED=?, ICON_NAME=?";
"IS_SHARED=?, ICON_NAME=? WHERE ID = ?"; if (!isIdentifierNull) {
PreparedStatement preparedStatement = connection.prepareStatement(insertToPlatform); insertToPlatform += ",IDENTIFIER = ? ";
preparedStatement.setString(1, platform.getIdentifier()); }
preparedStatement.setString(2, platform.getName()); if (!isNameNull) {
preparedStatement.setString(3, platform.getDescription()); insertToPlatform += ", NAME =?";
preparedStatement.setBoolean(4, platform.isShared()); }
preparedStatement.setString(5, platform.getIconName()); insertToPlatform += " WHERE ID = ?";
preparedStatement = connection.prepareStatement(insertToPlatform);
preparedStatement.setString(1, platform.getDescription());
preparedStatement.setBoolean(2, platform.isShared());
preparedStatement.setString(3, platform.getIconName());
if (!isIdentifierNull && !isNameNull) {
preparedStatement.setString(4, platform.getIdentifier());
preparedStatement.setString(5, platform.getName());
preparedStatement.setInt(6, platformId);
} else if (isIdentifierNull && !isNameNull) {
preparedStatement.setString(4, platform.getName());
preparedStatement.setInt(5, platformId);
} else if (!isIdentifierNull) {
preparedStatement.setString(4, platform.getIdentifier());
preparedStatement.setInt(5, platformId);
} else {
preparedStatement.setInt(4, platformId);
}
preparedStatement.execute(); preparedStatement.execute();
platformId = getPlatformId(tenantDomain, platform.getIdentifier()); platformId = getPlatformId(tenantId, platform.getIdentifier());
String deletePlatformProps = "DELETE FROM APPM_PLATFORM_PROPERTIES WHERE PLATFORM_ID=?"; String deletePlatformProps = "DELETE FROM APPM_PLATFORM_PROPERTIES WHERE PLATFORM_ID=?";
preparedStatement = connection.prepareStatement(deletePlatformProps); preparedStatement = connection.prepareStatement(deletePlatformProps);
preparedStatement.setInt(1, platformId); preparedStatement.setInt(1, platformId);
preparedStatement.execute(); preparedStatement.execute();
String insertPlatformProps = "INSERT INTO APPM_PLATFORM_PROPERTIES (PLATFORM_ID, PROP_NAME, OPTIONAL," + String insertPlatformProps =
" DEFAULT_VALUE) VALUES ( ? , ?, ? , ?)"; "INSERT INTO APPM_PLATFORM_PROPERTIES (PLATFORM_ID, PROP_NAME, OPTIONAL,"
+ " DEFAULT_VALUE) VALUES ( ? , ?, ? , ?)";
if (platform.getProperties() != null) {
for (Platform.Property property : platform.getProperties()) { for (Platform.Property property : platform.getProperties()) {
preparedStatement = connection.prepareStatement(insertPlatformProps); preparedStatement = connection.prepareStatement(insertPlatformProps);
preparedStatement.setInt(1, platformId); preparedStatement.setInt(1, platformId);
@ -146,45 +170,41 @@ public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformD
preparedStatement.setString(4, property.getDefaultValue()); preparedStatement.setString(4, property.getDefaultValue());
preparedStatement.execute(); preparedStatement.execute();
} }
}
} else { } else {
String insertToPlatform = "UPDATE APPM_PLATFORM SET IDENTIFIER = ? WHERE ID = ?"; String insertToPlatform = "UPDATE APPM_PLATFORM SET IDENTIFIER = ? WHERE ID = ?";
PreparedStatement preparedStatement = connection.prepareStatement(insertToPlatform); preparedStatement = connection.prepareStatement(insertToPlatform);
preparedStatement.setInt(1, platformId); preparedStatement.setInt(1, platformId);
preparedStatement.execute(); preparedStatement.execute();
} }
ConnectionManagerUtil.commitTransaction();
} else { } else {
throw new PlatformManagementDAOException("Cannot find any platform that was registered with identifier - " throw new PlatformManagementDAOException(
+ platform.getIdentifier() + " for tenant - " + tenantDomain); "Cannot find any platform that was registered with identifier - " + platform.getIdentifier()
+ " for tenant - " + tenantId);
} }
} catch (SQLException e) { } catch (SQLException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException("Error while executing the SQL query. ", e); throw new PlatformManagementDAOException("Error while executing the SQL query. ", e);
} catch (PlatformManagementDAOException ex) {
ConnectionManagerUtil.rollbackTransaction();
throw ex;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction(); throw new PlatformManagementDAOException(
throw new PlatformManagementDAOException("Unable to obtain the connection while trying to register the platform - " "Unable to obtain the connection while trying to register the platform - " + platform
+ platform.getIdentifier() + " for tenant - " + tenantDomain, e); .getIdentifier() + " for tenant - " + tenantId, e);
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException("Error occurred while performing the transaction on the database " +
"for adding the platform - " + platform.getIdentifier() + " , tenant domain - " + tenantDomain);
} finally { } finally {
ConnectionManagerUtil.closeConnection(); Util.cleanupResources(preparedStatement, null);
} }
} }
private int getPlatformId(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException { private int getPlatformId(int tenantId, String platformIdentifier) throws PlatformManagementDAOException {
String query = "SELECT ID FROM APPM_PLATFORM WHERE (TENANT_DOMAIN=? AND IDENTIFIER=?) OR (IS_SHARED = TRUE AND IDENTIFIER=?)"; PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = TRUE AND "
+ "IDENTIFIER=?)";
try { try {
Connection connection = ConnectionManagerUtil.getConnection(); Connection connection = this.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, tenantDomain); preparedStatement.setInt(1, tenantId);
preparedStatement.setString(2, platformIdentifier); preparedStatement.setString(2, platformIdentifier);
preparedStatement.setString(3, platformIdentifier); preparedStatement.setString(3, platformIdentifier);
ResultSet resultSet = preparedStatement.executeQuery(); resultSet = preparedStatement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
return resultSet.getInt("ID"); return resultSet.getInt("ID");
} }
@ -193,175 +213,180 @@ public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformD
throw new PlatformManagementDAOException("Error when trying to obtaining the database connection.", e); throw new PlatformManagementDAOException("Error when trying to obtaining the database connection.", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformManagementDAOException("Error in executing the query - " + query, e); throw new PlatformManagementDAOException("Error in executing the query - " + query, e);
} finally {
Util.cleanupResources(preparedStatement, resultSet);
} }
} }
@Override @Override
public void unregister(String tenantDomain, String platformIdenfier) throws PlatformManagementDAOException { public void unregister(int tenantId, String platformIdenfier, boolean isFileBased) throws
PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
try { try {
ConnectionManagerUtil.beginTransaction(); Platform platform = getPlatform(tenantId, platformIdenfier);
int platformId = getPlatformId(tenantDomain, platformIdenfier);
if (platformId != -1) { if (platform != null) {
Connection connection = ConnectionManagerUtil.getConnection(); if (isFileBased == platform.isFileBased()) {
Connection connection = this.getConnection();
String deletePlatform = "DELETE FROM APPM_PLATFORM WHERE ID = ?"; String deletePlatform = "DELETE FROM APPM_PLATFORM WHERE ID = ?";
PreparedStatement preparedStatement = connection.prepareStatement(deletePlatform); preparedStatement = connection.prepareStatement(deletePlatform);
preparedStatement.setInt(1, platformId); preparedStatement.setInt(1, platform.getId());
preparedStatement.execute(); preparedStatement.execute();
ConnectionManagerUtil.commitTransaction();
} else { } else {
throw new PlatformManagementDAOException("Platform identifier - " + platformIdenfier if (isFileBased) {
+ " is already unregistered registered for tenant - " + tenantDomain); throw new PlatformManagementDAOException("Platform with identifier - " + platformIdenfier
+ " is not a file based platform. Try to remove that using PlatformManagement APIs");
} else {
throw new PlatformManagementDAOException("Platform with identifier - " + platformIdenfier
+ " is a file based platform. Try to remove that by un-deploying the relevant file.");
}
}
} else {
throw new PlatformManagementDAOException(
"Platform identifier - " + platformIdenfier + " is not registered for tenant - " + tenantId);
} }
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException("Unable to start the transaction while trying to register the platform - "
+ platformIdenfier + " for tenant - " + tenantDomain, e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction(); throw new PlatformManagementDAOException(
throw new PlatformManagementDAOException("Unable to obtain the connection while trying to register the platform - " "Unable to obtain the connection while trying to register the platform - " + platformIdenfier
+ platformIdenfier + " for tenant - " + tenantDomain, e); + " for tenant - " + tenantId, e);
} catch (SQLException e) { } catch (SQLException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException("Error while executing the SQL query. ", e); throw new PlatformManagementDAOException("Error while executing the SQL query. ", e);
} catch (PlatformManagementDAOException ex) {
ConnectionManagerUtil.rollbackTransaction();
throw ex;
} finally { } finally {
ConnectionManagerUtil.closeConnection(); Util.cleanupResources(preparedStatement, null);
} }
} }
public void addMapping(String tenantDomain, List<String> platformIdentifiers) throws PlatformManagementDAOException { public void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementDAOException {
String insertMapping = "INSERT INTO APPM_PLATFORM_TENANT_MAPPING(TENANT_DOMAIN, PLATFORM_ID) VALUES (?, ?)"; String insertMapping = "INSERT INTO APPM_PLATFORM_TENANT_MAPPING(TENANT_ID, PLATFORM_ID) VALUES (?, ?)";
PreparedStatement preparedStatement = null;
try { try {
ConnectionManagerUtil.beginTransaction();
for (String platformIdentifier : platformIdentifiers) { for (String platformIdentifier : platformIdentifiers) {
if (getTenantPlatformMapping(tenantDomain, platformIdentifier) != -1) { if (getTenantPlatformMapping(tenantId, platformIdentifier) == -1) {
int platformId = getPlatformId(tenantDomain, platformIdentifier); int platformId = getPlatformId(tenantId, platformIdentifier);
Connection connection = ConnectionManagerUtil.getConnection(); Connection connection = this.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(insertMapping); preparedStatement = connection.prepareStatement(insertMapping);
preparedStatement.setString(1, tenantDomain); preparedStatement.setInt(1, tenantId);
preparedStatement.setInt(2, platformId); preparedStatement.setInt(2, platformId);
preparedStatement.execute(); preparedStatement.execute();
} else { } else {
throw new PlatformManagementDAOException("Platform identifier - " + platformIdentifier + " is already assigned to tenant domain - " + tenantDomain); log.error("Platform identifier - " + platformIdentifier + " is already assigned to tenant domain"
+ " - " + tenantId);
} }
} }
ConnectionManagerUtil.commitTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException("Error occured while trying to add the mapping of platform - "
+ platformIdentifiers.toString() + " for tenant - " + tenantDomain, e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction(); throw new PlatformManagementDAOException("Error occurred when getting the connection for the database. ",
throw new PlatformManagementDAOException("Error occurred when getting the connection for the database. ", e); e);
} catch (SQLException e) { } catch (SQLException e) {
ConnectionManagerUtil.rollbackTransaction(); throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + insertMapping,
throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + insertMapping, e); e);
} catch (PlatformManagementDAOException ex) {
ConnectionManagerUtil.rollbackTransaction();
throw ex;
} finally { } finally {
ConnectionManagerUtil.closeConnection(); Util.cleanupResources(preparedStatement, null);
} }
} }
private int getTenantPlatformMapping(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException { private int getTenantPlatformMapping(int tenantId, String platformIdentifier) throws
String getMapping = "SELECT MAPPING.ID as ID FROM (SELECT ID FROM APPM_PLATFORM_TENANT_MAPPING WHERE TENANT_DOMAIN=?) MAPPING JOIN " + PlatformManagementDAOException {
"(SELECT ID FROM APPM_PLATFORM WHERE APPM_PLATFORM.IDENTIFIER=?) PLATFORM ON MAPPING.PLATFORM_ID=PLATFORM.ID"; PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String getMapping = "SELECT MAPPING.ID as ID FROM (SELECT ID, PLATFORM_ID FROM APPM_PLATFORM_TENANT_MAPPING "
+ "WHERE TENANT_ID=?) MAPPING JOIN (SELECT ID FROM APPM_PLATFORM WHERE APPM_PLATFORM.IDENTIFIER=?) "
+ "PLATFORM ON MAPPING.PLATFORM_ID=PLATFORM.ID";
try { try {
Connection connection = ConnectionManagerUtil.getConnection(); Connection connection = this.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(getMapping); preparedStatement = connection.prepareStatement(getMapping);
preparedStatement.setString(1, tenantDomain); preparedStatement.setInt(1, tenantId);
preparedStatement.setString(2, platformIdentifier); preparedStatement.setString(2, platformIdentifier);
ResultSet resultSet = preparedStatement.executeQuery(); resultSet = preparedStatement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
return resultSet.getInt("ID"); return resultSet.getInt("ID");
} }
return -1; return -1;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Error occured while obtaining the connection to get the existing " + throw new PlatformManagementDAOException(
"Tenant - Platform Mapping.", e); "Error occurred while obtaining the connection to get the existing " + "Tenant - Platform Mapping.",
e);
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + getMapping, e); throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + getMapping, e);
} finally {
Util.cleanupResources(preparedStatement, resultSet);
} }
} }
public void removeMapping(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException { @Override
public void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementDAOException {
String deleteMapping = "DELETE FROM APPM_PLATFORM_TENANT_MAPPING WHERE ID = ?"; String deleteMapping = "DELETE FROM APPM_PLATFORM_TENANT_MAPPING WHERE ID = ?";
PreparedStatement preparedStatement = null;
try { try {
ConnectionManagerUtil.beginTransaction(); int mappingId = getTenantPlatformMapping(tenantId, platformIdentifier);
int mappingId = getTenantPlatformMapping(tenantDomain, platformIdentifier);
if (mappingId != -1) { if (mappingId != -1) {
Connection connection = ConnectionManagerUtil.getConnection(); Connection connection = this.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(deleteMapping); preparedStatement = connection.prepareStatement(deleteMapping);
preparedStatement.setInt(1, mappingId); preparedStatement.setInt(1, mappingId);
preparedStatement.execute(); preparedStatement.execute();
ConnectionManagerUtil.commitTransaction();
} else { } else {
throw new PlatformManagementDAOException("Platform - " + platformIdentifier throw new PlatformManagementDAOException(
+ " is already unassigned for tenant - " + tenantDomain); "Platform - " + platformIdentifier + " is already unassigned for tenant - " + tenantId);
} }
} catch (TransactionManagementException | DBConnectionException e) { } catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction(); throw new PlatformManagementDAOException(
throw new PlatformManagementDAOException("Error occurred while unassigning the platform - " + platformIdentifier "Error occurred while unassigning the platform - " + platformIdentifier + " for tenant - "
+ " for tenant - " + tenantDomain); + tenantId);
} catch (SQLException e) { } catch (SQLException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException("Error occurred while executing the query - " + deleteMapping); throw new PlatformManagementDAOException("Error occurred while executing the query - " + deleteMapping);
} catch (PlatformManagementDAOException ex) {
ConnectionManagerUtil.rollbackTransaction();
throw ex;
} finally { } finally {
ConnectionManagerUtil.closeConnection(); Util.cleanupResources(preparedStatement, null);
} }
} }
@Override @Override
public void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException { public void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException {
int platformId = getPlatformId(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, platformIdentifier); PreparedStatement preparedStatement = null;
String getMapping = "DELETE FROM APPM_PLATFORM_TENANT_MAPPING WHERE TENANT_DOMAIN != ? AND PLATFORM_ID=?"; int platformId = getPlatformId(MultitenantConstants.SUPER_TENANT_ID, platformIdentifier);
String getMapping = "DELETE FROM APPM_PLATFORM_TENANT_MAPPING WHERE TENANT_ID != ? AND PLATFORM_ID=?";
try { try {
ConnectionManagerUtil.openConnection(); Connection connection = this.getConnection();
Connection connection = ConnectionManagerUtil.getConnection(); preparedStatement = connection.prepareStatement(getMapping);
PreparedStatement preparedStatement = connection.prepareStatement(getMapping); preparedStatement.setInt(1, MultitenantConstants.SUPER_TENANT_ID);
preparedStatement.setString(1, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
preparedStatement.setInt(2, platformId); preparedStatement.setInt(2, platformId);
preparedStatement.execute(); preparedStatement.execute();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Error occured while obtaining the connection to get the existing " + throw new PlatformManagementDAOException(
"Tenant - Platform Mapping.", e); "Error occurred while obtaining the connection to remove existing " + "Tenant - Platform Mapping"
+ " for the platform : " + platformIdentifier, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + getMapping, e); throw new PlatformManagementDAOException("Error occurred while executing the SQL query - " + getMapping, e);
} finally { } finally {
ConnectionManagerUtil.closeConnection(); Util.cleanupResources(preparedStatement, null);
} }
} }
@Override @Override
public List<Platform> getPlatforms(String tenantDomain) throws PlatformManagementDAOException { public List<Platform> getPlatforms(int tenantId) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("GetPlaforms request received for the tenantDomain " + tenantDomain); log.debug("GetPlaforms request received for the tenant ID " + tenantId);
} }
String selectQuery = String selectQuery =
"SELECT MAPPING.ID, PLATFORM.IDENTIFIER FROM (SELECT * FROM APPM_PLATFORM WHERE TENANT_DOMAIN=? OR " "SELECT MAPPING.ID, PLATFORM.IDENTIFIER FROM (SELECT * FROM APPM_PLATFORM WHERE TENANT_ID=? OR "
+ "IS_SHARED = TRUE AND FILE_BASED = FALSE) PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING " + "IS_SHARED = TRUE AND FILE_BASED = FALSE) PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING "
+ "MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID"; + "MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID";
try { try {
Connection connection = ConnectionManagerUtil.openConnection(); Connection connection = this.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(selectQuery); preparedStatement = connection.prepareStatement(selectQuery);
preparedStatement.setString(1, tenantDomain); preparedStatement.setInt(1, tenantId);
ResultSet resultSet = preparedStatement.executeQuery(); resultSet = preparedStatement.executeQuery();
List<Platform> platforms = new ArrayList<>(); List<Platform> platforms = new ArrayList<>();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Platform retrieved for the tenant domain " + tenantDomain); log.debug("Platform retrieved for the tenant Id " + tenantId);
} }
while (resultSet.next()) { while (resultSet.next()) {
String identifier = resultSet.getString("PLATFORM.IDENTIFIER"); String identifier = resultSet.getString("PLATFORM.IDENTIFIER");
int mappingID = resultSet.getInt("MAPPING.ID"); int mappingID = resultSet.getInt("MAPPING.ID");
Platform platform = getPlatform(tenantDomain, identifier); Platform platform = getPlatform(tenantId, identifier);
if (mappingID != 0) { if (mappingID != 0) {
platform.setEnabled(true); platform.setEnabled(true);
} else { } else {
@ -373,36 +398,37 @@ public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformD
} }
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Number of platforms available for the tenant domain - " + tenantDomain + " :" + platforms log.debug("Number of platforms available for the tenant ID - " + tenantId + " :" + platforms
.size()); .size());
} }
return platforms; return platforms;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new PlatformManagementDAOException( throw new PlatformManagementDAOException(
"Error occured when loading the platforms for tenant - " + tenantDomain, e); "Error occurred when loading the platforms for tenant - " + tenantId, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformManagementDAOException("Error occurred when executing query - " + selectQuery, e); throw new PlatformManagementDAOException("Error occurred when executing query - " + selectQuery, e);
} finally { } finally {
ConnectionManagerUtil.closeConnection(); Util.cleanupResources(preparedStatement,resultSet);
} }
} }
public Platform getPlatform(String tenantDomain, String platformIdenfier) throws PlatformManagementDAOException { public Platform getPlatform(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String platformQuery = "SELECT * FROM (SELECT * FROM APPM_PLATFORM WHERE (TENANT_DOMAIN=? AND IDENTIFIER=?) " + String platformQuery = "SELECT * FROM (SELECT * FROM APPM_PLATFORM WHERE (TENANT_DOMAIN=? AND IDENTIFIER=?) " +
"OR (IS_SHARED = TRUE AND IDENTIFIER=?) AND FILE_BASED = FALSE ) PLATFORM " + "OR (IS_SHARED = TRUE AND IDENTIFIER=?) AND FILE_BASED = FALSE ) PLATFORM " +
"LEFT JOIN APPM_PLATFORM_PROPERTIES PROPS ON PLATFORM.ID = PROPS.PLATFORM_ID"; "LEFT JOIN APPM_PLATFORM_PROPERTIES PROPS ON PLATFORM.ID = PROPS.PLATFORM_ID";
try { try {
ConnectionManagerUtil.openConnection(); Connection connection = this.getConnection();
Connection connection = ConnectionManagerUtil.getConnection(); preparedStatement = connection.prepareStatement(platformQuery);
PreparedStatement preparedStatement = connection.prepareStatement(platformQuery);
preparedStatement.setString(1, tenantDomain); preparedStatement.setString(1, tenantDomain);
preparedStatement.setString(2, platformIdenfier); preparedStatement.setString(2, platformIdentifier);
preparedStatement.setString(3, platformIdenfier); preparedStatement.setString(3, platformIdentifier);
ResultSet resultSet = preparedStatement.executeQuery(); resultSet = preparedStatement.executeQuery();
Platform platform = new Platform(); Platform platform = new Platform();
if (resultSet.next()) { if (resultSet.next()) {
platform.setId(resultSet.getInt("PLATFORM.ID")); platform.setId(resultSet.getInt("PLATFORM.ID"));
platform.setIdentifier(platformIdenfier); platform.setIdentifier(platformIdentifier);
platform.setName(resultSet.getString("PLATFORM.NAME")); platform.setName(resultSet.getString("PLATFORM.NAME"));
platform.setIconName(resultSet.getString("PLATFORM.DESCRIPTION")); platform.setIconName(resultSet.getString("PLATFORM.DESCRIPTION"));
platform.setIconName(resultSet.getString("PLATFORM.ICON_NAME")); platform.setIconName(resultSet.getString("PLATFORM.ICON_NAME"));
@ -420,50 +446,57 @@ public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformD
} while (resultSet.next()); } while (resultSet.next());
platform.setProperties(properties); platform.setProperties(properties);
} else { } else {
platform.setIdentifier(platformIdenfier); platform.setIdentifier(platformIdentifier);
platform.setFileBased(true); platform.setFileBased(true);
} }
return platform; return platform;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Error when loading the platform - " + platformIdenfier, e); throw new PlatformManagementDAOException("Error when loading the platform - " + platformIdentifier, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformManagementDAOException("Error in executing the query - " + platformQuery, e); throw new PlatformManagementDAOException("Error in executing the query - " + platformQuery, e);
} finally {
Util.cleanupResources(preparedStatement, resultSet);
} }
} }
public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException { public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException {
Connection conn;
Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
String sql = ""; String sql = "";
try { try {
conn = this.getConnection(); conn = this.getConnection();
sql += "SELECT * "; sql = "SELECT * FROM APPM_PLATFORM WHERE IDENTIFIER = ? AND TENANT_ID = ?";
sql += "FROM APPM_PLATFORM ";
sql += "WHERE IDENTIFIER = ? ";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, identifier); stmt.setString(1, identifier);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
Platform platform = null; Platform platform = null;
if (rs.next()) { if (rs.next()) {
platform = new Platform(); platform = new Platform();
platform.setFileBased(rs.getBoolean("FILE_BASED"));
platform.setIdentifier(rs.getString("IDENTIFIER"));
if (!platform.isFileBased()) {
platform.setId(rs.getInt("ID")); platform.setId(rs.getInt("ID"));
platform.setName(rs.getString("NAME")); platform.setName(rs.getString("NAME"));
platform.setIdentifier(rs.getString("IDENTIFIER")); platform.setDescription(rs.getString("DESCRIPTION"));
platform.setIconName(rs.getString("ICON_NAME"));
platform.setShared(rs.getBoolean("IS_SHARED"));
}
} }
return platform; return platform;
} catch (SQLException e) { } catch (SQLException e) {
throw new PlatformManagementDAOException("Error occurred while getting application List", e); throw new PlatformManagementDAOException("Error occurred while getting platform with the identifier " +
identifier + ", for the tenant : " + tenantId, e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new PlatformManagementDAOException("Error occurred while obtaining the DB connection.", e); throw new PlatformManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally {
Util.cleanupResources(stmt, rs);
} }
} }
} }

@ -17,11 +17,14 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.deployer; package org.wso2.carbon.device.application.mgt.core.deployer;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
/**
* Platform represents an Application Platform such as Android, IOS, etc.
*/
@XmlRootElement(name = "Platform") @XmlRootElement(name = "Platform")
public class Platform { public class Platform {

@ -29,20 +29,26 @@ import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.Constants; import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
/**
* PlatformDeployer is responsible for deploying platforms that are added in the filesystem.
* This will deploy the platforms that are added in <IOT_HOME>/repository/deployment/server/platforms directory.
*/
public class PlatformDeployer extends AbstractDeployer { public class PlatformDeployer extends AbstractDeployer {
private static final Log log = LogFactory.getLog(PlatformDeployer.class); private static final Log log = LogFactory.getLog(PlatformDeployer.class);
@Override @Override
public void init(ConfigurationContext configurationContext) { public void init(ConfigurationContext configurationContext) {
File deployementDir = new File(MultitenantUtils.getAxis2RepositoryPath(CarbonContext.getThreadLocalCarbonContext(). File deployementDir = new File(
MultitenantUtils.getAxis2RepositoryPath(CarbonContext.getThreadLocalCarbonContext().
getTenantId()) + Constants.PLATFORMS_DEPLOYMENT_DIR_NAME); getTenantId()) + Constants.PLATFORMS_DEPLOYMENT_DIR_NAME);
if (!deployementDir.exists()) { if (!deployementDir.exists()) {
if (!deployementDir.mkdir()) { if (!deployementDir.mkdir()) {
@ -51,18 +57,22 @@ public class PlatformDeployer extends AbstractDeployer {
} }
} }
@Override
public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException { public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
File deploymentFile = new File(deploymentFileData.getAbsolutePath()); File deploymentFile = new File(deploymentFileData.getAbsolutePath());
try { try {
JAXBContext jaxbContext = JAXBContext.newInstance(Platform.class); JAXBContext jaxbContext = JAXBContext.newInstance(Platform.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Platform platformConf = (Platform) unmarshaller.unmarshal(deploymentFile); Platform platformConf = (Platform) unmarshaller.unmarshal(deploymentFile);
if (platformConf.getName().contentEquals(getPlatformID(deploymentFile.getName()))) { if (platformConf.getId().contentEquals(getPlatformID(deploymentFile.getName()))) {
org.wso2.carbon.device.application.mgt.common.Platform platform = convert(platformConf); org.wso2.carbon.device.application.mgt.common.Platform platform = convert(platformConf);
DataHolder.getInstance().getPlatformManager().register(CarbonContext.getThreadLocalCarbonContext().getTenantDomain(), platform); DataHolder.getInstance().getPlatformManager()
.register(CarbonContext.getThreadLocalCarbonContext().getTenantId(), platform);
log.info("Platform configuration : " + deploymentFile.getName() + " deployed successfully");
} else { } else {
log.error("Unable to deploy the platform - " + deploymentFile.getAbsolutePath() + "!. Platform config file name - " log.error("Unable to deploy the platform - " + deploymentFile.getAbsolutePath()
+ deploymentFile.getName() + " should match with the 'id' provided within the platform configuration!"); + "!. Platform config file name - " + deploymentFile.getName()
+ " should match with the 'id' provided within the platform configuration!");
} }
} catch (JAXBException e) { } catch (JAXBException e) {
log.error("Platform configuration file - " + deploymentFile.getAbsolutePath() + " is invalid!", e); log.error("Platform configuration file - " + deploymentFile.getAbsolutePath() + " is invalid!", e);
@ -71,12 +81,15 @@ public class PlatformDeployer extends AbstractDeployer {
} }
} }
@Override
public void undeploy(String fileName) throws DeploymentException { public void undeploy(String fileName) throws DeploymentException {
String platformId = getPlatformID(fileName); String platformId = getPlatformID(fileName);
try { try {
DataHolder.getInstance().getPlatformManager().unregister(CarbonContext.getThreadLocalCarbonContext().getTenantDomain(), platformId, true); DataHolder.getInstance().getPlatformManager()
.unregister(CarbonContext.getThreadLocalCarbonContext().getTenantId(), platformId, true);
log.info("Platform configuration : " + fileName + " un-deployed successfully");
} catch (PlatformManagementException e) { } catch (PlatformManagementException e) {
log.error("Error occurred while undeploying the platform - " + fileName); log.error("Error occurred while un-deploying the platform - " + fileName);
} }
} }
@ -89,7 +102,8 @@ public class PlatformDeployer extends AbstractDeployer {
} }
private org.wso2.carbon.device.application.mgt.common.Platform convert(Platform platformConfig) { private org.wso2.carbon.device.application.mgt.common.Platform convert(Platform platformConfig) {
org.wso2.carbon.device.application.mgt.common.Platform platform = new org.wso2.carbon.device.application.mgt.common.Platform(); org.wso2.carbon.device.application.mgt.common.Platform platform =
new org.wso2.carbon.device.application.mgt.common.Platform();
platform.setIdentifier(platformConfig.getId()); platform.setIdentifier(platformConfig.getId());
platform.setName(platformConfig.getName()); platform.setName(platformConfig.getName());
platform.setDescription(platformConfig.getDescription()); platform.setDescription(platformConfig.getDescription());
@ -99,13 +113,17 @@ public class PlatformDeployer extends AbstractDeployer {
platform.setDefaultTenantMapping(platformConfig.isTenantMapping()); platform.setDefaultTenantMapping(platformConfig.isTenantMapping());
platform.setEnabled(false); platform.setEnabled(false);
List<org.wso2.carbon.device.application.mgt.common.Platform.Property> properties = new ArrayList<>(); List<org.wso2.carbon.device.application.mgt.common.Platform.Property> properties = new ArrayList<>();
if (platformConfig.getProperties() != null) {
for (Property propertyConfig : platformConfig.getProperties()) { for (Property propertyConfig : platformConfig.getProperties()) {
org.wso2.carbon.device.application.mgt.common.Platform.Property property = new org.wso2.carbon.device.application.mgt.common.Platform.Property(); org.wso2.carbon.device.application.mgt.common.Platform.Property property =
new org.wso2.carbon.device.application.mgt.common.Platform.Property();
property.setName(propertyConfig.getName()); property.setName(propertyConfig.getName());
property.setDefaultValue(propertyConfig.getDefaultValue()); property.setDefaultValue(propertyConfig.getDefaultValue());
property.setOptional(propertyConfig.isOptional()); property.setOptional(propertyConfig.isOptional());
properties.add(property); properties.add(property);
} }
}
platform.setProperties(properties); platform.setProperties(properties);
return platform; return platform;
} }

@ -19,6 +19,9 @@ package org.wso2.carbon.device.application.mgt.core.exception;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException; import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
/**
* Exception that will be thrown when there is a issue during Platform level DAO operations.
*/
public class PlatformManagementDAOException extends PlatformManagementException { public class PlatformManagementDAOException extends PlatformManagementException {
public PlatformManagementDAOException(String message, Throwable ex) { public PlatformManagementDAOException(String message, Throwable ex) {

@ -20,10 +20,14 @@ package org.wso2.carbon.device.application.mgt.core.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.Platform; import org.wso2.carbon.device.application.mgt.common.Platform;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException; import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
import org.wso2.carbon.device.application.mgt.common.services.PlatformManager; import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory; import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.user.api.Tenant; import org.wso2.carbon.user.api.Tenant;
import org.wso2.carbon.user.api.TenantManager; import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
@ -34,8 +38,11 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/**
* Implementation of {@link PlatformManager}, which manages the CRUD operations on Application platforms.
*/
public class PlatformManagerImpl implements PlatformManager { public class PlatformManagerImpl implements PlatformManager {
private Map<String, Map<String, Platform>> inMemoryStore; private Map<Integer, Map<String, Platform>> inMemoryStore;
private static Log log = LogFactory.getLog(PlatformManagerImpl.class); private static Log log = LogFactory.getLog(PlatformManagerImpl.class);
public PlatformManagerImpl() { public PlatformManagerImpl() {
@ -43,34 +50,58 @@ public class PlatformManagerImpl implements PlatformManager {
} }
@Override @Override
public void initialize(String tenantDomain) throws PlatformManagementException { public void initialize(int tenantId) throws PlatformManagementException {
List<Platform> platforms = DAOFactory.getPlatformDAO().getPlatforms(tenantDomain); try {
ConnectionManagerUtil.beginTransaction();
List<Platform> platforms = DAOFactory.getPlatformDAO().getPlatforms(tenantId);
List<String> platformIdentifiers = new ArrayList<>(); List<String> platformIdentifiers = new ArrayList<>();
for (Platform platform : platforms) { for (Platform platform : platforms) {
if (!platform.isEnabled() & platform.isDefaultTenantMapping()) { if (!platform.isEnabled() & platform.isDefaultTenantMapping()) {
platformIdentifiers.add(platform.getIdentifier()); platformIdentifiers.add(platform.getIdentifier());
} }
} }
addMapping(tenantDomain, platformIdentifiers); DAOFactory.getPlatformDAO().addMapping(tenantId, platformIdentifiers);
ConnectionManagerUtil.commitTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException(
"Transaction Management Exception while initializing the " + "platforms for the tenant : "
+ tenantId, e);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while initializing the " + "platforms for the tenant : " + tenantId,
e);
} finally {
ConnectionManagerUtil.closeConnection();
}
} }
@Override @Override
public List<Platform> getPlatforms(String tenantDomain) throws PlatformManagementException { public List<Platform> getPlatforms(int tenantId) throws PlatformManagementException {
int platformIndex = 0;
List<Platform> platforms;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request for getting platforms received for the tenant domain " + tenantDomain + " at " log.debug("Request for getting platforms received for the tenant ID " + tenantId + " at "
+ "PlatformManager level"); + "PlatformManager level");
} }
List<Platform> platforms = DAOFactory.getPlatformDAO().getPlatforms(tenantDomain); try {
int platformIndex = 0; ConnectionManagerUtil.openConnection();
platforms = DAOFactory.getPlatformDAO().getPlatforms(tenantId);
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Database Connection Exception while getting the platforms for the tenant : " + tenantId, e);
} finally {
ConnectionManagerUtil.closeConnection();
}
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Number of platforms received from DAO layer is " + platforms.size() + " for the tenant " log.debug("Number of platforms received from DAO layer is " + platforms.size() + " for the tenant "
+ tenantDomain); + tenantId);
} }
for (Platform platform : platforms) { for (Platform platform : platforms) {
if (platform.isFileBased()) { if (platform.isFileBased()) {
Map<String, Platform> superTenantPlatforms = this.inMemoryStore Map<String, Platform> superTenantPlatforms = this.inMemoryStore
.get(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); .get(MultitenantConstants.SUPER_TENANT_ID);
Platform registeredPlatform = superTenantPlatforms.get(platform.getIdentifier()); Platform registeredPlatform = superTenantPlatforms.get(platform.getIdentifier());
if (registeredPlatform != null) { if (registeredPlatform != null) {
platforms.set(platformIndex, new Platform(registeredPlatform)); platforms.set(platformIndex, new Platform(registeredPlatform));
@ -87,36 +118,45 @@ public class PlatformManagerImpl implements PlatformManager {
platformIndex++; platformIndex++;
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Number of effective platforms for the tenant " + tenantDomain + " : " + platforms.size()); log.debug("Number of effective platforms for the tenant " + tenantId + " : " + platforms.size());
} }
return platforms; return platforms;
} }
@Override @Override
public Platform getPlatform(String tenantDomain, String identifier) throws PlatformManagementException { public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementException {
Platform platform = getPlatformFromInMemory(tenantDomain, identifier); Platform platform = getPlatformFromInMemory(tenantId, identifier);
if (platform == null) { if (platform == null) {
platform = DAOFactory.getPlatformDAO().getPlatform(tenantDomain, identifier); try {
ConnectionManagerUtil.openConnection();
platform = DAOFactory.getPlatformDAO().getPlatform(tenantId, identifier);
if (platform != null) { if (platform != null) {
return platform; return platform;
} }
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to get the " + "platform with the id :" + identifier
+ " for the tenant : " + tenantId, e);
} finally {
ConnectionManagerUtil.closeConnection();
}
} else { } else {
return new Platform(platform); return new Platform(platform);
} }
throw new PlatformManagementException("No platform was found for tenant - " + tenantDomain + throw new PlatformManagementException(
" with Platform identifier - " + identifier); "No platform was found for tenant - " + tenantId + " with platform identifier - " + identifier);
} }
private Platform getPlatformFromInMemory(String tenantDomain, String identifier) { private Platform getPlatformFromInMemory(int tenantId, String identifier) {
Map<String, Platform> platformMap = this.inMemoryStore.get(tenantDomain); Map<String, Platform> platformMap = this.inMemoryStore.get(tenantId);
if (platformMap != null) { if (platformMap != null) {
Platform platform = platformMap.get(identifier); Platform platform = platformMap.get(identifier);
if (platform != null) { if (platform != null) {
return platform; return platform;
} }
} }
if (!tenantDomain.equalsIgnoreCase(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
platformMap = this.inMemoryStore.get(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); platformMap = this.inMemoryStore.get(MultitenantConstants.SUPER_TENANT_ID);
if (platformMap != null) { if (platformMap != null) {
Platform platform = platformMap.get(identifier); Platform platform = platformMap.get(identifier);
if (platform != null && platform.isShared()) { if (platform != null && platform.isShared()) {
@ -128,23 +168,28 @@ public class PlatformManagerImpl implements PlatformManager {
} }
@Override @Override
public synchronized void register(String tenantDomain, Platform platform) throws PlatformManagementException { public synchronized void register(int tenantId, Platform platform) throws PlatformManagementException {
if (platform.isShared() && !tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { if (platform.isShared() && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
throw new PlatformManagementException("Platform sharing is a restricted operation, therefore Platform - " throw new PlatformManagementException(
+ platform.getIdentifier() + " cannot be shared by the tenant domain - " + tenantDomain); "Platform sharing is a restricted operation, therefore Platform - " + platform.getIdentifier()
+ " cannot be shared by the tenant domain - " + tenantId);
} }
int platformId = DAOFactory.getPlatformDAO().register(tenantDomain, platform); try {
ConnectionManagerUtil.beginTransaction();
int platformId = DAOFactory.getPlatformDAO().register(tenantId, platform);
if (platform.isFileBased()) { if (platform.isFileBased()) {
platform.setId(platformId); platform.setId(platformId);
Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantDomain); Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantId);
if (tenantPlatforms == null) { if (tenantPlatforms == null) {
tenantPlatforms = new HashMap<>(); tenantPlatforms = new HashMap<>();
this.inMemoryStore.put(tenantDomain, tenantPlatforms); this.inMemoryStore.put(tenantId, tenantPlatforms);
} }
if (tenantPlatforms.get(platform.getIdentifier()) == null) { if (tenantPlatforms.get(platform.getIdentifier()) == null) {
tenantPlatforms.put(platform.getIdentifier(), platform); tenantPlatforms.put(platform.getIdentifier(), platform);
} else { } else {
throw new PlatformManagementException("Platform - " + platform.getIdentifier() + " is already registered!"); ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementException(
"Platform - " + platform.getIdentifier() + " is already registered!");
} }
} }
if (platform.isDefaultTenantMapping()) { if (platform.isDefaultTenantMapping()) {
@ -153,42 +198,86 @@ public class PlatformManagerImpl implements PlatformManager {
TenantManager tenantManager = DataHolder.getInstance().getRealmService().getTenantManager(); TenantManager tenantManager = DataHolder.getInstance().getRealmService().getTenantManager();
Tenant[] tenants = tenantManager.getAllTenants(); Tenant[] tenants = tenantManager.getAllTenants();
for (Tenant tenant : tenants) { for (Tenant tenant : tenants) {
addMapping(tenant.getDomain(), platform.getIdentifier()); DAOFactory.getPlatformDAO()
.addMapping(tenant.getId(), getListOfString(platform.getIdentifier()));
} }
} }
addMapping(tenantDomain, platform.getIdentifier()); DAOFactory.getPlatformDAO().addMapping(tenantId, getListOfString(platform.getIdentifier()));
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new PlatformManagementException("Error occured while assigning the platforms for tenants!", e); ConnectionManagerUtil.rollbackTransaction();
} throw new PlatformManagementException("Error occurred while assigning the platforms for tenants!",
e);
}
}
ConnectionManagerUtil.commitTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException(
"Transaction Management Exception while trying to register a " + "platform with id " + platform
.getIdentifier() + " for tenant " + tenantId);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to register a " + "platform with id " + platform
.getIdentifier() + " for tenant " + tenantId);
} finally {
ConnectionManagerUtil.closeConnection();
} }
} }
@Override @Override
public void update(String tenantDomain, String oldPlatformIdentifier, Platform platform) public void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws
throws PlatformManagementException { PlatformManagementException {
if (platform.isShared() && !tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { if (platform.isShared() && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
throw new PlatformManagementException("Platform sharing is a restricted operation, therefore Platform - " throw new PlatformManagementException(
+ platform.getIdentifier() + " cannot be shared by the tenant domain - " + tenantDomain); "Platform sharing is a restricted operation, therefore Platform - " + platform.getIdentifier()
+ " cannot be shared by the tenant domain - " + tenantId);
} }
Platform oldPlatform; Platform oldPlatform;
if (platform.getIdentifier() != null && !platform.getIdentifier().equals(oldPlatformIdentifier)) {
try {
ConnectionManagerUtil.openConnection();
Platform existingPlatform = DAOFactory.getPlatformDAO().getPlatform(tenantId, platform.getIdentifier());
if (existingPlatform != null) {
throw new PlatformManagementException(
"Cannot update the identifier of the platform from '" + oldPlatformIdentifier + "' to '"
+ platform.getIdentifier() + "'. Another platform exists "
+ "already with the identifier '" + platform.getIdentifier() + "' for the tenant : "
+ tenantId);
}
} catch (DBConnectionException e) {
throw new PlatformManagementException(
"Database Connection Exception while trying to update the " + "platform for the tenant : "
+ tenantId, e);
} finally {
ConnectionManagerUtil.closeConnection();
}
}
try {
if (platform.isFileBased()) { if (platform.isFileBased()) {
Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantDomain); Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantId);
if (tenantPlatforms == null) { if (tenantPlatforms == null) {
throw new PlatformManagementException("No platforms registered for the tenant - " + tenantDomain + throw new PlatformManagementException(
" with platform identifier - " + platform.getIdentifier()); "No platforms registered for the tenant - " + tenantId + " with platform identifier - "
+ platform.getIdentifier());
} }
oldPlatform = tenantPlatforms.get(oldPlatformIdentifier); oldPlatform = tenantPlatforms.get(oldPlatformIdentifier);
if (oldPlatform == null) { if (oldPlatform == null) {
throw new PlatformManagementException("No platforms registered for the tenant - " + tenantDomain + throw new PlatformManagementException(
" with platform identifier - " + platform.getIdentifier()); "No platforms registered for the tenant - " + tenantId + " with platform identifier - "
+ platform.getIdentifier());
} else { } else {
DAOFactory.getPlatformDAO().update(tenantDomain, oldPlatformIdentifier, platform); ConnectionManagerUtil.beginTransaction();
DAOFactory.getPlatformDAO().update(tenantId, oldPlatformIdentifier, platform);
platform.setId(oldPlatform.getId()); platform.setId(oldPlatform.getId());
tenantPlatforms.put(platform.getIdentifier(), platform); tenantPlatforms.put(platform.getIdentifier(), platform);
} }
} else { } else {
oldPlatform = DAOFactory.getPlatformDAO().getPlatform(tenantDomain, oldPlatformIdentifier); ConnectionManagerUtil.beginTransaction();
DAOFactory.getPlatformDAO().update(tenantDomain, oldPlatformIdentifier, platform); oldPlatform = DAOFactory.getPlatformDAO().getPlatform(tenantId, oldPlatformIdentifier);
DAOFactory.getPlatformDAO().update(tenantId, oldPlatformIdentifier, platform);
} }
if (platform.isDefaultTenantMapping() && !oldPlatform.isDefaultTenantMapping()) { if (platform.isDefaultTenantMapping() && !oldPlatform.isDefaultTenantMapping()) {
try { try {
@ -196,45 +285,101 @@ public class PlatformManagerImpl implements PlatformManager {
TenantManager tenantManager = DataHolder.getInstance().getRealmService().getTenantManager(); TenantManager tenantManager = DataHolder.getInstance().getRealmService().getTenantManager();
Tenant[] tenants = tenantManager.getAllTenants(); Tenant[] tenants = tenantManager.getAllTenants();
for (Tenant tenant : tenants) { for (Tenant tenant : tenants) {
addMapping(tenant.getDomain(), platform.getIdentifier()); DAOFactory.getPlatformDAO()
.addMapping(tenant.getId(), getListOfString(platform.getIdentifier()));
} }
} }
addMapping(tenantDomain, platform.getIdentifier()); DAOFactory.getPlatformDAO().addMapping(tenantId, getListOfString(platform.getIdentifier()));
} catch (UserStoreException e) { } catch (UserStoreException e) {
throw new PlatformManagementException("Error occured while assigning the platforms for tenants!", e); throw new PlatformManagementException("Error occurred while assigning the platforms for tenants!",
e);
} }
} }
if (!platform.isShared() && oldPlatform.isShared()) { if (!platform.isShared() && oldPlatform.isShared()) {
DAOFactory.getPlatformDAO().removeMappingTenants(platform.getIdentifier()); DAOFactory.getPlatformDAO().removeMappingTenants(platform.getIdentifier());
} }
ConnectionManagerUtil.commitTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException(
"Transaction Management Exception while trying to update " + "platform : " + oldPlatformIdentifier
+ " of tenant :" + tenantId);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to update " + "platform : " + oldPlatformIdentifier
+ " of tenant :" + tenantId);
} finally {
ConnectionManagerUtil.closeConnection();
}
}
private List<String> getListOfString(String platformIdentifier) {
List<String> identifiers = new ArrayList<>();
identifiers.add(platformIdentifier);
return identifiers;
} }
@Override @Override
public void unregister(String tenantDomain, String identifier, boolean isFileBased) throws PlatformManagementException { public void unregister(int tenantId, String identifier, boolean isFileBased) throws PlatformManagementException {
try {
ConnectionManagerUtil.beginTransaction();
DAOFactory.getPlatformDAO().unregister(tenantId, identifier, isFileBased);
if (isFileBased) { if (isFileBased) {
Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantDomain); Map<String, Platform> tenantPlatforms = this.inMemoryStore.get(tenantId);
if (tenantPlatforms != null) { if (tenantPlatforms != null) {
this.inMemoryStore.remove(identifier); tenantPlatforms.remove(identifier);
} }
} else { }
DAOFactory.getPlatformDAO().unregister(tenantDomain, identifier); ConnectionManagerUtil.commitTransaction();
} catch (TransactionManagementException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException(
"Transaction Management Exception while trying to un-register " + "the platform with identifier : "
+ identifier + " tenant :" + tenantId, e);
} catch (DBConnectionException e) {
ConnectionManagerUtil.rollbackTransaction();
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to un-register " + "the platform with identifier : "
+ identifier + " tenant :" + tenantId, e);
} finally {
ConnectionManagerUtil.closeConnection();
} }
} }
@Override @Override
public void addMapping(String tenantDomain, List<String> platformIdentifiers) throws PlatformManagementException { public void addMapping(int tenantId, List<String> platformIdentifiers) throws PlatformManagementException {
DAOFactory.getPlatformDAO().addMapping(tenantDomain, platformIdentifiers); try {
ConnectionManagerUtil.openConnection();
DAOFactory.getPlatformDAO().addMapping(tenantId, platformIdentifiers);
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to add tenant " + "mapping for tenant ID : "
+ tenantId);
} finally {
ConnectionManagerUtil.closeConnection();
}
} }
@Override @Override
public void addMapping(String tenantDomain, String platformIdentifier) throws PlatformManagementException { public void addMapping(int tenantId, String platformIdentifier) throws PlatformManagementException {
List<String> identifiers = new ArrayList<>(); List<String> identifiers = new ArrayList<>();
identifiers.add(platformIdentifier); identifiers.add(platformIdentifier);
DAOFactory.getPlatformDAO().addMapping(tenantDomain, identifiers); addMapping(tenantId, identifiers);
} }
@Override @Override
public void removeMapping(String tenantDomain, String platformIdentifier) throws PlatformManagementException { public void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementException {
DAOFactory.getPlatformDAO().removeMapping(tenantDomain, platformIdentifier); try {
ConnectionManagerUtil.openConnection();
DAOFactory.getPlatformDAO().removeMapping(tenantId, platformIdentifier);
} catch (DBConnectionException e) {
throw new PlatformManagementDAOException(
"Database Connection Exception while trying to remove tenant mapping for tenant ID : " + tenantId);
} finally {
ConnectionManagerUtil.closeConnection();
}
} }
} }

@ -29,7 +29,6 @@ import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManage
import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager; import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
import org.wso2.carbon.device.application.mgt.common.services.VisibilityTypeManager; import org.wso2.carbon.device.application.mgt.common.services.VisibilityTypeManager;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
/** /**
@ -63,8 +62,6 @@ public class DataHolder {
private static final DataHolder applicationMgtDataHolder = new DataHolder(); private static final DataHolder applicationMgtDataHolder = new DataHolder();
private DataSourceService dataSourceService;
private DataHolder() { private DataHolder() {
} }
@ -169,11 +166,4 @@ public class DataHolder {
this.realmService = realmService; this.realmService = realmService;
} }
public void setDataSourceService(DataSourceService dataSourceService) {
this.dataSourceService = dataSourceService;
}
public DataSourceService getDataSourceService() {
return dataSourceService;
}
} }

@ -70,8 +70,7 @@ public class ServiceComponent {
private static Log log = LogFactory.getLog(ServiceComponent.class); private static Log log = LogFactory.getLog(ServiceComponent.class);
protected void activate(ComponentContext componentContext) throws NamingException, protected void activate(ComponentContext componentContext) throws NamingException {
ApplicationManagementDAOException {
BundleContext bundleContext = componentContext.getBundleContext(); BundleContext bundleContext = componentContext.getBundleContext();
try { try {
String datasourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName(); String datasourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName();
@ -119,9 +118,12 @@ public class ServiceComponent {
bundleContext.registerService(ApplicationUploadManager.class.getName(), uploadManager, null); bundleContext.registerService(ApplicationUploadManager.class.getName(), uploadManager, null);
DAOFactory.init(datasourceName); DAOFactory.init(datasourceName);
DAOFactory.initDatabases();
log.info("ApplicationManagement core bundle has been successfully initialized"); log.info("ApplicationManagement core bundle has been successfully initialized");
} catch (InvalidConfigurationException e) { } catch (InvalidConfigurationException e) {
log.error("Error while activating Application Management core component. ", e); log.error("Error while activating Application Management core component. ", e);
} catch (ApplicationManagementDAOException e) {
log.error("Error while activating Application Management core component.Failed to create the database ", e);
} }
} }
@ -152,10 +154,12 @@ public class ServiceComponent {
} }
protected void setDataSourceService(DataSourceService dataSourceService) { protected void setDataSourceService(DataSourceService dataSourceService) {
DataHolder.getInstance().setDataSourceService(dataSourceService); //Not implemented. Not needed but to make sure the datasource service are registered, as it is needed create
// databases.
} }
protected void unsetDataSourceService(DataSourceService dataSourceService) { protected void unsetDataSourceService(DataSourceService dataSourceService) {
DataHolder.getInstance().setDataSourceService(null); //Not implemented. Not needed but to make sure the datasource service are registered, as it is needed to create
// databases.
} }
} }

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -18,13 +18,13 @@
package org.wso2.carbon.device.application.mgt.core.util; package org.wso2.carbon.device.application.mgt.core.util;
import org.apache.commons.logging.Log; import java.io.File;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator; import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource; import org.apache.commons.logging.LogFactory;
import java.io.File; import org.apache.commons.logging.Log;
/** /**
* ApplicationMgtDatabaseCreator is responsible for creating the Application Management related tables. * ApplicationMgtDatabaseCreator is responsible for creating the Application Management related tables.
@ -35,8 +35,8 @@ public class ApplicationMgtDatabaseCreator extends DatabaseCreator {
CarbonUtils.getCarbonHome() + File.separator + "dbscripts" + File.separator + "cdm" + File.separator CarbonUtils.getCarbonHome() + File.separator + "dbscripts" + File.separator + "cdm" + File.separator
+ "application-mgt" + File.separator; + "application-mgt" + File.separator;
public ApplicationMgtDatabaseCreator(DataSource dataSource) { public ApplicationMgtDatabaseCreator(String dataSourceName) {
super(dataSource); super(ConnectionManagerUtil.resolveDataSource(dataSourceName));
} }
protected String getDbScriptLocation(String databaseType) { protected String getDbScriptLocation(String databaseType) {

@ -273,18 +273,19 @@ public class ConnectionManagerUtil {
} }
} }
/** /**
* Resolve data source from the data source definition. * Resolve the datasource from the datasource definition.
* *
* @param dataSourceName data source name * @param dataSourceName Name of the datasource
* @return DataSource resolved by the datasource name
*/ */
public static void resolveDataSource(String dataSourceName) { public static DataSource resolveDataSource(String dataSourceName) {
try { try {
dataSource = InitialContext.doLookup(dataSourceName); dataSource = InitialContext.doLookup(dataSourceName);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e);
} }
return dataSource;
} }
@ -296,4 +297,5 @@ public class ConnectionManagerUtil {
} }
return null; return null;
} }
} }

@ -41,6 +41,12 @@
</modules> </modules>
<build> <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<plugin> <plugin>

@ -6,15 +6,36 @@
-- Table APPM_PLATFORM -- Table APPM_PLATFORM
-- ----------------------------------------------------- -- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_PLATFORM ( CREATE TABLE IF NOT EXISTS APPM_PLATFORM (
ID INT NOT NULL, ID INT NOT NULL AUTO_INCREMENT UNIQUE,
NAME VARCHAR(100) NOT NULL, IDENTIFIER VARCHAR (100) NOT NULL,
DESCRIPTION TEXT NULL, TENANT_ID INT NOT NULL ,
IDENTIFIER VARCHAR(100) NOT NULL, NAME VARCHAR (255),
ICON_NAME VARCHAR(100) NULL, FILE_BASED BOOLEAN,
DESCRIPTOR LONGTEXT NOT NULL, DESCRIPTION LONGVARCHAR,
PUBLISHED TINYINT NULL, IS_SHARED BOOLEAN,
PRIMARY KEY (ID), ICON_NAME VARCHAR (100),
UNIQUE INDEX IDENTIFIER_UNIQUE (IDENTIFIER ASC)); PRIMARY KEY (IDENTIFIER, TENANT_ID)
);
CREATE TABLE IF NOT EXISTS APPM_PLATFORM_PROPERTIES (
ID INT NOT NULL AUTO_INCREMENT,
PLATFORM_ID INT NOT NULL,
PROP_NAME VARCHAR (100) NOT NULL,
OPTIONAL BOOLEAN,
DEFAUL_VALUE VARCHAR (255),
FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(ID) ON DELETE CASCADE,
PRIMARY KEY (ID, PLATFORM_ID, PROP_NAME)
);
CREATE TABLE IF NOT EXISTS APPM_PLATFORM_TENANT_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
TENANT_ID INT NOT NULL ,
PLATFORM_ID VARCHAR (100) NOT NULL,
FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(IDENTIFIER) ON DELETE CASCADE,
PRIMARY KEY (ID, TENANT_ID, PLATFORM_ID)
);
CREATE INDEX FK_PLATFROM_TENANT_MAPPING_PLATFORM ON APPM_PLATFORM_TENANT_MAPPING(PLATFORM_ID ASC);
-- ----------------------------------------------------- -- -----------------------------------------------------
-- Table APPM_APPLICATION_CATEGORY -- Table APPM_APPLICATION_CATEGORY
@ -26,21 +47,6 @@ CREATE TABLE IF NOT EXISTS APPM_APPLICATION_CATEGORY (
PUBLISHED TINYINT NULL, PUBLISHED TINYINT NULL,
PRIMARY KEY (ID)); PRIMARY KEY (ID));
-- -----------------------------------------------------
-- Table APPM_PLATFORM_APPLICATION_MAPPING
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_PLATFORM_APPLICATION_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
PLATFORM_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
PRIMARY KEY (ID, PLATFORM_ID),
CONSTRAINT fk_APPM_PLATFORM_TENANT_MAPPING_APPM_SUPPORTED_PLATFORM1
FOREIGN KEY (PLATFORM_ID)
REFERENCES APPM_PLATFORM (ID)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
CREATE INDEX FK_PLATFROM_APPLICATION_MAPPING_PLATFORM ON APPM_PLATFORM_APPLICATION_MAPPING(PLATFORM_ID ASC);
-- ----------------------------------------------------- -- -----------------------------------------------------
@ -83,9 +89,9 @@ CREATE TABLE IF NOT EXISTS APPM_APPLICATION (
REFERENCES APPM_APPLICATION_CATEGORY (ID) REFERENCES APPM_APPLICATION_CATEGORY (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION, ON UPDATE NO ACTION,
CONSTRAINT fk_APPM_APPLICATION_APPM_PLATFORM_APPLICATION_MAPPING1 CONSTRAINT fk_APPM_APPLICATION_APPM_PLATFORM_TENANT_MAPPING1
FOREIGN KEY (PLATFORM_APPLICATION_MAPPING_ID) FOREIGN KEY (PLATFORM_APPLICATION_MAPPING_ID)
REFERENCES APPM_PLATFORM_APPLICATION_MAPPING (ID) REFERENCES APPM_PLATFORM_TENANT_MAPPING (ID)
ON DELETE NO ACTION ON DELETE NO ACTION
ON UPDATE NO ACTION, ON UPDATE NO ACTION,
CONSTRAINT fk_APPM_APPLICATION_APPM_LIFECYCLE_STATE1 CONSTRAINT fk_APPM_APPLICATION_APPM_LIFECYCLE_STATE1
@ -278,8 +284,8 @@ CREATE INDEX FK_VISIBILITY_APPLICATION ON APPM_VISIBILITY(APPLICATION_ID ASC);
-- Table APPM_SUBSCRIPTION_PROPERTIES -- Table APPM_SUBSCRIPTION_PROPERTIES
-- ----------------------------------------------------- -- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS APPM_SUBSCRIPTION_PROPERTIES ( CREATE TABLE IF NOT EXISTS APPM_SUBSCRIPTION_PROPERTIES (
PROP_KEY TEXT NOT NULL, PROP_KEY VARCHAR(500) NOT NULL,
PROP_VALUE TEXT NULL, PROP_VALUE VARCHAR(500) NULL,
APPM_SUBSCRIPTION_ID INT NOT NULL, APPM_SUBSCRIPTION_ID INT NOT NULL,
PRIMARY KEY (PROP_KEY, APPM_SUBSCRIPTION_ID), PRIMARY KEY (PROP_KEY, APPM_SUBSCRIPTION_ID),
CONSTRAINT fk_APPM_SUBSCRIPTION_PROPERTIES_APPM_SUBSCRIPTION1 CONSTRAINT fk_APPM_SUBSCRIPTION_PROPERTIES_APPM_SUBSCRIPTION1

@ -14,16 +14,27 @@ SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- ----------------------------------------------------- -- -----------------------------------------------------
-- Table `APPM_PLATFORM` -- Table `APPM_PLATFORM`
-- ----------------------------------------------------- -- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_PLATFORM` ( CREATE TABLE IF NOT EXISTS APPM_PLATFORM (
`ID` INT NOT NULL, ID INT NOT NULL AUTO_INCREMENT UNIQUE,
`NAME` VARCHAR(100) NOT NULL, IDENTIFIER VARCHAR (100) NOT NULL,
`DESCRIPTION` TEXT NULL, TENANT_ID INT NOT NULL ,
`IDENTIFIER` VARCHAR(100) NOT NULL, NAME VARCHAR (255),
`DESCRIPTOR` LONGTEXT NOT NULL, FILE_BASED BOOLEAN,
PRIMARY KEY (`ID`), DESCRIPTION VARCHAR (2048),
UNIQUE INDEX `IDENTIFIER_UNIQUE` (`IDENTIFIER` ASC)) IS_SHARED BOOLEAN,
ENGINE = InnoDB ICON_NAME VARCHAR (100),
COMMENT = 'This table contains the data related to the application platform'; PRIMARY KEY (IDENTIFIER, TENANT_ID)
);
CREATE TABLE IF NOT EXISTS APPM_PLATFORM_PROPERTIES (
ID INT NOT NULL AUTO_INCREMENT,
PLATFORM_ID INT NOT NULL,
PROP_NAME VARCHAR (100) NOT NULL,
OPTIONAL BOOLEAN,
DEFAUL_VALUE VARCHAR (255),
FOREIGN KEY(PLATFORM_ID) REFERENCES APPM_PLATFORM(ID) ON DELETE CASCADE,
PRIMARY KEY (ID, PLATFORM_ID, PROP_NAME)
);
-- ----------------------------------------------------- -- -----------------------------------------------------
@ -235,7 +246,7 @@ CREATE TABLE IF NOT EXISTS `APPM_COMMENT` (
-- ----------------------------------------------------- -- -----------------------------------------------------
-- Table `APPM_PLATFORM_TENENT_MAPPING` -- Table `APPM_PLATFORM_TENENT_MAPPING`
-- ----------------------------------------------------- -- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `APPM_PLATFORM_TENENT_MAPPING` ( CREATE TABLE IF NOT EXISTS `APPM_PLATFORM_TENANT_MAPPING` (
`ID` INT NOT NULL AUTO_INCREMENT, `ID` INT NOT NULL AUTO_INCREMENT,
`PLATFORM_ID` INT NOT NULL, `PLATFORM_ID` INT NOT NULL,
`TENANT_ID` INT NOT NULL, `TENANT_ID` INT NOT NULL,

@ -953,11 +953,6 @@
<artifactId>org.wso2.carbon.identity.application.common</artifactId> <artifactId>org.wso2.carbon.identity.application.common</artifactId>
<version>${carbon.identity.framework.version}</version> <version>${carbon.identity.framework.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth2.grant.jwt</artifactId>
<version>${identity.jwt.extension.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.identity.framework</groupId> <groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.user.mgt</artifactId> <artifactId>org.wso2.carbon.user.mgt</artifactId>
@ -1190,16 +1185,6 @@
<artifactId>org.wso2.carbon.application.mgt.stub</artifactId> <artifactId>org.wso2.carbon.application.mgt.stub</artifactId>
<version>${carbon.commons.version}</version> <version>${carbon.commons.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId>
<version>${carbon.analytics.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.datasource.commons</artifactId>
<version>${carbon.analytics.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.event-processing</groupId> <groupId>org.wso2.carbon.event-processing</groupId>
<artifactId>org.wso2.carbon.event.processor.stub</artifactId> <artifactId>org.wso2.carbon.event.processor.stub</artifactId>
@ -1429,11 +1414,6 @@
<groupId>org.wso2.carbon.analytics-common</groupId> <groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId> <artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
<version>${carbon.analytics.common.version}</version> <version>${carbon.analytics.common.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.receiver.stub</artifactId>
<version>${carbon.analytics.common.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.analytics</groupId> <groupId>org.wso2.carbon.analytics</groupId>
@ -1445,11 +1425,6 @@
<artifactId>org.wso2.carbon.analytics.dataservice.commons</artifactId> <artifactId>org.wso2.carbon.analytics.dataservice.commons</artifactId>
<version>${carbon.analytics.version}</version> <version>${carbon.analytics.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.stream.stub</artifactId>
<version>${carbon.analytics.common.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.analytics-common</groupId> <groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.publisher.stub</artifactId> <artifactId>org.wso2.carbon.event.publisher.stub</artifactId>
@ -1666,10 +1641,6 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins> </plugins>
<pluginManagement> <pluginManagement>
<plugins> <plugins>
@ -2022,7 +1993,6 @@
<servlet-api.version>2.5</servlet-api.version> <servlet-api.version>2.5</servlet-api.version>
<!--JWT grant type extension feature--> <!--JWT grant type extension feature-->
<identity.jwt.extension.version>1.0.2</identity.jwt.extension.version>
<jackson-annotations.version>2.6.1.wso2v1</jackson-annotations.version> <jackson-annotations.version>2.6.1.wso2v1</jackson-annotations.version>
<jackson-databind.version>2.6.1.wso2v3</jackson-databind.version> <jackson-databind.version>2.6.1.wso2v3</jackson-databind.version>
<joda-time.version>2.8.2.wso2v1</joda-time.version> <joda-time.version>2.8.2.wso2v1</joda-time.version>

Loading…
Cancel
Save