fixing conflics and fixes to app update APIs

feature/appm-store/pbac
inoshperera 6 years ago
commit dbc382716a

@ -31,7 +31,6 @@ import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@ -45,7 +44,7 @@ public class APIUtil {
private static final String DEFAULT_AGENT_API_TAG = "device_agent"; private static final String DEFAULT_AGENT_API_TAG = "device_agent";
private static final String DEFAULT_CERT_API_TAG = "scep_management"; private static final String DEFAULT_CERT_API_TAG = "scep_management";
private static final String DEFAULT_APP_MGT_TAG = "application_management"; private static final String DEFAULT_APP_MGT_TAG = "application_management";
private static final String DEFAULT_APP_MGT_LCYCLE_MGT_TAG = "lifecycle_management"; private static final String DEFAULT_APP_MGT_REVIEW_MGT_TAG = "review_management";
private static final String DEFAULT_APP_MGT_SUB_MGT_TAG = "subscription_management"; private static final String DEFAULT_APP_MGT_SUB_MGT_TAG = "subscription_management";
public static final String PERMISSION_PROPERTY_NAME = "name"; public static final String PERMISSION_PROPERTY_NAME = "name";
@ -112,7 +111,7 @@ public class APIUtil {
allowedApisTags.add(DEFAULT_CERT_API_TAG); allowedApisTags.add(DEFAULT_CERT_API_TAG);
allowedApisTags.add(DEFAULT_AGENT_API_TAG); allowedApisTags.add(DEFAULT_AGENT_API_TAG);
allowedApisTags.add(DEFAULT_APP_MGT_TAG); allowedApisTags.add(DEFAULT_APP_MGT_TAG);
allowedApisTags.add(DEFAULT_APP_MGT_LCYCLE_MGT_TAG); allowedApisTags.add(DEFAULT_APP_MGT_REVIEW_MGT_TAG);
allowedApisTags.add(DEFAULT_APP_MGT_SUB_MGT_TAG); allowedApisTags.add(DEFAULT_APP_MGT_SUB_MGT_TAG);
return allowedApisTags; return allowedApisTags;
} }

@ -60,10 +60,6 @@ public class ApplicationRelease {
value = "icon file storing location") value = "icon file storing location")
private String iconLoc; private String iconLoc;
@ApiModelProperty(name = "applicationCreator",
value = "Application release creator")
private String applicationCreator;
@ApiModelProperty(name = "releaseType", @ApiModelProperty(name = "releaseType",
value = "Release type of the application release", value = "Release type of the application release",
required = true, required = true,
@ -229,14 +225,6 @@ public class ApplicationRelease {
this.screenshotLoc3 = screenshotLoc3; this.screenshotLoc3 = screenshotLoc3;
} }
public String getApplicationCreator() {
return applicationCreator;
}
public void setApplicationCreator(String applicationCreator) {
this.applicationCreator = applicationCreator;
}
public String getIconLoc() { public String getIconLoc() {
return iconLoc; return iconLoc;
} }

@ -18,52 +18,51 @@
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/** /**
* Filter represents a criteria that can be used for searching applications. * Filter represents a criteria that can be used for searching applications.
*/ */
@ApiModel(value = "Filter", description = "This is related to the application filtering.")
public class Filter { public class Filter {
@ApiModelProperty( /**
name = "appName", * Name of the application
value = "Name of the application", */
required = false)
private String appName; private String appName;
@ApiModelProperty( /**
name = "appType", * Type of the application
value = "Type of the application", */
required = false)
private String appType; private String appType;
@ApiModelProperty( /**
name = "isFullMatch", * Category of the application
value = "Checking the application name matches fully with given name", */
required = false) private String appCategory;
/**
* Checking the application name matches fully with given name
*/
private boolean isFullMatch; private boolean isFullMatch;
@ApiModelProperty( /**
name = "limit", * Limit of the applications
value = "Limit of the applications", */
required = false)
private int limit; private int limit;
@ApiModelProperty( /**
name = "offset", * Started from
value = "Started from", */
required = false)
private int offset; private int offset;
@ApiModelProperty( /**
name = "sortBy", * Ascending or descending order
value = "Ascending or descending order", */
required = false)
private String sortBy; private String sortBy;
/**
* Set as True if required to have only published application release, otherwise set to False
*/
private boolean requirePublishedRelease;
public int getLimit() { public int getLimit() {
return limit; return limit;
} }
@ -111,4 +110,20 @@ public class Filter {
public void setAppType(String appType) { public void setAppType(String appType) {
this.appType = appType; this.appType = appType;
} }
public String getAppCategory() {
return appCategory;
}
public void setAppCategory(String appCategory) {
this.appCategory = appCategory;
}
public boolean isRequirePublishedRelease() {
return requirePublishedRelease;
}
public void setRequirePublishedRelease(boolean requirePublishedRelease) {
this.requirePublishedRelease = requirePublishedRelease;
}
} }

@ -119,7 +119,7 @@ public interface ApplicationManager {
* @return the boolean value, whether application exist or not * @return the boolean value, whether application exist or not
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException Application Management Exception.
*/ */
Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException; boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException;
/** /**
* To get Application with the given UUID. * To get Application with the given UUID.
@ -129,15 +129,6 @@ public interface ApplicationManager {
*/ */
Boolean isUserAllowable(List<UnrestrictedRole> unrestrictedRoles, String userName) throws ApplicationManagementException; Boolean isUserAllowable(List<UnrestrictedRole> unrestrictedRoles, String userName) throws ApplicationManagementException;
/**
* To get all the releases of a particular Application.
*
* @param applicationId ID of the Application to get all the releases.
* @return the List of the Application releases related with the particular Application.
* @throws ApplicationManagementException Application Management Exception.
*/
List<ApplicationRelease> getReleases(int applicationId) throws ApplicationManagementException;
/** /**
* To get the release of a particular Application. * To get the release of a particular Application.
* *
@ -152,24 +143,23 @@ public interface ApplicationManager {
* To get all the releases of a particular Application. * To get all the releases of a particular Application.
* *
* @param applicationId ID of the Application . * @param applicationId ID of the Application .
* @param applicationUuid UUID of the Application Release. * @param releaseUuid UUID of the Application Release.
* @return the LifecycleState of the Application releases related with the particular Application. * @return the LifecycleState of the Application releases related with the particular Application.
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException Application Management Exception.
*/ */
LifecycleState getLifecycleState(int applicationId, String applicationUuid) throws ApplicationManagementException; LifecycleState getLifecycleState(int applicationId, String releaseUuid) throws ApplicationManagementException;
/** /**
* To get all the releases of a particular Application. * To get all the releases of a particular Application.
* *
* @param applicationId ID of the Application. * @param applicationId ID of the Application.
* @param applicationUuid UUID of the Application Release. * @param releaseUuid UUID of the Application Release.
* @param state Lifecycle state to change the app * @param state Lifecycle state to change the app
* @param checkExist whether it is needed to check if the app and release already exist in the database * @param checkExist whether it is needed to check if the app and release already exist in the database
* @param releaseId The release ID of the application(optional)
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException Application Management Exception.
*/ */
void changeLifecycleState(int applicationId, String applicationUuid, LifecycleState state, Boolean checkExist, void changeLifecycleState(int applicationId, String releaseUuid, LifecycleState state, Boolean checkExist)
int releaseId) throws ApplicationManagementException; throws ApplicationManagementException;
/** /**
* Get the application if application is an accessible one. * Get the application if application is an accessible one.

@ -84,6 +84,17 @@ public interface ApplicationDAO {
*/ */
Application getApplication(String appName, String appType, int tenantId) throws ApplicationManagementDAOException; Application getApplication(String appName, String appType, int tenantId) throws ApplicationManagementDAOException;
/**
* To get the application with the given id
*
* @param id ID of the application.
* @param tenantId ID of the tenant.
* @return the application
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
Application getApplicationById(String id, int tenantId) throws
ApplicationManagementDAOException;
/** /**
* To get the application with the given uuid * To get the application with the given uuid
* *
@ -98,10 +109,11 @@ public interface ApplicationDAO {
* To get the application with the given uuid * To get the application with the given uuid
* *
* @param appId ID of the application * @param appId ID of the application
* @param tenantId Tenant Id
* @return the boolean value * @return the boolean value
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementDAOException; boolean verifyApplicationExistenceById(int appId, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To get the application id of the application specified by the UUID * To get the application id of the application specified by the UUID

@ -58,13 +58,12 @@ public interface ApplicationReleaseDAO {
/** /**
* To get all the releases of a particular application. * To get all the releases of a particular application.
* *
* @param applicationName Name of the Application * @param applicationId Id of the Application
* @param applicationType Type of the Application
* @param tenantId tenant id of the application * @param tenantId tenant id of the application
* @return list of the application releases * @return list of the application releases
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
List<ApplicationRelease> getReleases(String applicationName, String applicationType, int tenantId) throws List<ApplicationRelease> getReleases(int applicationId, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
/** /**
@ -128,6 +127,16 @@ public interface ApplicationReleaseDAO {
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
ApplicationRelease getReleaseByIds(int applicationId, String releaseUuid, int tenantId) throws ApplicationRelease getReleaseByIds(int applicationId, String releaseUuid, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
/**
* To verify whether application release exist or not.
*
* @param appId ID of the application.
* @param uuid UUID of the application release.
* @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
boolean verifyReleaseExistence(int appId, String uuid, int tenantId) throws ApplicationManagementDAOException;
} }

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

@ -175,7 +175,6 @@ public class Util {
appRelease.setAppHashValue(rs.getString("APP_HASH_VALUE")); appRelease.setAppHashValue(rs.getString("APP_HASH_VALUE"));
appRelease.setAppStoredLoc(rs.getString("STORED_LOCATION")); appRelease.setAppStoredLoc(rs.getString("STORED_LOCATION"));
appRelease.setBannerLoc(rs.getString("BANNER_LOCATION")); appRelease.setBannerLoc(rs.getString("BANNER_LOCATION"));
appRelease.setApplicationCreator(rs.getString("CREATED_BY"));
appRelease.setRating(rs.getDouble("RATING")); appRelease.setRating(rs.getDouble("RATING"));
appRelease.setIsSharedWithAllTenants(rs.getInt("SHARED_WITH_ALL_TENANTS")); appRelease.setIsSharedWithAllTenants(rs.getInt("SHARED_WITH_ALL_TENANTS"));
appRelease.setMetaData(rs.getString("APP_META_INFO")); appRelease.setMetaData(rs.getString("APP_META_INFO"));

@ -34,7 +34,9 @@ import java.sql.SQLException;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar;
import java.util.List; import java.util.List;
/** /**
@ -53,18 +55,23 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
} }
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet rs = null; ResultSet rs = null;
sql = "INSERT INTO AP_APP_REVIEW (TENANT_ID, COMMENT, PARENT_ID, USERNAME, AP_APP_RELEASE_ID, AP_APP_ID) " sql = "INSERT INTO AP_APP_REVIEW (TENANT_ID, COMMENT, PARENT_ID, USERNAME,CREATED_AT, MODIFIES_AT,"
+ "VALUES (?,?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE UUID= ?)," + " AP_APP_RELEASE_ID, AP_APP_ID) VALUES (?,?,?,?,?,?,(SELECT ID FROM AP_APP_RELEASE WHERE UUID= ?),"
+ "(SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID=?));"; + "(SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID=?));";
try { try {
Calendar calendar = Calendar.getInstance();
Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
statement = conn.prepareStatement(sql, new String[] { "id" }); statement = conn.prepareStatement(sql, new String[] { "id" });
statement.setInt(1, tenantId); statement.setInt(1, tenantId);
statement.setString(2, review.getComment()); statement.setString(2, review.getComment());
statement.setInt(3, review.getParentId()); statement.setInt(3, review.getParentId());
statement.setString(4, review.getUsername()); statement.setString(4, review.getUsername());
statement.setString(5,uuid); statement.setTimestamp(5,timestamp);
statement.setString(6,uuid); statement.setTimestamp(6,timestamp);
statement.setString(7,uuid);
statement.setString(8,uuid);
statement.executeUpdate(); statement.executeUpdate();
rs = statement.getGeneratedKeys(); rs = statement.getGeneratedKeys();
return rs.next(); return rs.next();
@ -134,15 +141,19 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet rs = null; ResultSet rs = null;
sql = "UPDATE AP_APP_REVIEW SET COMMENT=?, RATING=? WHERE ID=? AND USERNAME=? AND TENANT_ID=?;"; sql = "UPDATE AP_APP_REVIEW SET COMMENT=?, RATING=?, MODIFIED_AT=? WHERE ID=? AND USERNAME=? AND TENANT_ID=?;";
try { try {
Calendar calendar = Calendar.getInstance();
Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setString(1, review.getComment()); statement.setString(1, review.getComment());
statement.setInt(2, review.getRating()); statement.setInt(2, review.getRating());
statement.setInt(3, reviewId); statement.setTimestamp(3, timestamp);
statement.setString(4, username); statement.setInt(4, reviewId);
statement.setInt(5, tenantId); statement.setString(5, username);
statement.setInt(6, tenantId);
return statement.executeUpdate(); return statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new ReviewManagementDAOException("Error occurred while executing review updating query"); throw new ReviewManagementDAOException("Error occurred while executing review updating query");
@ -205,11 +216,11 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql = "SELECT AP_APP_REVIEW.ID AS ID, AP_APP_REVIEW.COMMENT AS COMMENT, " sql = "SELECT AP_APP_REVIEW.ID AS ID, AP_APP_REVIEW.COMMENT AS COMMENT, "
+ "AP_APP_REVIEW.CREATED_BY AS CREATED_BY, AP_APP_REVIEW.MODIFIED_BY AS MODIFIED_BY, " + "AP_APP_REVIEW.CREATED_AT AS CREATED_AT, AP_APP_REVIEW.MODIFIED_AT AS MODIFIED_AT, "
+ "AP_APP_REVIEW.PARENT_ID AS PARENT_ID FROM AP_APP_REVIEW, AP_APP_RELEASE WHERE " + "AP_APP_REVIEW.USERNAME AS USERNAME, AP_APP_REVIEW.PARENT_ID AS PARENT_ID "
+ "AP_APP_REVIEW.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND AP_APP_RELEASE.UUID =? AND " + "FROM AP_APP_REVIEW, AP_APP_RELEASE WHERE AP_APP_REVIEW.AP_APP_RELEASE_ID=AP_APP_RELEASE.ID AND "
+ "AP_APP_REVIEW.TENANT_ID = ? AND AP_APP_REVIEW.TENANT_ID = AP_APP_RELEASE.TENANT_ID " + "AP_APP_RELEASE.UUID =? AND AP_APP_REVIEW.TENANT_ID = ? AND "
+ "LIMIT ? OFFSET ?;"; + "AP_APP_REVIEW.TENANT_ID = AP_APP_RELEASE.TENANT_ID LIMIT ? OFFSET ?;";
statement = conn.prepareStatement(sql); statement = conn.prepareStatement(sql);
statement.setString(1, uuid); statement.setString(1, uuid);
statement.setInt(2, tenantId); statement.setInt(2, tenantId);
@ -219,15 +230,18 @@ public class ReviewDAOImpl extends AbstractDAOImpl implements ReviewDAO {
while (rs.next()) { while (rs.next()) {
Review review = new Review(); Review review = new Review();
review.setId(rs.getInt("ID")); review.setId(rs.getInt("ID"));
review.setComment(rs.getString("COMMENT_TEXT")); review.setComment(rs.getString("COMMENT"));
review.setUsername(rs.getString("CREATED_BY")); review.setCreatedAt(rs.getTimestamp("CREATED_AT"));
review.setModifiedAt(rs.getTimestamp("MODIFIED_AT"));
review.setParentId(rs.getInt("PARENT_ID"));
review.setUsername(rs.getString("USERNAME"));
reviews.add(review); reviews.add(review);
} }
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ReviewManagementDAOException( throw new ReviewManagementDAOException(
"Error occurred while obtaining the DB connection when verifying application existence", e); "Error occurred while obtaining the DB connection when verifying application existence", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ReviewManagementDAOException("Error occurred while adding unrestricted roles", e); throw new ReviewManagementDAOException("DB connection error occurred while getting all reviews", e);
}finally { }finally {
Util.cleanupResources(statement, rs); Util.cleanupResources(statement, rs);
} }

@ -116,7 +116,8 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Error occurred while obtaining the DB connection when verifying application existence", e); "Error occurred while obtaining the DB connection when verifying application existence", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding unrestricted roles", e); throw new ApplicationManagementDAOException(
"DB connection error occured while checking whether application exist or not.", e);
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
@ -146,11 +147,17 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
throw new ApplicationManagementDAOException("Filter need to be instantiated"); throw new ApplicationManagementDAOException("Filter need to be instantiated");
} }
if (filter.getAppType() != null) { if (filter.getAppType() != null && !filter.getAppType().isEmpty()) {
sql += " AND AP_APP.TYPE "; sql += " AND AP_APP.TYPE ";
sql += "= ?"; sql += "= ?";
} }
if (filter.getAppName() != null) {
if (filter.getAppCategory() != null && !filter.getAppCategory().isEmpty()) {
sql += " AND AP_APP.APP_CATEGORY ";
sql += "= ?";
}
if (filter.getAppName() != null && !filter.getAppName().isEmpty()) {
sql += " AND LOWER (AP_APP.NAME) "; sql += " AND LOWER (AP_APP.NAME) ";
if (filter.isFullMatch()) { if (filter.isFullMatch()) {
sql += "= ?"; sql += "= ?";
@ -174,10 +181,13 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
stmt.setInt(paramIndex++, tenantId); stmt.setInt(paramIndex++, tenantId);
stmt.setString(paramIndex++, AppLifecycleState.REMOVED.toString()); stmt.setString(paramIndex++, AppLifecycleState.REMOVED.toString());
if (filter.getAppType() != null) { if (filter.getAppType() != null && !filter.getAppType().isEmpty()) {
stmt.setString(paramIndex++, filter.getAppType()); stmt.setString(paramIndex++, filter.getAppType());
} }
if (filter.getAppName() != null) { if (filter.getAppCategory() != null && !filter.getAppCategory().isEmpty()) {
stmt.setString(paramIndex++, filter.getAppCategory());
}
if (filter.getAppName() != null && !filter.getAppName().isEmpty()) {
if (filter.isFullMatch()) { if (filter.isFullMatch()) {
stmt.setString(paramIndex++, filter.getAppName().toLowerCase()); stmt.setString(paramIndex++, filter.getAppName().toLowerCase());
} else { } else {
@ -337,6 +347,48 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public Application getApplicationById(String id, int tenantId) throws
ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting application with the id:" + id);
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
String sql =
"SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY "
+ "AS APP_CATEGORY, AP_APP.SUB_TYPE AS SUB_TYPE ,AP_APP.CURRENCY AS CURRENCY,"
+ " AP_APP.RESTRICTED AS RESTRICTED, AP_APP_TAG.TAG AS APP_TAG, AP_UNRESTRICTED_ROLE.ROLE "
+ "AS ROLE FROM AP_APP, AP_APP_TAG, AP_UNRESTRICTED_ROLE WHERE AP_APP.NAME=? AND "
+ "AP_APP.APP_ID= ? AND AP_APP.TENANT_ID=?;";
stmt = conn.prepareStatement(sql);
stmt.setString(1, id);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved basic details of the application with the id:" + id);
}
return Util.loadApplication(rs);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred while getting application details with app id " + id +
" While executing query ", e);
} catch (JSONException e) {
throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e);
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override @Override
public Application getApplicationById(int applicationId, int tenantId) throws public Application getApplicationById(int applicationId, int tenantId) throws
ApplicationManagementDAOException { ApplicationManagementDAOException {
@ -382,7 +434,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementDAOException { public boolean verifyApplicationExistenceById(int appId, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application with the application ID(" + appId + " ) from the database"); log.debug("Getting application with the application ID(" + appId + " ) from the database");
} }
@ -392,13 +444,11 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = String sql =
"SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY " "SELECT AP_APP.ID AS APP_ID FROM AP_APP WHERE AP_APP.ID = ? AND AP_APP.TENANT_ID=?;";
+ "AS APP_CATEGORY, AP_APP.SUB_TYPE AS SUB_TYPE, AP_APP_TAG.TAG AS TAG, "
+ "AP_UNRESTRICTED_ROLE.ROLE AS ROLE FROM AP_APP, AP_APP_TAG, AP_UNRESTRICTED_ROLE "
+ "WHERE AP_APP.ID = ?;";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, appId); stmt.setInt(1, appId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {

@ -21,22 +21,18 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.application.release
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.JSONException;
import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease; import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.Rating; import org.wso2.carbon.device.application.mgt.common.Rating;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util; 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.dao.impl.application.GenericApplicationDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.sql.Connection; import java.sql.Connection;
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.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -47,30 +43,26 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
private static final Log log = LogFactory.getLog(GenericApplicationReleaseDAOImpl.class); private static final Log log = LogFactory.getLog(GenericApplicationReleaseDAOImpl.class);
/** /**
* To insert the Application Release Details. * To insert the Application Release Details.
* *
* @param appId Id of the application * @param appId Id of the application
* @param applicationRelease Application Release the properties of which that need to be inserted. * @param applicationRelease Application Release the properties of which that need to be inserted.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override public ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId, int tenantId)
public ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId, int tenantId) throws throws ApplicationManagementDAOException {
ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
String sql = "INSERT INTO AP_APP_RELEASE (VERSION,TENANT_ID,UUID,RELEASE_TYPE, PACKAGE_NAME, APP_PRICE," String sql = "INSERT INTO AP_APP_RELEASE (VERSION,TENANT_ID,UUID,RELEASE_TYPE, PACKAGE_NAME, APP_PRICE,"
+ "STORED_LOCATION,ICON_LOCATION, BANNER_LOCATION, SC_1_LOCATION,SC_2_LOCATION,SC_3_LOCATION, " + + "STORED_LOCATION, BANNER_LOCATION, SC_1_LOCATION,SC_2_LOCATION,SC_3_LOCATION, APP_HASH_VALUE,"
"APP_HASH_VALUE," + "SHARED_WITH_ALL_TENANTS, APP_META_INFO,AP_APP_ID) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
+ "SHARED_WITH_ALL_TENANTS, APP_META_INFO,CREATED_BY,AP_APP_ID) "
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?);";
int index = 0; int index = 0;
String generatedColumns[] = {"ID"}; String generatedColumns[] = { "ID" };
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql, generatedColumns); statement = connection.prepareStatement(sql, generatedColumns);
@ -89,7 +81,6 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
statement.setString(++index, applicationRelease.getAppHashValue()); statement.setString(++index, applicationRelease.getAppHashValue());
statement.setInt(++index, applicationRelease.getIsSharedWithAllTenants()); statement.setInt(++index, applicationRelease.getIsSharedWithAllTenants());
statement.setString(++index, applicationRelease.getMetaData()); statement.setString(++index, applicationRelease.getMetaData());
statement.setString(++index, applicationRelease.getApplicationCreator());
statement.setInt(++index, appId); statement.setInt(++index, appId);
statement.executeUpdate(); statement.executeUpdate();
resultSet = statement.getGeneratedKeys(); resultSet = statement.getGeneratedKeys();
@ -102,39 +93,37 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
"SQL Exception while trying to release an application by executing the query " + sql, e); "SQL Exception while trying to release an application by executing the query " + sql, e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Database Connection Exception while trying to release a new version" , e); "Database Connection Exception while trying to release a new version", e);
} finally { } finally {
Util.cleanupResources(statement, resultSet); Util.cleanupResources(statement, resultSet);
} }
} }
/** /**
* To get release details of a specific application. * To get latest updated app release details of a specific application.
* *
* @param applicationName Name of the application. * @param applicationName Name of the application.
* @param applicationType Type of the application. * @param applicationType Type of the application.
* @param versionName version name of the application. * @param versionName version name of the application.
* @param releaseType type of the application release. * @param releaseType type of the application release.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override public ApplicationRelease getRelease(String applicationName, String applicationType, String versionName,
public ApplicationRelease getRelease(String applicationName, String applicationType, String versionName,
String releaseType, int tenantId) throws ApplicationManagementDAOException { String releaseType, int tenantId) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
String sql = "SELECT AR.ID AS RELEASE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR.RELEASE_TYPE, " String sql = "SELECT AR.ID AS RELEASE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID AS UUID, AR.RELEASE_TYPE AS "
+ "AR.PACKAGE_NAME AS PACKAGE_NAME, AR.APP_PRICE, AR.STORED_LOCATION, AR.BANNER_LOCATION, " + "RELEASE_TYPE, AR.PACKAGE_NAME AS PACKAGE_NAME, AR.APP_PRICE AS APP_PRICE, AR.STORED_LOCATION AS "
+ "AR.SC_1_LOCATION AS SCREEN_SHOT_1, AR.SC_2_LOCATION AS SCREEN_SHOT_2, AR.SC_3_LOCATION AS " + "STORED_LOCATION, AR.BANNER_LOCATION AS BANNER_LOCATION, AR.SC_1_LOCATION AS SCREEN_SHOT_1, "
+ "SCREEN_SHOT_3, AR.APP_HASH_VALUE AS HASH_VALUE, AR.SHARED_WITH_ALL_TENANTS AS SHARED, " + "AR.SC_2_LOCATION AS SCREEN_SHOT_2, AR.SC_3_LOCATION AS SCREEN_SHOT_3, AR.APP_HASH_VALUE AS "
+ "AR.APP_META_INFO, AR.CREATED_BY, AR.CREATED_AT, AR.PUBLISHED_BY, AR.PUBLISHED_AT, AR.STARS, " + "HASH_VALUE, AR.SHARED_WITH_ALL_TENANTS AS SHARED, AR.APP_META_INFO AS APP_META_INFO , "
+ "AL.CURRENT_STATE, AL.PREVIOUSE_STATE, AL.UPDATED_BY, AL.UPDATED_AT FROM " + "AR.RATING AS RATING, AL.CURRENT_STATE, AL.PREVIOUS_STATE, AL.UPDATED_BY, AL.UPDATED_AT FROM "
+ "AP_APP_RELEASE AS AR, AP_APP_LIFECYCLE_STATE AS AL WHERE " + "AP_APP_RELEASE AS AR, AP_APP_LIFECYCLE_STATE AS AL WHERE AR.AP_APP_ID=(SELECT ID FROM AP_APP WHERE "
+ "AR.AP_APP_ID=(SELECT ID FROM AP_APP WHERE NAME=? AND TYPE=? AND TENANT_ID=?) " + "NAME=? AND TYPE=? AND TENANT_ID=?) AND AR.VERSION=? AND AR.RELEASE_TYPE=? AND "
+ "AND AR.VERSION=? AND AR.RELEASE_TYPE=? AND AL.AP_APP_RELEASE_ID=AR.ID " + "AL.AP_APP_RELEASE_ID=AR.ID AND AL.TENANT_ID=AR.TENANT_ID ORDER BY AL.UPDATED_AT DESC;";
+ "AND AL.TENANT_ID=AR.TENANT_ID ORDER BY AL.UPDATED_AT DESC;";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
@ -152,11 +141,10 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
return null; return null;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database connection exception while trying to get the " throw new ApplicationManagementDAOException("Database connection exception while trying to get the "
+ "release details of the application with " + applicationName + " and version " + + "release details of the application with " + applicationName + " and version " + versionName, e);
versionName, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error while getting release details of the application " + throw new ApplicationManagementDAOException(
applicationName + " and version " + versionName + " , while executing the query " + sql, e); "Error while getting release details of the application " + applicationName + " and version " + versionName + " , while executing the query " + sql, e);
} finally { } finally {
Util.cleanupResources(statement, resultSet); Util.cleanupResources(statement, resultSet);
} }
@ -166,25 +154,25 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* To get release details of a specific application. * To get release details of a specific application.
* *
* @param applicationId ID of the application. * @param applicationId ID of the application.
* @param releaseUuid UUID of the application release. * @param releaseUuid UUID of the application release.
* @param tenantId Tenant Id * @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override public ApplicationRelease getReleaseByIds(int applicationId, String releaseUuid, int tenantId)
public ApplicationRelease getReleaseByIds(int applicationId, String releaseUuid, int tenantId) throws throws ApplicationManagementDAOException {
ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
String sql = "SELECT AR.ID AS RELEASE_ID, AR.PACKAGE_NAME, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR" + String sql =
".RELEASE_TYPE, AR.APP_PRICE, AR.STORED_LOCATION, AR.ICON_LOCATION, AR.BANNER_LOCATION, AR" + "SELECT AR.ID AS RELEASE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR.RELEASE_TYPE, AR.APP_PRICE, "
".SC_1_LOCATION AS SCREEN_SHOT_1, AR.SC_2_LOCATION AS SCREEN_SHOT_2, AR.SC_3_LOCATION AS SCREEN_SHOT_3, AR.APP_HASH_VALUE AS " + + "AR.STORED_LOCATION, AR.BANNER_LOCATION, AR.SC_1_LOCATION AS SCREEN_SHOT_1, "
"HASH_VALUE, AR.SHARED_WITH_ALL_TENANTS AS SHARED, AR.APP_META_INFO, AR.CREATED_BY, AR.CREATED_AT, AR" + + "AR.SC_2_LOCATION AS SCREEN_SHOT_2, AR.SC_3_LOCATION AS SCREEN_SHOT_3, AR.PACKAGE_NAME AS "
".PUBLISHED_BY, AR.PUBLISHED_AT, AR.STARS, AL.CURRENT_STATE, AL.PREVIOUSE_STATE, AL.UPDATED_BY, " + + "PACKAGE_NAME, AR.APP_HASH_VALUE AS HASH_VALUE, AR.SHARED_WITH_ALL_TENANTS AS SHARED, "
"AL.UPDATED_AT FROM AP_APP_RELEASE AS AR, AP_APP_LIFECYCLE_STATE AS AL WHERE " + + "AR.APP_META_INFO AS APP_META_INFO, AR.RATING AS RATING, AL.CURRENT_STATE, AL.PREVIOUS_STATE, "
"AR.AP_APP_ID = ? AND AR.UUID = ? AND AR.TENANT_ID = ? AND AL.AP_APP_RELEASE_ID=AR.ID AND " + + "AL.UPDATED_BY, AL.UPDATED_AT FROM AP_APP_RELEASE AS AR, AP_APP_LIFECYCLE_STATE AS AL "
"AL.TENANT_ID = AR.TENANT_ID ORDER BY AL.UPDATED_AT DESC;"; + "WHERE AR.AP_APP_ID = ? AND AR.UUID = ? AND AR.TENANT_ID = ? AND AL.AP_APP_RELEASE_ID=AR.ID "
+ "AND AL.TENANT_ID = AR.TENANT_ID ORDER BY AL.UPDATED_AT DESC;";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
@ -200,14 +188,12 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
return null; return null;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Database connection exception while trying to get the release details of the " + "Database connection exception while trying to get the release details of the " + "application id: "
"application id: " + applicationId + "and UUID of the application release: " + + applicationId + "and UUID of the application release: " + releaseUuid, e);
releaseUuid, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Error while getting release details of the application id: " + applicationId + "Error while getting release details of the application id: " + applicationId
" and theUUID of the application " + + " and theUUID of the application " + "release: " + releaseUuid + " , while executing the query " + sql, e);
"release: " + releaseUuid + " , while executing the query " + sql, e);
} finally { } finally {
Util.cleanupResources(statement, resultSet); Util.cleanupResources(statement, resultSet);
} }
@ -216,62 +202,42 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
/** /**
* To insert the application release properties. * To insert the application release properties.
* *
* @param applicationName Name of the application. * @param applicationId Id of the application.
* @param applicationType Type of the application. * @param tenantId Tenant Id
* @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override public List<ApplicationRelease> getReleases(int applicationId, int tenantId)
public List<ApplicationRelease> getReleases(String applicationName, String applicationType, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
List<ApplicationRelease> applicationReleases = new ArrayList<>(); List<ApplicationRelease> applicationReleases = new ArrayList<>();
String sql = "SELECT AR.ID AS RELESE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR.RELEASE_TYPE, AR.APP_PRICE," String sql = "SELECT AR.ID AS RELEASE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR.RELEASE_TYPE "
+ " AR.STORED_LOCATION, AR.BANNER_LOCATION, AR.SC_1_LOCATION AS SCREEN_SHOT_1, AR.SC_2_LOCATION AS " + "AS RELEASE_TYPE, AR.PACKAGE_NAME AS PACKAGE_NAME, AR.APP_PRICE, AR.STORED_LOCATION, "
+ "SCREEN_SHOT_2, AR.SC_3_LOCATION AS SCREEN_SHOT_3, AR.APP_HASH_VALUE AS HASH_VALUE, " + "AR.BANNER_LOCATION, AR.SC_1_LOCATION AS SCREEN_SHOT_1, AR.SC_2_LOCATION AS SCREEN_SHOT_2, "
+ "AR.SHARED_WITH_ALL_TENANTS AS SHARED, AR.APP_META_INFO, AR.CREATED_BY, AR.CREATED_AT, " + "AR.SC_3_LOCATION AS SCREEN_SHOT_3, AR.APP_HASH_VALUE AS HASH_VALUE, "
+ "AR.PUBLISHED_BY, AR.PUBLISHED_AT, AR.STARS, AR.RATING FROM AP_APP_RELEASE AS " + "AR.SHARED_WITH_ALL_TENANTS AS SHARED, AR.APP_META_INFO AS APP_META_INFO, "
+ "AR where AR.AP_APP_ID=(SELECT ID FROM AP_APP WHERE NAME = ? AND TYPE = ? " + "AR.RATING AS RATING FROM AP_APP_RELEASE AS AR where AR.AP_APP_ID=? AND AR.TENANT_ID = ?;";
+ "AND TENANT_ID = ?) AND AR.TENANT_ID = ? ;";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setString(1, applicationName); statement.setInt(1, applicationId);
statement.setString(2, applicationType); statement.setInt(2, tenantId);
statement.setInt(3, tenantId);
statement.setInt(4, tenantId);
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
ApplicationRelease applicationRelease = new ApplicationRelease(); ApplicationRelease applicationRelease = constructApplicationRelease(resultSet);
applicationRelease.setId(resultSet.getInt("RELESE_ID"));
applicationRelease.setVersion(resultSet.getString("RELEASE_VERSION"));
applicationRelease.setUuid(resultSet.getString("UUID"));
applicationRelease.setReleaseType(resultSet.getString("RELEASE_TYPE"));
applicationRelease.setPrice(resultSet.getDouble("APP_PRICE"));
applicationRelease.setAppStoredLoc(resultSet.getString("STORED_LOCATION"));
applicationRelease.setBannerLoc(resultSet.getString("BANNER_LOCATION"));
applicationRelease.setScreenshotLoc1(resultSet.getString("SCREEN_SHOT_1"));
applicationRelease.setScreenshotLoc2(resultSet.getString("SCREEN_SHOT_2"));
applicationRelease.setScreenshotLoc3(resultSet.getString("SCREEN_SHOT_3"));
applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE"));
applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED"));
applicationRelease.setMetaData(resultSet.getString("APP_META_INFO"));
applicationRelease.setApplicationCreator(resultSet.getString("CREATED_BY"));
applicationRelease.setRating(resultSet.getDouble("RATING"));
applicationReleases.add(applicationRelease); applicationReleases.add(applicationRelease);
} }
return applicationReleases; return applicationReleases;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database connection exception while trying to get the " throw new ApplicationManagementDAOException("Database connection exception while trying to get the "
+ "release details of the application with Name " + applicationName, e); + "release details of the application with app ID: " + applicationId, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Error while getting all the release details of the " + applicationName + " application" "Error while getting all the release details of the app ID: " + applicationId
+ ", while executing the query " + sql, e); + ", while executing the query " + sql, e);
} finally { } finally {
Util.cleanupResources(statement, resultSet); Util.cleanupResources(statement, resultSet);
@ -318,7 +284,6 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE")); applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE"));
applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED")); applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED"));
applicationRelease.setMetaData(resultSet.getString("APP_META_INFO")); applicationRelease.setMetaData(resultSet.getString("APP_META_INFO"));
applicationRelease.setApplicationCreator(resultSet.getString("CREATED_BY"));
applicationRelease.setRating(resultSet.getDouble("RATING")); applicationRelease.setRating(resultSet.getDouble("RATING"));
applicationReleases.add(applicationRelease); applicationReleases.add(applicationRelease);
} }
@ -338,15 +303,15 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
/** /**
* To Update starts of an application release. * To Update starts of an application release.
* *
* @param uuid UUID of the application Release. * @param uuid UUID of the application Release.
* @param rating given stars for the application release. * @param rating given stars for the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override public void updateRatingValue(String uuid, double rating, int ratedUsers)
public void updateRatingValue(String uuid, double rating, int ratedUsers) throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
String sql = "UPDATE AP_APP_RELEASE SET RATING = ? AND RATED_USERS = ? WHERE UUID = ?;"; String sql = "UPDATE AP_APP_RELEASE SET RATING = ?,RATED_USERS = ? WHERE UUID = ?;";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
@ -371,8 +336,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* @param uuid UUID of the application Release. * @param uuid UUID of the application Release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override public Rating getRating(String uuid, int tenantId) throws ApplicationManagementDAOException {
public Rating getRating(String uuid, int tenantId) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
@ -385,7 +349,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
statement.setInt(2, tenantId); statement.setInt(2, tenantId);
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
if (resultSet.next()){ if (resultSet.next()) {
rating = new Rating(); rating = new Rating();
rating.setRatingValue(resultSet.getDouble("RATING")); rating.setRatingValue(resultSet.getDouble("RATING"));
rating.setNoOfUsers(resultSet.getInt("RATED_USERS")); rating.setNoOfUsers(resultSet.getInt("RATED_USERS"));
@ -408,18 +372,14 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
* @param applicationRelease Application Release the properties of which that need to be inserted. * @param applicationRelease Application Release the properties of which that need to be inserted.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override public ApplicationRelease updateRelease(int applicationId, ApplicationRelease applicationRelease, int tenantId)
public ApplicationRelease updateRelease(int applicationId, ApplicationRelease applicationRelease, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
String sql = String sql = "UPDATE AP_APP_RELEASE SET VERSION = ?, UUID = ?, RELEASE_TYPE = ?, PACKAGE_NAME = ?,"
"UPDATE AP_APP_RELEASE " + + " APP_PRICE = ?, STORED_LOCATION = ?, BANNER_LOCATION = ?, SC_1_LOCATION = ?, SC_2_LOCATION = ?,"
"SET VERSION = ? , UUID = ? , RELEASE_TYPE = ? , PACKAGE_NAME = ? " + + " SC_3_LOCATION = ?, APP_HASH_VALUE = ?, SHARED_WITH_ALL_TENANTS = ?, APP_META_INFO = ? "
", APP_PRICE = ? , STORED_LOCATION = ? , ICON_LOCATION = ? , BANNER_LOCATION = ? , " + + "WHERE AP_APP_ID = ? AND TENANT_ID = ? AND ID = ?;";
"SC_1_LOCATION = ? , SC_2_LOCATION = ? , SC_3_LOCATION = ? , APP_HASH_VALUE = ? " +
", SHARED_WITH_ALL_TENANTS = ? , APP_META_INFO = ? " +
"WHERE AP_APP_ID = ? AND TENANT_ID = ? AND ID = ?;";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
@ -429,17 +389,16 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
statement.setString(4, applicationRelease.getPackageName()); statement.setString(4, applicationRelease.getPackageName());
statement.setDouble(5, applicationRelease.getPrice()); statement.setDouble(5, applicationRelease.getPrice());
statement.setString(6, applicationRelease.getAppStoredLoc()); statement.setString(6, applicationRelease.getAppStoredLoc());
statement.setString(7, applicationRelease.getIconLoc()); statement.setString(7, applicationRelease.getBannerLoc());
statement.setString(8, applicationRelease.getBannerLoc()); statement.setString(8, applicationRelease.getScreenshotLoc1());
statement.setString(9, applicationRelease.getScreenshotLoc1()); statement.setString(9, applicationRelease.getScreenshotLoc2());
statement.setString(10, applicationRelease.getScreenshotLoc2()); statement.setString(10, applicationRelease.getScreenshotLoc3());
statement.setString(11, applicationRelease.getScreenshotLoc3()); statement.setString(11, applicationRelease.getAppHashValue());
statement.setString(12, applicationRelease.getAppHashValue()); statement.setInt(12, applicationRelease.getIsSharedWithAllTenants());
statement.setInt(13, applicationRelease.getIsSharedWithAllTenants()); statement.setString(13, applicationRelease.getMetaData());
statement.setString(14, applicationRelease.getMetaData()); statement.setInt(14, applicationId);
statement.setInt(15, applicationId); statement.setInt(15, tenantId);
statement.setInt(16, tenantId); statement.setInt(16, applicationRelease.getId());
statement.setInt(17, applicationRelease.getId());
statement.executeUpdate(); statement.executeUpdate();
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
@ -456,12 +415,11 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
/** /**
* To delete an application release. * To delete an application release.
* *
* @param id Id of the application Release. * @param id Id of the application Release.
* @param version version name of the application release. * @param version version name of the application release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
@Override @Override public void deleteRelease(int id, String version) throws ApplicationManagementDAOException {
public void deleteRelease(int id, String version) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
String sql = "DELETE FROM AP_APP_RELEASE WHERE ID = ? AND VERSION = ?"; String sql = "DELETE FROM AP_APP_RELEASE WHERE ID = ? AND VERSION = ?";
@ -483,8 +441,46 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
} }
} }
@Override
public boolean verifyReleaseExistence(int appId, String uuid, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Verifying application release existence by application id:" + appId
+ " and application release uuid: " + uuid);
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
String sql =
"SELECT AR.ID AS RELEASE_ID FROM AP_APP_RELEASE AS AR WHERE AR.AP_APP_ID = ? AND AR.UUID = ? AND "
+ "AR.TENANT_ID = ?;";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, appId);
stmt.setString(2, uuid);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved basic details of the application release with the application ID "
+ appId + " Application release uuid: " + uuid);
}
return rs.next();
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred while getting application release details with app ID: " + appId
+ " App release uuid: " + uuid + " While executing query ", e);
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
/** /**
* This method is capable to construct {@link ApplicationRelease} and return the object * This method is capable to construct {@link ApplicationRelease} and return the object
*
* @param resultSet result set obtained from the query executing. * @param resultSet result set obtained from the query executing.
* @throws SQLException SQL exception while accessing result set data. * @throws SQLException SQL exception while accessing result set data.
*/ */
@ -505,9 +501,7 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE")); applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE"));
applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED")); applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED"));
applicationRelease.setMetaData(resultSet.getString("APP_META_INFO")); applicationRelease.setMetaData(resultSet.getString("APP_META_INFO"));
applicationRelease.setApplicationCreator(resultSet.getString("CREATED_BY")); applicationRelease.setRating(resultSet.getDouble("RATING"));
return applicationRelease; return applicationRelease;
} }
}
}

@ -23,7 +23,6 @@ import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionExcep
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO; import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util; import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
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.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.sql.Connection; import java.sql.Connection;
@ -39,41 +38,57 @@ import java.util.List;
public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements LifecycleStateDAO { public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements LifecycleStateDAO {
@Override @Override
public LifecycleState getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws ApplicationManagementDAOException { public LifecycleState getLatestLifeCycleStateByReleaseID(int applicationReleaseId) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = "SELECT ID, CURRENT_STATE, PREVIOUSE_STATE, TENANT_ID, UPDATED_AT, UPDATED_BY FROM " String sql = "SELECT ID, CURRENT_STATE, PREVIOUS_STATE, TENANT_ID, UPDATED_AT, UPDATED_BY FROM "
+ "AP_APP_LIFECYCLE_STATE WHERE AP_APP_RELEASE_ID=? ORDER BY UPDATED_AT DESC;"; + "AP_APP_LIFECYCLE_STATE WHERE AP_APP_RELEASE_ID=? ORDER BY UPDATED_AT DESC;";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, applicationReleaseId); stmt.setInt(1, applicationReleaseId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
LifecycleState lifecycleState = null; return constructLifecycle(rs);
} catch (SQLException e) {
throw new LifeCycleManagementDAOException("Error occurred while getting application List", e);
} catch (DBConnectionException e) {
throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection to get latest"
+ " lifecycle state for a specific application", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
if (rs.next()) { public LifecycleState getLatestLifeCycleState(int appId, String uuid) throws LifeCycleManagementDAOException{
lifecycleState = new LifecycleState(); Connection conn = null;
lifecycleState.setId(rs.getInt("ID")); PreparedStatement stmt = null;
lifecycleState.setCurrentState(rs.getString("CURRENT_STATE")); ResultSet rs = null;
lifecycleState.setPreviousState(rs.getString("PREVIOUSE_STATE")); try {
lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT")); conn = this.getDBConnection();
lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY")); String sql = "SELECT ID, CURRENT_STATE, PREVIOUS_STATE, TENANT_ID, UPDATED_AT, UPDATED_BY FROM "
} + "AP_APP_LIFECYCLE_STATE WHERE AP_APP_ID=? AND AP_APP_RELEASE_ID=(SELECT ID FROM AP_APP_RELEASE "
return lifecycleState; + "WHERE UUID=?) ORDER BY UPDATED_AT DESC;";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, appId);
stmt.setString(2, uuid);
rs = stmt.executeQuery();
return constructLifecycle(rs);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while getting application List", e); throw new LifeCycleManagementDAOException("Error occurred while getting application List", e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection to get latest" throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection to get latest"
+ " lifecycle state for a specific application", e); + " lifecycle state for a specific application", e);
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public List<LifecycleState> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException { public List<LifecycleState> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException {
List<LifecycleState> lifecycleStates = new ArrayList<>(); List<LifecycleState> lifecycleStates = new ArrayList<>();
@ -82,7 +97,7 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
ResultSet rs = null; ResultSet rs = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = "SELECT ID, CURRENT_STATE, PREVIOUSE_STATE, TENANT_ID, UPDATED_AT, UPDATED_BY FROM " String sql = "SELECT ID, CURRENT_STATE, PREVIOUS_STATE, TENANT_ID, UPDATED_AT, UPDATED_BY FROM "
+ "AP_APP_LIFECYCLE_STATE WHERE AP_APP_RELEASE_ID = ? ORDER BY UPDATED_AT ASC;"; + "AP_APP_LIFECYCLE_STATE WHERE AP_APP_RELEASE_ID = ? ORDER BY UPDATED_AT ASC;";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1,appReleaseId); stmt.setInt(1,appReleaseId);
@ -91,7 +106,7 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
LifecycleState lifecycleState = new LifecycleState(); LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setId(rs.getInt("ID")); lifecycleState.setId(rs.getInt("ID"));
lifecycleState.setCurrentState(rs.getString("CURRENT_STATE")); lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
lifecycleState.setPreviousState(rs.getString("PREVIOUSE_STATE")); lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE"));
lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT")); lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT"));
lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY")); lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY"));
lifecycleStates.add(lifecycleState); lifecycleStates.add(lifecycleState);
@ -108,19 +123,19 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
} }
@Override @Override
public void addLifecycleState(LifecycleState state, int appId, int releaseId, int tenantId) throws LifeCycleManagementDAOException { public void addLifecycleState(LifecycleState state, int appId, String uuid, int tenantId) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
String sql = "INSERT INTO AP_APP_LIFECYCLE_STATE (CURRENT_STATE, PREVIOUSE_STATE, TENANT_ID, UPDATED_BY, " String sql = "INSERT INTO AP_APP_LIFECYCLE_STATE (CURRENT_STATE, PREVIOUS_STATE, TENANT_ID, UPDATED_BY, "
+ "AP_APP_RELEASE_ID, AP_APP_ID) VALUES (?,?, ?, ?,?,?);"; + "AP_APP_RELEASE_ID, AP_APP_ID) VALUES (?,?, ?, ?,(SELECT ID FROM AP_APP_RELEASE WHERE UUID=?),?);";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, state.getCurrentState()); stmt.setString(1, state.getCurrentState().toUpperCase());
stmt.setString(2, state.getPreviousState()); stmt.setString(2, state.getPreviousState().toUpperCase());
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.setString(4, state.getUpdatedBy()); stmt.setString(4, state.getUpdatedBy());
stmt.setInt(5, releaseId); stmt.setString(5, uuid);
stmt.setInt(6, appId); stmt.setInt(6, appId);
stmt.executeUpdate(); stmt.executeUpdate();
@ -153,4 +168,22 @@ public class GenericLifecycleStateDAOImpl extends AbstractDAOImpl implements Lif
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
private LifecycleState constructLifecycle(ResultSet rs) throws LifeCycleManagementDAOException {
LifecycleState lifecycleState = null;
try {
if (rs !=null && rs.next()) {
lifecycleState = new LifecycleState();
lifecycleState.setId(rs.getInt("ID"));
lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
lifecycleState.setPreviousState(rs.getString("PREVIOUS_STATE"));
lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT"));
lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY"));
}
} catch (SQLException e) {
throw new LifeCycleManagementDAOException(
"Error occurred while construct lifecycle state by retrieving data from SQL query", e);
}
return lifecycleState;
}
} }

@ -35,7 +35,6 @@ import org.wso2.carbon.device.application.mgt.common.Tag;
import org.wso2.carbon.device.application.mgt.common.UnrestrictedRole; import org.wso2.carbon.device.application.mgt.common.UnrestrictedRole;
import org.wso2.carbon.device.application.mgt.common.User; import org.wso2.carbon.device.application.mgt.common.User;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException; import org.wso2.carbon.device.application.mgt.common.exception.RequestValidatingException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
@ -54,7 +53,7 @@ import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger; import org.wso2.carbon.device.application.mgt.core.lifecycle.LifecycleStateManger;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
@ -72,7 +71,6 @@ import java.util.List;
public class ApplicationManagerImpl implements ApplicationManager { public class ApplicationManagerImpl implements ApplicationManager {
private static final Log log = LogFactory.getLog(ApplicationManagerImpl.class); private static final Log log = LogFactory.getLog(ApplicationManagerImpl.class);
private DeviceTypeDAO deviceTypeDAO;
private VisibilityDAO visibilityDAO; private VisibilityDAO visibilityDAO;
private ApplicationDAO applicationDAO; private ApplicationDAO applicationDAO;
private ApplicationReleaseDAO applicationReleaseDAO; private ApplicationReleaseDAO applicationReleaseDAO;
@ -86,7 +84,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
private void initDataAccessObjects() { private void initDataAccessObjects() {
this.deviceTypeDAO = ApplicationManagementDAOFactory.getDeviceTypeDAO();
this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO(); this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO(); this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
this.lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO(); this.lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
@ -102,7 +99,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.debug("Create Application received for the tenant : " + tenantId + " From" + " the user : " + userName); log.debug("Create Application received for the tenant : " + tenantId + " From" + " the user : " + userName);
} }
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
validateAppCreatingRequest(application); validateAppCreatingRequest(application);
validateAppReleasePayload(application.getApplicationReleases().get(0)); validateAppReleasePayload(application.getApplicationReleases().get(0));
@ -169,8 +165,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
LifecycleState lifecycleState = new LifecycleState(); LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setCurrentState(AppLifecycleState.CREATED.toString()); lifecycleState.setCurrentState(AppLifecycleState.CREATED.toString());
lifecycleState.setPreviousState(AppLifecycleState.CREATED.toString()); lifecycleState.setPreviousState(AppLifecycleState.CREATED.toString());
changeLifecycleState(appId, applicationRelease.getUuid(), lifecycleState, false, changeLifecycleState(appId, applicationRelease.getUuid(), lifecycleState, false);
applicationRelease.getId());
applicationRelease.setLifecycleState(lifecycleState); applicationRelease.setLifecycleState(lifecycleState);
applicationReleases.add(applicationRelease); applicationReleases.add(applicationRelease);
@ -217,13 +212,13 @@ public class ApplicationManagerImpl implements ApplicationManager {
try { try {
ConnectionManagerUtil.getDBConnection(); ConnectionManagerUtil.getDBConnection();
applicationList = applicationDAO.getApplications(filter, tenantId); applicationList = applicationDAO.getApplications(filter, tenantId);
if(applicationList != null && applicationList.getApplications() != null && applicationList if(applicationList != null && applicationList.getApplications() != null && !applicationList
.getApplications().size() > 0) { .getApplications().isEmpty()) {
if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
applicationList = getRoleRestrictedApplicationList(applicationList, userName); applicationList = getRoleRestrictedApplicationList(applicationList, userName);
} }
for (Application application : applicationList.getApplications()) { for (Application application : applicationList.getApplications()) {
applicationReleases = getReleases(application.getId()); applicationReleases = getReleases(application, filter.isRequirePublishedRelease());
application.setApplicationReleases(applicationReleases); application.setApplicationReleases(applicationReleases);
} }
} }
@ -254,7 +249,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
LifecycleState lifecycleState = new LifecycleState(); LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setCurrentState(AppLifecycleState.CREATED.toString()); lifecycleState.setCurrentState(AppLifecycleState.CREATED.toString());
lifecycleState.setPreviousState(AppLifecycleState.CREATED.toString()); lifecycleState.setPreviousState(AppLifecycleState.CREATED.toString());
changeLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState, true, 0); changeLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState, true);
ConnectionManagerUtil.commitDBTransaction(); ConnectionManagerUtil.commitDBTransaction();
return applicationRelease; return applicationRelease;
@ -309,7 +304,6 @@ public class ApplicationManagerImpl implements ApplicationManager {
if (!isAppAllowed) { if (!isAppAllowed) {
return null; return null;
} }
if (state != null) { if (state != null) {
applicationReleases = getReleaseInState(appId, state); applicationReleases = getReleaseInState(appId, state);
} }
@ -358,10 +352,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
List<ApplicationRelease> applicationReleases; List<ApplicationRelease> applicationReleases;
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
application = ApplicationManagementDAOFactory.getApplicationDAO() application = this.applicationDAO.getApplication(appName, appType, tenantId);
.getApplication(appName, appType, tenantId);
if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
applicationReleases = getReleases(application.getId()); applicationReleases = getReleases(application, false);
application.setApplicationReleases(applicationReleases); application.setApplicationReleases(applicationReleases);
return application; return application;
} }
@ -378,7 +371,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
return null; return null;
} }
applicationReleases = getReleases(application.getId()); applicationReleases = getReleases(application, false);
application.setApplicationReleases(applicationReleases); application.setApplicationReleases(applicationReleases);
return application; return application;
} catch (UserStoreException e) { } catch (UserStoreException e) {
@ -396,8 +389,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
Application application; Application application;
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
application = ApplicationManagementDAOFactory.getApplicationDAO() application = this.applicationDAO.getApplicationByRelease(appReleaseUUID, tenantId);
.getApplicationByRelease(appReleaseUUID, tenantId);
if (application.getUnrestrictedRoles().isEmpty() || isRoleExists(application.getUnrestrictedRoles(), if (application.getUnrestrictedRoles().isEmpty() || isRoleExists(application.getUnrestrictedRoles(),
userName)) { userName)) {
@ -412,11 +404,12 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
public Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException { public boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException {
try { try {
Boolean isAppExist; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
boolean isAppExist;
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
isAppExist = ApplicationManagementDAOFactory.getApplicationDAO().verifyApplicationExistenceById(appId); isAppExist = this.applicationDAO.verifyApplicationExistenceById(appId, tenantId);
return isAppExist; return isAppExist;
} finally { } finally {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
@ -433,11 +426,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
@Override private List<ApplicationRelease> getReleases(Application application, boolean requirePublishedRelease)
public List<ApplicationRelease> getReleases(int applicationId) throws ApplicationManagementException { throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
Application application = getApplicationIfAccessible(applicationId);
List<ApplicationRelease> applicationReleases; List<ApplicationRelease> applicationReleases;
List<ApplicationRelease> filteredApplicationReleases = new ArrayList<>(); List<ApplicationRelease> filteredApplicationReleases = new ArrayList<>();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -445,23 +436,44 @@ public class ApplicationManagerImpl implements ApplicationManager {
.toString()); .toString());
} }
ConnectionManagerUtil.getDBConnection(); ConnectionManagerUtil.getDBConnection();
applicationReleases = this.applicationReleaseDAO.getReleases(application.getName(), application.getType(), tenantId); applicationReleases = this.applicationReleaseDAO.getReleases(application.getId(), tenantId);
for (ApplicationRelease applicationRelease : applicationReleases) { for (ApplicationRelease applicationRelease : applicationReleases) {
LifecycleState lifecycleState = ApplicationManagementDAOFactory.getLifecycleStateDAO(). LifecycleState lifecycleState = null;
getLatestLifeCycleStateByReleaseID(applicationRelease.getId()); try {
lifecycleState = ApplicationManagementDAOFactory.getLifecycleStateDAO().
getLatestLifeCycleStateByReleaseID(applicationRelease.getId());
} catch (LifeCycleManagementDAOException e) {
throw new ApplicationManagementException(
"Error occurred while getting the latest lifecycle state for the application release UUID: "
+ applicationRelease.getUuid(), e);
}
if (lifecycleState != null) { if (lifecycleState != null) {
applicationRelease.setLifecycleState(lifecycleState); applicationRelease.setLifecycleState(lifecycleState);
if (!AppLifecycleState.REMOVED.toString() if (!AppLifecycleState.REMOVED.toString()
.equals(applicationRelease.getLifecycleState().getCurrentState())) { .equals(applicationRelease.getLifecycleState().getCurrentState())) {
filteredApplicationReleases.add(applicationRelease); if (requirePublishedRelease){
if (AppLifecycleState.PUBLISHED.toString()
.equals(applicationRelease.getLifecycleState().getCurrentState())){
filteredApplicationReleases.add(applicationRelease);
}
}else{
filteredApplicationReleases.add(applicationRelease);
}
} }
} }
} }
if (requirePublishedRelease && filteredApplicationReleases.size() > 1) {
log.error("There are more than one published application releases for application ID: " + application
.getId());
}
return filteredApplicationReleases; return filteredApplicationReleases;
} }
@Override @Override
public List<ApplicationRelease> getReleaseInState(int applicationId, String state) throws public List<ApplicationRelease> getReleaseInState(int applicationId, String state) throws
ApplicationManagementException { ApplicationManagementException {
@ -481,6 +493,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
List<String> storedLocations = new ArrayList<>(); List<String> storedLocations = new ArrayList<>();
Application application;
try { try {
if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
@ -489,10 +502,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
"need to have admin permission"); "need to have admin permission");
} }
if (getApplicationIfAccessible(applicationId) == null) { application = getApplicationIfAccessible(applicationId);
if ( application == null) {
throw new ApplicationManagementException("Invalid Application"); throw new ApplicationManagementException("Invalid Application");
} }
List<ApplicationRelease> applicationReleases = getReleases(applicationId); List<ApplicationRelease> applicationReleases = getReleases(application, false);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Request is received to delete applications which are related with the application id " + log.debug("Request is received to delete applications which are related with the application id " +
applicationId); applicationId);
@ -502,11 +516,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
LifecycleState newAppLifecycleState = new LifecycleState(); LifecycleState newAppLifecycleState = new LifecycleState();
newAppLifecycleState.setPreviousState(appLifecycleState.getCurrentState()); newAppLifecycleState.setPreviousState(appLifecycleState.getCurrentState());
newAppLifecycleState.setCurrentState(AppLifecycleState.REMOVED.toString()); newAppLifecycleState.setCurrentState(AppLifecycleState.REMOVED.toString());
changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState, true, 0); changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState, true);
storedLocations.add(applicationRelease.getAppHashValue()); storedLocations.add(applicationRelease.getAppHashValue());
} }
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
ApplicationManagementDAOFactory.getApplicationDAO().deleteApplication(applicationId); this.applicationDAO.deleteApplication(applicationId);
} catch (UserStoreException e) { } catch (UserStoreException e) {
String msg = "Error occured while check whether current user has the permission to delete an application"; String msg = "Error occured while check whether current user has the permission to delete an application";
log.error(msg); log.error(msg);
@ -533,7 +547,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
LifecycleState newAppLifecycleState = new LifecycleState(); LifecycleState newAppLifecycleState = new LifecycleState();
newAppLifecycleState.setPreviousState(appLifecycleState.getCurrentState()); newAppLifecycleState.setPreviousState(appLifecycleState.getCurrentState());
newAppLifecycleState.setCurrentState(AppLifecycleState.REMOVED.toString()); newAppLifecycleState.setCurrentState(AppLifecycleState.REMOVED.toString());
changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState, true, 0); changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState, true);
}else{ }else{
throw new ApplicationManagementException("Can't delete the application release, You have to move the " + throw new ApplicationManagementException("Can't delete the application release, You have to move the " +
"lifecycle state from "+ currentState + " to acceptable " + "lifecycle state from "+ currentState + " to acceptable " +
@ -640,8 +654,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
Application application; Application application;
boolean isAppAllowed = false; boolean isAppAllowed = false;
try { try {
application = ApplicationManagementDAOFactory.getApplicationDAO() application = this.applicationDAO.getApplicationById(applicationId, tenantId);
.getApplicationById(applicationId, tenantId);
if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) { if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
return application; return application;
} }
@ -812,57 +825,72 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
@Override @Override
public LifecycleState getLifecycleState(int applicationId, String applicationUuid) throws public LifecycleState getLifecycleState(int applicationId, String releaseUuid) throws
ApplicationManagementException { ApplicationManagementException {
LifecycleState lifecycleState; LifecycleState lifecycleState;
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
lifecycleState = this.lifecycleStateDAO.getLatestLifeCycleStateByReleaseID(applicationId); lifecycleState = this.lifecycleStateDAO.getLatestLifeCycleState(applicationId, releaseUuid);
if (lifecycleState == null) { if (lifecycleState == null) {
throw new NotFoundException( throw new NotFoundException(
"Couldn't find the lifecycle data for appid: " + applicationId + " and app release UUID: " "Couldn't find the lifecycle data for appid: " + applicationId + " and app release UUID: "
+ applicationUuid); + releaseUuid);
} }
lifecycleState.setNextStates(new ArrayList<>(lifecycleStateManger. lifecycleState.setNextStates(new ArrayList<>(getLifecycleManagementService().
getNextLifecycleStates(lifecycleState.getCurrentState()))); getNextLifecycleStates(lifecycleState.getCurrentState())));
} catch (ApplicationManagementDAOException e) {
throw new ApplicationManagementException("Failed to get lifecycle state", e);
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
throw new ApplicationManagementException("Failed to get application and application management", e); throw new ApplicationManagementException("Failed to get application and application management", e);
} catch (LifeCycleManagementDAOException e) {
throw new ApplicationManagementException("Failed to get lifecycle state from database", e);
} }
return lifecycleState; return lifecycleState;
} }
@Override @Override
public void changeLifecycleState(int applicationId, String applicationUuid, LifecycleState state, Boolean public void changeLifecycleState(int applicationId, String releaseUuid, LifecycleState state, Boolean checkExist)
checkExist, int releaseId) throws ApplicationManagementException { throws ApplicationManagementException {
try { try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (checkExist) { if (checkExist) {
getApplicationIfAccessible(applicationId); ConnectionManagerUtil.openDBConnection();
} if (!this.applicationDAO.verifyApplicationExistenceById(applicationId, tenantId)){
if (releaseId < 1) { throw new NotFoundException(
releaseId = getAppReleaseIfExists(applicationId, applicationUuid).getId(); "Couldn't found application for the application Id: " + applicationId);
}
if (!this.applicationReleaseDAO.verifyReleaseExistence(applicationId, releaseUuid, tenantId)){
throw new NotFoundException(
"Couldn't found application release for the application Id: " + applicationId
+ " application release uuid: " + releaseUuid);
}
} }
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
state.setUpdatedBy(userName); state.setUpdatedBy(userName);
if (state.getCurrentState() != null && state.getPreviousState() != null) { if (state.getCurrentState() != null && state.getPreviousState() != null) {
if (getLifecycleManagementService()
if (getLifecycleManagementService().isValidStateChange(state.getPreviousState(), state.getCurrentState())) { .isValidStateChange(state.getPreviousState(), state.getCurrentState())) {
this.lifecycleStateDAO ConnectionManagerUtil.beginDBTransaction();
.addLifecycleState(state, applicationId, releaseId, tenantId); //todo if current state of the adding lifecycle state is PUBLISHED, need to check whether is there
//todo any other application release in PUBLISHED state for the application( i.e for the appid)
this.lifecycleStateDAO.addLifecycleState(state, applicationId, releaseUuid, tenantId);
ConnectionManagerUtil.commitDBTransaction();
} else { } else {
log.error("Invalid lifecycle state transition from '" + state.getPreviousState() + "'" log.error("Invalid lifecycle state transition from '" + state.getPreviousState() + "'" + " to '"
+ " to '" + state.getCurrentState() + "'"); + state.getCurrentState() + "'");
throw new ApplicationManagementException("Lifecycle State Validation failed"); throw new ApplicationManagementException("Lifecycle State Validation failed. Application Id: " +
applicationId + " Application release UUID: " + releaseUuid);
} }
} }
} catch (LifeCycleManagementDAOException | DBConnectionException e) { } catch (LifeCycleManagementDAOException e) {
throw new ApplicationManagementException("Failed to add lifecycle state", e); ConnectionManagerUtil.rollbackDBTransaction();
} catch (ApplicationManagementException e) { throw new ApplicationManagementException(
throw new ApplicationManagementException("Lifecycle State Validation failed", e); "Failed to add lifecycle state. Application Id: " + applicationId + " Application release UUID: "
+ releaseUuid, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
} }
} }

@ -34,7 +34,6 @@ import org.wso2.carbon.device.application.mgt.common.services.*;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO; import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO; import org.wso2.carbon.device.application.mgt.core.dao.ReviewDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
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.exception.ReviewManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ReviewManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder; import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
@ -71,7 +70,7 @@ public class ReviewManagerImpl implements ReviewManager {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
boolean isSuccess = false; boolean isSuccess = false;
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.openDBConnection();
Review existingReview = reviewDAO.haveUerCommented(uuid, username, tenantId); Review existingReview = reviewDAO.haveUerCommented(uuid, username, tenantId);
if (existingReview != null && isAuthorizedUser(username, existingReview.getUsername(), tenantId) if (existingReview != null && isAuthorizedUser(username, existingReview.getUsername(), tenantId)
&& review.getRating() > 0 && review.getRating() != existingReview.getRating()) { && review.getRating() > 0 && review.getRating() != existingReview.getRating()) {
@ -82,12 +81,13 @@ public class ReviewManagerImpl implements ReviewManager {
Runnable task = () -> calculateRating(review.getRating(), -12345, uuid); Runnable task = () -> calculateRating(review.getRating(), -12345, uuid);
new Thread(task).start(); new Thread(task).start();
review.setUsername(username); review.setUsername(username);
ConnectionManagerUtil.beginDBTransaction();
isSuccess = this.reviewDAO.addReview(review, uuid, tenantId); isSuccess = this.reviewDAO.addReview(review, uuid, tenantId);
} if (isSuccess) {
if (isSuccess) { ConnectionManagerUtil.commitDBTransaction();
ConnectionManagerUtil.commitDBTransaction(); } else {
} else { ConnectionManagerUtil.rollbackDBTransaction();
ConnectionManagerUtil.rollbackDBTransaction(); }
} }
return isSuccess; return isSuccess;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
@ -116,8 +116,8 @@ public class ReviewManagerImpl implements ReviewManager {
log.debug("Review updating request is received for the review id " + reviewId); log.debug("Review updating request is received for the review id " + reviewId);
} }
try { try {
ConnectionManagerUtil.openDBConnection();
if (existingReview == null) { if (existingReview == null) {
ConnectionManagerUtil.openDBConnection();
existingReview = this.reviewDAO.getReview(reviewId); existingReview = this.reviewDAO.getReview(reviewId);
if (existingReview != null && isAuthorizedUser(username, existingReview.getUsername(), tenantId)) { if (existingReview != null && isAuthorizedUser(username, existingReview.getUsername(), tenantId)) {
if (review.getRating() > 0 && review.getRating() != existingReview.getRating()) { if (review.getRating() > 0 && review.getRating() != existingReview.getRating()) {
@ -176,7 +176,7 @@ public class ReviewManagerImpl implements ReviewManager {
} }
try { try {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
reviews = this.reviewDAO.getAllReviews(uuid, Util.validateCommentListPageSize(request), tenantId); reviews = this.reviewDAO.getAllReviews(uuid, request, tenantId);
for (Review review : reviews) { for (Review review : reviews) {
if (hierarchicalReviewSet.containsKey(review.getParentId())) { if (hierarchicalReviewSet.containsKey(review.getParentId())) {

@ -18,12 +18,16 @@ public class LifecycleStateManger {
public LifecycleStateManger(List<LifecycleState> states) { public LifecycleStateManger(List<LifecycleState> states) {
lifecycleStates = new HashMap<>(); lifecycleStates = new HashMap<>();
for (LifecycleState s : states) { for (LifecycleState s : states) {
lifecycleStates.put(s.getName(), new State(s.getName(), s.getProceedingStates())); if (s.getProceedingStates() != null) {
s.getProceedingStates().replaceAll(String::toUpperCase);
}
lifecycleStates.put(s.getName().toUpperCase(), new State(s.getName().toUpperCase(), s.getProceedingStates()));
} }
} }
public Set<String> getNextLifecycleStates(String currentLifecycleState) { public Set<String> getNextLifecycleStates(String currentLifecycleState) {
return lifecycleStates.get(currentLifecycleState).getProceedingStates(); return lifecycleStates.get(currentLifecycleState.toUpperCase()).getProceedingStates();
} }
public boolean isValidStateChange(String currentState, String nextState) { public boolean isValidStateChange(String currentState, String nextState) {

@ -32,14 +32,14 @@ public class LifecycleManagementTest {
public void checkValidNextLifecycleState() { public void checkValidNextLifecycleState() {
Set<String> proceedingStates = lifecycleStateManger.getNextLifecycleStates(CURRENT_STATE); Set<String> proceedingStates = lifecycleStateManger.getNextLifecycleStates(CURRENT_STATE);
Assert.assertTrue("Invalid proceeding state of: " + CURRENT_STATE, Assert.assertTrue("Invalid proceeding state of: " + CURRENT_STATE,
proceedingStates.contains(NEXT_STATE)); proceedingStates.contains(NEXT_STATE.toUpperCase()));
} }
@Test @Test
public void checkInvalidNextLifecycleState() { public void checkInvalidNextLifecycleState() {
Set<String> proceedingStates = lifecycleStateManger.getNextLifecycleStates(CURRENT_STATE); Set<String> proceedingStates = lifecycleStateManger.getNextLifecycleStates(CURRENT_STATE);
Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE, Assert.assertFalse("Invalid proceeding state of: " + CURRENT_STATE,
proceedingStates.contains(BOGUS_STATE)); proceedingStates.contains(BOGUS_STATE.toUpperCase()));
} }
@Test @Test

@ -55,7 +55,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId> <artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version> <version>1.8</version>
<executions> <executions>
<execution> <execution>
<phase>compile</phase> <phase>compile</phase>

@ -0,0 +1,41 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.application.mgt.publisher.api;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApiOriginFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
public void destroy() {
//do nothing
}
public void init(FilterConfig filterConfig) throws ServletException {
//do nothing
}
}

@ -39,6 +39,7 @@ import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
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;
@ -125,10 +126,25 @@ public interface ApplicationManagementAPI {
}) })
Response getApplications( Response getApplications(
@ApiParam( @ApiParam(
name = "filter", name = "name",
value = "Filter to get application list", value = "Name of the application")
required = true) @QueryParam("name") String appName,
@Valid Filter filter, @ApiParam(
name = "type",
value = "Type of the application")
@QueryParam("type") String appType,
@ApiParam(
name = "category",
value = "Category of the application")
@QueryParam("category") String appCategory,
@ApiParam(
name = "exact-match",
value = "Is it requesting exactly matching application or partially matching application.")
@QueryParam("exact-match") boolean isFullMatch,
@ApiParam(
name = "published-release",
value = "If set to True, only get published release for the application")
@QueryParam("published-release") boolean requirePublishedReleases,
@ApiParam( @ApiParam(
name = "offset", name = "offset",
value = "offset", value = "offset",
@ -138,7 +154,12 @@ public interface ApplicationManagementAPI {
name = "limit", name = "limit",
value = "limit", value = "limit",
defaultValue = "20") defaultValue = "20")
@QueryParam("limit") int limit @QueryParam("limit") int limit,
@ApiParam(
name = "sort",
value = "Sorting type",
defaultValue = "AES")
@QueryParam("sort") String sortBy
); );
@GET @GET
@ -537,6 +558,10 @@ public interface ApplicationManagementAPI {
code = 201, code = 201,
message = "OK. \n Successfully add a lifecycle state.", message = "OK. \n Successfully add a lifecycle state.",
response = Application.class), response = Application.class),
@ApiResponse(
code = 404,
message = "NOT FOUND. \n Error occurred while adding new lifecycle state.",
response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred adding a lifecycle state.", message = "Internal Server Error. \n Error occurred adding a lifecycle state.",

@ -42,6 +42,7 @@ import java.util.UUID;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
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;
@ -65,14 +66,32 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@Override @Override
@Consumes("application/json") @Consumes("application/json")
public Response getApplications( public Response getApplications(
@Valid Filter filter, @QueryParam("name") String appName,
@QueryParam("offset") int offset, @QueryParam("type") String appType,
@QueryParam("limit") int limit) { @QueryParam("category") String appCategory,
@QueryParam("exact-match") boolean isFullMatch,
@QueryParam("published-release") boolean requirePublishedReleases,
@DefaultValue("0") @QueryParam("offset") int offset,
@DefaultValue("20") @QueryParam("limit") int limit,
@DefaultValue("ASC") @QueryParam("sort") String sortBy) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
Filter filter = new Filter();
filter.setOffset(offset); filter.setOffset(offset);
filter.setLimit(limit); filter.setLimit(limit);
filter.setSortBy(sortBy);
filter.setFullMatch(isFullMatch);
filter.setRequirePublishedRelease(requirePublishedReleases);
if (appName != null && !appName.isEmpty()) {
filter.setAppName(appName);
}
if (appType != null && !appType.isEmpty()) {
filter.setAppType(appType);
}
if (appCategory != null && !appCategory.isEmpty()) {
filter.setAppCategory(appCategory);
}
ApplicationList applications = applicationManager.getApplications(filter); ApplicationList applications = applicationManager.getApplications(filter);
if (applications.getApplications().isEmpty()) { if (applications.getApplications().isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity return Response.status(Response.Status.NOT_FOUND).entity
@ -390,7 +409,8 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@DELETE @DELETE
@Path("/{appid}") @Path("/{appid}")
public Response deleteApplication(@PathParam("appid") int applicationId) { public Response deleteApplication(
@PathParam("appid") int applicationId) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try { try {
@ -411,7 +431,9 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@DELETE @DELETE
@Path("/{appid}/{uuid}") @Path("/{appid}/{uuid}")
public Response deleteApplicationRelease(@PathParam("appid") int applicationId, @PathParam("uuid") String releaseUuid) { public Response deleteApplicationRelease(
@PathParam("appid") int applicationId,
@PathParam("uuid") String releaseUuid) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager(); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try { try {
@ -461,7 +483,12 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
LifecycleState state) { LifecycleState state) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
try { try {
applicationManager.changeLifecycleState(applicationId, applicationUuid, state, true, 0); applicationManager.changeLifecycleState(applicationId, applicationUuid, state, true);
} catch (NotFoundException e) {
String msg = "Could,t find application release for application id: " + applicationId
+ " and application release uuid: " + applicationUuid;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while adding lifecycle state."; String msg = "Error occurred while adding lifecycle state.";
log.error(msg, e); log.error(msg, e);

@ -36,7 +36,7 @@
</jaxrs:server> </jaxrs:server>
<bean id="swaggerConfig" class="io.swagger.jaxrs.config.BeanConfig"> <bean id="swaggerConfig" class="io.swagger.jaxrs.config.BeanConfig">
<property name="resourcePackage" value="org.wso2.carbon.device.application.mgt"/> <property name="resourcePackage" value="org.wso2.carbon.device.application.mgt.publisher.api"/>
<property name="version" value="1.0"/> <property name="version" value="1.0"/>
<property name="host" value="localhost:9443"/> <property name="host" value="localhost:9443"/>
<property name="schemes" value="https" /> <property name="schemes" value="https" />

@ -46,6 +46,17 @@
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<!-- Below configuration is used to redirect http requests to https -->
<security-constraint>
<web-resource-collection>
<web-resource-name>ApplicationMgt-Admin</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>
<param-name>managed-api-enabled</param-name> <param-name>managed-api-enabled</param-name>
@ -61,20 +72,8 @@
</context-param> </context-param>
<filter> <filter>
<filter-name>CorsFilter</filter-name> <filter-name>ApiOriginFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class> <filter-class>org.wso2.carbon.device.application.mgt.publisher.api.ApiOriginFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,DELETE,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type</param-value>
</init-param>
</filter> </filter>
<filter> <filter>
@ -114,7 +113,7 @@
</filter-mapping> </filter-mapping>
<filter-mapping> <filter-mapping>
<filter-name>CorsFilter</filter-name> <filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern> <url-pattern>/*</url-pattern>
</filter-mapping> </filter-mapping>

@ -55,7 +55,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId> <artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version> <version>1.8</version>
<executions> <executions>
<execution> <execution>
<phase>compile</phase> <phase>compile</phase>
@ -85,7 +85,7 @@
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version> <version>1.5.0</version>
<executions> <executions>
<execution> <execution>
<phase>test</phase> <phase>test</phase>
@ -176,6 +176,7 @@
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId> <artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>

@ -0,0 +1,46 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.application.mgt.store.api;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ApiOriginFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
public void destroy() {
//do nothing
}
public void init(FilterConfig filterConfig) throws ServletException {
//do nothing
}
}

@ -0,0 +1,124 @@
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.application.mgt.store.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxrs.lifecycle.ResourceProvider;
import org.apache.cxf.jaxrs.model.ClassResourceInfo;
import org.apache.cxf.jaxrs.model.OperationResourceInfo;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
public class ValidationInterceptor extends AbstractPhaseInterceptor<Message> {
private Log log = LogFactory.getLog(getClass());
private Validator validator = null; //validator interface is thread-safe
public ValidationInterceptor() {
super(Phase.PRE_INVOKE);
ValidatorFactory defaultFactory = Validation.buildDefaultValidatorFactory();
validator = defaultFactory.getValidator();
if (validator == null) {
log.warn("Bean Validation provider could not be found, no validation will be performed");
} else {
log.debug("Validation In-Interceptor initialized successfully");
}
}
@Override
public void handleMessage(Message message) throws Fault {
final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class);
if (operationResource == null) {
log.info("OperationResourceInfo is not available, skipping validation");
return;
}
final ClassResourceInfo classResource = operationResource.getClassResourceInfo();
if (classResource == null) {
log.info("ClassResourceInfo is not available, skipping validation");
return;
}
final ResourceProvider resourceProvider = classResource.getResourceProvider();
if (resourceProvider == null) {
log.info("ResourceProvider is not available, skipping validation");
return;
}
final List<Object> arguments = MessageContentsList.getContentsList(message);
final Method method = operationResource.getAnnotatedMethod();
final Object instance = resourceProvider.getInstance(message);
if (method != null && arguments != null) {
//validate the parameters(arguments) over the invoked method
validate(method, arguments.toArray(), instance);
//validate the fields of each argument
for (Object arg : arguments) {
if (arg != null)
validate(arg);
}
}
}
public <T> void validate(final Method method, final Object[] arguments, final T instance) {
if (validator == null) {
log.warn("Bean Validation provider could not be found, no validation will be performed");
return;
}
ExecutableValidator methodValidator = validator.forExecutables();
Set<ConstraintViolation<T>> violations = methodValidator.validateParameters(instance,
method, arguments);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
public <T> void validate(final T object) {
if (validator == null) {
log.warn("Bean Validation provider could be found, no validation will be performed");
return;
}
Set<ConstraintViolation<T>> violations = validator.validate(object);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
public void handleFault(Message messageParam) {
}
}

@ -63,7 +63,7 @@ import java.util.List;
} }
), ),
tags = { tags = {
@Tag(name = "store_management", description = "Review Management related APIs") @Tag(name = "review_management", description = "Review Management related APIs")
} }
) )
@Scopes( @Scopes(
@ -124,18 +124,17 @@ public interface ReviewManagementAPI {
name="uuid", name="uuid",
value="uuid of the application release.", value="uuid of the application release.",
required = true) required = true)
@PathParam("uuid") @PathParam("uuid") String uuid,
String uuid,
@ApiParam( @ApiParam(
name="offSet", name="offset",
value="Starting review number.",defaultValue = "0") value="Starting review number.",
@QueryParam("offSet") defaultValue = "0")
int offSet, @QueryParam("offSet") int offSet,
@ApiParam( @ApiParam(
name="limit", name="limit",
value = "Limit of paginated reviews",defaultValue = "20") value = "Limit of paginated reviews",
@QueryParam("limit") defaultValue = "20")
int limit); @QueryParam("limit") int limit);
@POST @POST
@Path("/{uuid}") @Path("/{uuid}")

@ -98,32 +98,41 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Path("/{appType}") @Path("/{appType}")
public Response getApplication( public Response getApplication(@PathParam("appType") String appType,
@PathParam("appType") String appType,
@QueryParam("appName") String appName) { @QueryParam("appName") String appName) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
List<ApplicationRelease> publishedApplicationRelease = new ArrayList<>(); List<Application> filteredApps = new ArrayList<>();
Filter filter;
try { try {
Application application = applicationManager.getApplication(appType, appName); filter = new Filter();
if (application == null) { filter.setOffset(0);
filter.setLimit(20);
filter.setAppType(appType);
filter.setAppName(appName);
ApplicationList applications = applicationManager.getApplications(filter);
if (applications.getApplications().isEmpty()) {
return Response.status(Response.Status.NOT_FOUND) return Response.status(Response.Status.NOT_FOUND)
.entity("Application with application type: " + appType + " not found").build(); .entity("Application with application type: " + appType + " not found").build();
} }
for (Application application : applications.getApplications()) {
for (ApplicationRelease appRelease : application.getApplicationReleases()) { List<ApplicationRelease> publishedApplicationRelease = new ArrayList<>();
if (AppLifecycleState.PUBLISHED.toString().equals(appRelease.getLifecycleState().getCurrentState())){ for (ApplicationRelease appRelease : application.getApplicationReleases()) {
publishedApplicationRelease.add(appRelease); if (AppLifecycleState.PUBLISHED.toString()
.equals(appRelease.getLifecycleState().getCurrentState())) {
publishedApplicationRelease.add(appRelease);
}
} }
if (publishedApplicationRelease.size() > 1) {
String msg = "Application " + application.getName()
+ " has more than one PUBLISHED application releases";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
application.setApplicationReleases(publishedApplicationRelease);
filteredApps.add(application);
} }
if (publishedApplicationRelease.size() > 1) { applications.setApplications(filteredApps);
String msg = return Response.status(Response.Status.OK).entity(applications).build();
"Application " + application.getName() + " has more than one PUBLISHED application releases";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
application.setApplicationReleases(publishedApplicationRelease);
return Response.status(Response.Status.OK).entity(application).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build(); return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {

@ -35,6 +35,7 @@ import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
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.ReviewManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ReviewManagementException;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
@ -58,8 +59,8 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
@Path("/{uuid}") @Path("/{uuid}")
public Response getAllReviews( public Response getAllReviews(
@PathParam("uuid") String uuid, @PathParam("uuid") String uuid,
@QueryParam("offset") int offSet, @DefaultValue("0") @QueryParam("offset") int offSet,
@QueryParam("limit") int limit) { @DefaultValue("20") @QueryParam("limit") int limit) {
ReviewManager reviewManager = APIUtil.getReviewManager(); ReviewManager reviewManager = APIUtil.getReviewManager();
PaginationRequest request = new PaginationRequest(offSet, limit); PaginationRequest request = new PaginationRequest(offSet, limit);
try { try {

@ -18,29 +18,51 @@
--> -->
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation=" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
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="lifecycleMgtServiceBean"/> <ref bean="reviewMgtServiceBean"/>
<ref bean="subscriptionMgtServiceBean"/> <ref bean="subscriptionMgtServiceBean"/>
<ref bean="swaggerResource"/>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>
<ref bean="jsonProvider"/> <ref bean="jsonProvider"/>
<ref bean="multipartProvider"/> <ref bean="multipartProvider"/>
<ref bean="swaggerWriter"/>
</jaxrs:providers> </jaxrs:providers>
</jaxrs:server> </jaxrs:server>
<bean id="applicationMgtServiceBean" class="org.wso2.carbon.device.application.mgt.publisher.api.services.impl.ApplicationManagementAPIImpl"/> <bean id="swaggerConfig" class="io.swagger.jaxrs.config.BeanConfig">
<bean id="lifecycleMgtServiceBean" class="org.wso2.carbon.device.application.mgt.publisher.api.services.impl.LifecycleManagementAPIImpl" /> <property name="resourcePackage" value="org.wso2.carbon.device.application.mgt.store.api"/>
<bean id="subscriptionMgtServiceBean" class="org.wso2.carbon.device.application.mgt.publisher.api.services.impl.SubscriptionManagementAPIImpl"/> <property name="version" value="1.0"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.application.mgt.publisher.api.JSONMessageHandler"/> <property name="host" value="localhost:9443"/>
<bean id="multipartProvider" class="org.wso2.carbon.device.application.mgt.publisher.api.MultipartCustomProvider"/> <property name="schemes" value="https" />
<property name="basePath" value="/api/application-mgt-store/v1.0"/>
<property name="title" value="App Store Management Service API Definitions"/>
<property name="contact" value="dev@wso2.org"/>
<property name="license" value="Apache 2.0"/>
<property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>
<property name="scan" value="true"/>
</bean>
</beans> <bean id="ValidationInterceptor" class="org.wso2.carbon.device.application.mgt.store.api.ValidationInterceptor"/>
<bean id="swaggerWriter" class="io.swagger.jaxrs.listing.SwaggerSerializers" />
<bean id="swaggerResource" class="io.swagger.jaxrs.listing.ApiListingResource" />
<bean id="applicationMgtServiceBean" class="org.wso2.carbon.device.application.mgt.store.api.services.impl.ApplicationManagementAPIImpl"/>
<bean id="reviewMgtServiceBean" class="org.wso2.carbon.device.application.mgt.store.api.services.impl.ReviewManagementAPIImpl" />
<bean id="subscriptionMgtServiceBean" class="org.wso2.carbon.device.application.mgt.store.api.services.impl.SubscriptionManagementAPIImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.application.mgt.store.api.JSONMessageHandler"/>
<bean id="multipartProvider" class="org.wso2.carbon.device.application.mgt.store.api.MultipartCustomProvider"/>
<cxf:bus>
<cxf:inInterceptors>
<ref bean="ValidationInterceptor"/>
</cxf:inInterceptors>
</cxf:bus>
</beans>

@ -19,14 +19,20 @@
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"> version="2.5">
<display-name>Application Management Webapp</display-name> <display-name>App Store Management Webapp</display-name>
<servlet> <servlet>
<description>JAX-WS/JAX-RS Application Management Endpoint</description> <description>JAX-WS/JAX-RS App Store Management Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name> <display-name>JAX-WS/JAX-RS Servlet</display-name>
<servlet-name>CXFServlet</servlet-name> <servlet-name>CXFServlet</servlet-name>
<servlet-class> <servlet-class>
org.apache.cxf.transport.servlet.CXFServlet org.apache.cxf.transport.servlet.CXFServlet
</servlet-class> </servlet-class>
<!-- configure a security filter -->
<init-param>
<param-name>swagger.security.filter</param-name>
<param-value>ApiAuthorizationFilterImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> </servlet>
<servlet-mapping> <servlet-mapping>
<servlet-name>CXFServlet</servlet-name> <servlet-name>CXFServlet</servlet-name>
@ -40,6 +46,17 @@
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<!-- Below configuration is used to redirect http requests to https -->
<security-constraint>
<web-resource-collection>
<web-resource-name>ApplicationMgt-Admin</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
<!--publish to apim--> <!--publish to apim-->
<context-param> <context-param>
<param-name>managed-api-enabled</param-name> <param-name>managed-api-enabled</param-name>
@ -55,20 +72,8 @@
</context-param> </context-param>
<filter> <filter>
<filter-name>CorsFilter</filter-name> <filter-name>ApiOriginFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class> <filter-class>org.wso2.carbon.device.application.mgt.store.api.ApiOriginFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,DELETE,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type</param-value>
</init-param>
</filter> </filter>
<filter> <filter>
@ -108,7 +113,7 @@
</filter-mapping> </filter-mapping>
<filter-mapping> <filter-mapping>
<filter-name>CorsFilter</filter-name> <filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern> <url-pattern>/*</url-pattern>
</filter-mapping> </filter-mapping>

@ -20,17 +20,18 @@ CREATE TABLE IF NOT EXISTS AP_APP (
-- ----------------------------------------------------- -- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS AP_APP_RELEASE ( CREATE TABLE IF NOT EXISTS AP_APP_RELEASE (
ID INT(11) NOT NULL AUTO_INCREMENT, ID INT(11) NOT NULL AUTO_INCREMENT,
VERSION VARCHAR(10) NOT NULL, VERSION VARCHAR(25) NOT NULL,
TENANT_ID VARCHAR(45) NOT NULL, TENANT_ID VARCHAR(45) NOT NULL,
UUID VARCHAR(200) NOT NULL, UUID VARCHAR(200) NOT NULL,
RELEASE_TYPE VARCHAR(45) NOT NULL, RELEASE_TYPE VARCHAR(45) NOT NULL,
PACKAGE_NAME VARCHAR(45) NOT NULL,
APP_PRICE DECIMAL(6,2) NULL DEFAULT NULL, APP_PRICE DECIMAL(6,2) NULL DEFAULT NULL,
STORED_LOCATION VARCHAR(45) NOT NULL, STORED_LOCATION VARCHAR(100) NOT NULL,
BANNER_LOCATION VARCHAR(45) NOT NULL, BANNER_LOCATION VARCHAR(100) NOT NULL,
SC_1_LOCATION VARCHAR(45) NOT NULL, SC_1_LOCATION VARCHAR(100) NOT NULL,
SC_2_LOCATION VARCHAR(45) NULL DEFAULT NULL, SC_2_LOCATION VARCHAR(100) NULL DEFAULT NULL,
SC_3_LOCATION VARCHAR(45) NULL DEFAULT NULL, SC_3_LOCATION VARCHAR(100) NULL DEFAULT NULL,
APP_HASH_VALUE VARCHAR(1000) NOT NULL, APP_HASH_VALUE VARCHAR(100) NOT NULL,
SHARED_WITH_ALL_TENANTS INT(11) NULL DEFAULT NULL, SHARED_WITH_ALL_TENANTS INT(11) NULL DEFAULT NULL,
APP_META_INFO VARCHAR(20000) NULL DEFAULT NULL, APP_META_INFO VARCHAR(20000) NULL DEFAULT NULL,
RATING DOUBLE NULL DEFAULT NULL, RATING DOUBLE NULL DEFAULT NULL,
@ -51,9 +52,9 @@ CREATE TABLE IF NOT EXISTS AP_APP_REVIEW (
ID INT(11) NOT NULL AUTO_INCREMENT, ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL, TENANT_ID VARCHAR(45) NOT NULL,
COMMENT VARCHAR(250) NOT NULL, COMMENT VARCHAR(250) NOT NULL,
REPLY_COMMENT VARCHAR(250) NULL, PARENT_ID INT(11) NULL,
CREATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, CREATED_AT TIMESTAMP NOT NULL,
MODEFIED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, MODEFIED_AT TIMESTAMP NOT NULL,
RATING INT(11) NULL, RATING INT(11) NULL,
USERNAME VARCHAR(45) NOT NULL, USERNAME VARCHAR(45) NOT NULL,
AP_APP_RELEASE_ID INT(11) NOT NULL, AP_APP_RELEASE_ID INT(11) NOT NULL,
@ -75,7 +76,7 @@ CREATE TABLE IF NOT EXISTS AP_APP_LIFECYCLE_STATE (
PREVIOUSE_STATE VARCHAR(45) NOT NULL, PREVIOUSE_STATE VARCHAR(45) NOT NULL,
TENANT_ID VARCHAR(45) NOT NULL, TENANT_ID VARCHAR(45) NOT NULL,
UPDATED_BY VARCHAR(100) NOT NULL, UPDATED_BY VARCHAR(100) NOT NULL,
UPDATED_AT TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UPDATED_AT TIMESTAMP NOT NULL,
AP_APP_RELEASE_ID INT(11) NOT NULL, AP_APP_RELEASE_ID INT(11) NOT NULL,
AP_APP_ID INT(11) NOT NULL, AP_APP_ID INT(11) NOT NULL,
PRIMARY KEY (ID, AP_APP_RELEASE_ID, AP_APP_ID), PRIMARY KEY (ID, AP_APP_RELEASE_ID, AP_APP_ID),
@ -109,7 +110,7 @@ CREATE TABLE IF NOT EXISTS AP_DEVICE_SUBSCRIPTION (
ID INT(11) NOT NULL AUTO_INCREMENT, ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL, TENANT_ID VARCHAR(45) NOT NULL,
SUBSCRIBED_BY VARCHAR(100) NOT NULL, SUBSCRIBED_BY VARCHAR(100) NOT NULL,
SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL,
UNSUBSCRIBED INT(11) NULL DEFAULT NULL, UNSUBSCRIBED INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL, UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL,
@ -131,7 +132,7 @@ CREATE TABLE IF NOT EXISTS AP_GROUP_SUBSCRIPTION (
ID INT(11) NOT NULL AUTO_INCREMENT, ID INT(11) NOT NULL AUTO_INCREMENT,
TENANT_ID VARCHAR(45) NOT NULL, TENANT_ID VARCHAR(45) NOT NULL,
SUBSCRIBED_BY VARCHAR(100) NOT NULL, SUBSCRIBED_BY VARCHAR(100) NOT NULL,
SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL,
UNSUBSCRIBED INT(11) NULL DEFAULT NULL, UNSUBSCRIBED INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL, UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL,
@ -154,7 +155,7 @@ CREATE TABLE IF NOT EXISTS AP_ROLE_SUBSCRIPTION (
TENANT_ID VARCHAR(45) NOT NULL, TENANT_ID VARCHAR(45) NOT NULL,
ROLE_NAME VARCHAR(100) NOT NULL, ROLE_NAME VARCHAR(100) NOT NULL,
SUBSCRIBED_BY VARCHAR(100) NOT NULL, SUBSCRIBED_BY VARCHAR(100) NOT NULL,
SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, SUBSCRIBED_TIMESTAMP TIMESTAMP NOT NULL,
UNSUBSCRIBED INT(11) NULL DEFAULT NULL, UNSUBSCRIBED INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL, UNSUBSCRIBED_BY INT(11) NULL DEFAULT NULL,
UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL, UNSUBSCRIBED_TIMESTAMP TIMESTAMP NULL DEFAULT NULL,

@ -32,17 +32,18 @@ CREATE TABLE IF NOT EXISTS `AP_APP` (
-- ----------------------------------------------------- -- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `AP_APP_RELEASE` ( CREATE TABLE IF NOT EXISTS `AP_APP_RELEASE` (
`ID` INT(11) NOT NULL AUTO_INCREMENT, `ID` INT(11) NOT NULL AUTO_INCREMENT,
`VERSION` VARCHAR(10) NOT NULL, `VERSION` VARCHAR(25) NOT NULL,
`TENANT_ID` VARCHAR(45) NOT NULL, `TENANT_ID` VARCHAR(45) NOT NULL,
`UUID` VARCHAR(200) NOT NULL, `UUID` VARCHAR(200) NOT NULL,
`RELEASE_TYPE` VARCHAR(45) NOT NULL, `RELEASE_TYPE` VARCHAR(45) NOT NULL,
`PACKAGE_NAME` VARCHAR(45) NOT NULL,
`APP_PRICE` DECIMAL(6,2) NULL DEFAULT NULL, `APP_PRICE` DECIMAL(6,2) NULL DEFAULT NULL,
`STORED_LOCATION` VARCHAR(45) NOT NULL, `STORED_LOCATION` VARCHAR(100) NOT NULL,
`BANNER_LOCATION` VARCHAR(45) NOT NULL, `BANNER_LOCATION` VARCHAR(100) NOT NULL,
`SC_1_LOCATION` VARCHAR(45) NOT NULL, `SC_1_LOCATION` VARCHAR(100) NOT NULL,
`SC_2_LOCATION` VARCHAR(45) NULL DEFAULT NULL, `SC_2_LOCATION` VARCHAR(100) NULL DEFAULT NULL,
`SC_3_LOCATION` VARCHAR(45) NULL DEFAULT NULL, `SC_3_LOCATION` VARCHAR(100) NULL DEFAULT NULL,
`APP_HASH_VALUE` VARCHAR(1000) NOT NULL, `APP_HASH_VALUE` VARCHAR(100) NOT NULL,
`SHARED_WITH_ALL_TENANTS` INT(11) NULL DEFAULT NULL, `SHARED_WITH_ALL_TENANTS` INT(11) NULL DEFAULT NULL,
`APP_META_INFO` VARCHAR(20000) NULL DEFAULT NULL, `APP_META_INFO` VARCHAR(20000) NULL DEFAULT NULL,
`RATING` DOUBLE NULL DEFAULT NULL, `RATING` DOUBLE NULL DEFAULT NULL,
@ -68,9 +69,9 @@ CREATE TABLE IF NOT EXISTS `AP_APP_REVIEW` (
`ID` INT(11) NOT NULL AUTO_INCREMENT, `ID` INT(11) NOT NULL AUTO_INCREMENT,
`TENANT_ID` VARCHAR(45) NOT NULL, `TENANT_ID` VARCHAR(45) NOT NULL,
`COMMENT` VARCHAR(250) NOT NULL, `COMMENT` VARCHAR(250) NOT NULL,
`REPLY_COMMENT` VARCHAR(250) NULL, `PARENT_ID` INT(11) NULL,
`CREATED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `CREATED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`MODEFIED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `MODIFIED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`RATING` INT(11) NULL, `RATING` INT(11) NULL,
`USERNAME` VARCHAR(45) NOT NULL, `USERNAME` VARCHAR(45) NOT NULL,
`AP_APP_RELEASE_ID` INT(11) NOT NULL, `AP_APP_RELEASE_ID` INT(11) NOT NULL,
@ -93,7 +94,7 @@ CREATE INDEX `fk_AP_APP_COMMENT_AP_APP_RELEASE1_idx` ON `AP_APP_REVIEW` (`AP_APP
CREATE TABLE IF NOT EXISTS `AP_APP_LIFECYCLE_STATE` ( CREATE TABLE IF NOT EXISTS `AP_APP_LIFECYCLE_STATE` (
`ID` INT(11) NOT NULL AUTO_INCREMENT, `ID` INT(11) NOT NULL AUTO_INCREMENT,
`CURRENT_STATE` VARCHAR(45) NOT NULL, `CURRENT_STATE` VARCHAR(45) NOT NULL,
`PREVIOUSE_STATE` VARCHAR(45) NOT NULL, `PREVIOUS_STATE` VARCHAR(45) NOT NULL,
`TENANT_ID` VARCHAR(45) NOT NULL, `TENANT_ID` VARCHAR(45) NOT NULL,
`UPDATED_BY` VARCHAR(100) NOT NULL, `UPDATED_BY` VARCHAR(100) NOT NULL,
`UPDATED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `UPDATED_AT` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

@ -2100,7 +2100,7 @@
<jersey.version>1.9</jersey.version> <jersey.version>1.9</jersey.version>
<!-- Neethi version--> <!-- Neethi version-->
<neethi.version>2.0.4</neethi.version> <neethi.version>3.1.1</neethi.version>
<neethi.wso2.version>2.0.4.wso2v4</neethi.wso2.version> <neethi.wso2.version>2.0.4.wso2v4</neethi.wso2.version>
<!-- Release plugin ID for github--> <!-- Release plugin ID for github-->

Loading…
Cancel
Save