Add app release inserting API

feature/appm-store/pbac
lasanthaDLPDS 6 years ago
parent cd28edc6a3
commit 425938e3a8

@ -93,7 +93,7 @@ public interface ApplicationManager {
String getUuidOfLatestRelease(int appId) throws ApplicationManagementException; String getUuidOfLatestRelease(int appId) throws ApplicationManagementException;
/** /**
* To get Application with the given Id. * To get the Application for given Id.
* *
* @param id id of the Application * @param id id of the Application
* @param state state of the Application * @param state state of the Application
@ -102,6 +102,16 @@ public interface ApplicationManager {
*/ */
Application getApplicationById(int id, String state) throws ApplicationManagementException; Application getApplicationById(int id, String state) throws ApplicationManagementException;
/**
* To get the Application for given application relase UUID.
*
* @param uuid UUID of the Application
* @param state state of the Application
* @return the Application identified by the ID
* @throws ApplicationManagementException Application Management Exception.
*/
Application getApplicationByUuid(String uuid, String state) throws ApplicationManagementException;
/** /**
* To get an application associated with the release. * To get an application associated with the release.
* *
@ -146,11 +156,9 @@ public interface ApplicationManager {
* @param releaseUuid 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 handleDBConnections Whether it is necessary to open connections
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException Application Management Exception.
*/ */
void changeLifecycleState(int applicationId, String releaseUuid, LifecycleState state, Boolean checkExist, void changeLifecycleState(int applicationId, String releaseUuid, LifecycleState state, Boolean checkExist)
Boolean handleDBConnections)
throws ApplicationManagementException; throws ApplicationManagementException;
/** /**

@ -96,7 +96,7 @@ public interface ApplicationDAO {
ApplicationManagementDAOException; ApplicationManagementDAOException;
/** /**
* To get the application with the given uuid * To get the application with the given id
* *
* @param applicationId Id of the application to be retrieved. * @param applicationId Id of the application to be retrieved.
* @param tenantId ID of the tenant. * @param tenantId ID of the tenant.
@ -105,6 +105,16 @@ public interface ApplicationDAO {
*/ */
Application getApplicationById(int applicationId, int tenantId) throws ApplicationManagementDAOException; Application getApplicationById(int applicationId, int tenantId) throws ApplicationManagementDAOException;
/**
* To get the application with the given uuid
*
* @param releaseUuid UUID of the application release.
* @param tenantId ID of the tenant.
* @return the application
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
Application getApplicationByUUID(String releaseUuid, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To get the application with the given uuid * To get the application with the given uuid
* *

@ -138,6 +138,16 @@ public interface ApplicationReleaseDAO {
*/ */
boolean verifyReleaseExistence(int appId, String uuid, int tenantId) throws ApplicationManagementDAOException; boolean verifyReleaseExistence(int appId, String uuid, int tenantId) throws ApplicationManagementDAOException;
/**
* To verify whether application release exist or not for the given app release version.
*
* @param appId ID of the application.
* @param hashVal Hash value of the application release.
* @param tenantId Tenant Id
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
boolean verifyReleaseExistenceByHash(int appId, String hashVal, int tenantId) throws ApplicationManagementDAOException;
/** /**
* To verify whether application release exist or not for given application release uuid. * To verify whether application release exist or not for given application release uuid.
* *

@ -389,6 +389,53 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public Application getApplicationByUUID(String releaseUuid, int tenantId) throws
ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting application with the release UUID: " + releaseUuid + " from the database");
}
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.DEVICE_TYPE_ID AS DEVICE_TYPE_ID, "
+ "AP_APP_TAG.TAG AS APP_TAG, AP_UNRESTRICTED_ROLE.ROLE AS "
+ "ROLE FROM ((AP_APP LEFT JOIN AP_APP_TAG ON AP_APP.ID = AP_APP_TAG.AP_APP_ID) "
+ "LEFT JOIN AP_UNRESTRICTED_ROLE ON AP_APP.ID = AP_UNRESTRICTED_ROLE.AP_APP_ID) "
+ "WHERE AP_APP.ID = (SELECT AP_APP_ID FROM AP_APP_RELEASE WHERE UUID =? ) AND "
+ "AP_APP.TENANT_ID = ? AND AP_APP.STATUS != ?;";
stmt = conn.prepareStatement(sql);
stmt.setString(1, releaseUuid);
stmt.setInt(2, tenantId);
stmt.setString(3, AppLifecycleState.REMOVED.toString());
rs = stmt.executeQuery();
if (log.isDebugEnabled()) {
log.debug("Successfully retrieved basic details of the application for the application release UUID: "
+ releaseUuid);
}
return Util.loadApplication(rs);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred while getting application details with app release uuid " + releaseUuid +
" 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 {

@ -431,6 +431,43 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
} }
} }
@Override
public boolean verifyReleaseExistenceByHash(int appId, String hashVal, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Verifying application release existence by application id:" + appId
+ " and application hash value: " + hashVal);
}
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.APP_HASH_VALUE = ? AND AR.TENANT_ID = ?;";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, appId);
stmt.setString(2, hashVal);
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 hash value: " + hashVal);
}
return rs.next();
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
"Error occurred while getting application release details with app ID: " + appId
+ " App release hash value: " + hashVal + " While executing query ", e);
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override @Override
public boolean verifyReleaseExistence(int appId, String uuid, int tenantId) throws ApplicationManagementDAOException { public boolean verifyReleaseExistence(int appId, String uuid, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {

@ -46,6 +46,7 @@ import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory; import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util; 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.BadRequestException;
import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException; import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException;
import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
@ -165,7 +166,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, false); changeLifecycleState(appId, applicationRelease.getUuid(), lifecycleState, false);
applicationRelease.setLifecycleState(lifecycleState); applicationRelease.setLifecycleState(lifecycleState);
applicationReleases.add(applicationRelease); applicationReleases.add(applicationRelease);
@ -245,14 +246,22 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.debug("Application release request is received for the application " + application.toString()); log.debug("Application release request is received for the application " + application.toString());
} }
try { try {
ConnectionManagerUtil.getDBConnection(); ConnectionManagerUtil.openDBConnection();
if (!this.applicationDAO.verifyApplicationExistenceById(applicationId, tenantId)){
throw new NotFoundException(
"Couldn't found application for the application Id: " + applicationId);
}
if (this.applicationReleaseDAO
.verifyReleaseExistenceByHash(applicationId, applicationRelease.getAppHashValue(), tenantId)) {
throw new BadRequestException("Application release exists for the application Id: " + applicationId
+ " and uploaded binary file");
}
applicationRelease = this.applicationReleaseDAO applicationRelease = this.applicationReleaseDAO
.createRelease(applicationRelease, application.getId(), tenantId); .createRelease(applicationRelease, application.getId(), tenantId);
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, changeLifecycleState(application.getId(), applicationRelease.getUuid(), lifecycleState, false);
false);
return applicationRelease; return applicationRelease;
} catch (ApplicationManagementDAOException e) { } catch (ApplicationManagementDAOException e) {
throw new ApplicationManagementException( throw new ApplicationManagementException(
@ -321,6 +330,53 @@ public class ApplicationManagerImpl implements ApplicationManager {
} }
} }
@Override
public Application getApplicationByUuid(String uuid, String state) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Application application;
boolean isAppAllowed = false;
boolean isOpenConnection = false;
List<ApplicationRelease> applicationReleases = null;
try {
if (state != null) {
ConnectionManagerUtil.openDBConnection();
isOpenConnection = true;
}
application = this.applicationDAO.getApplicationByUUID(uuid, tenantId);
if (application == null) {
throw new NotFoundException("Couldn't find an application for application release UUID:: " + uuid);
}
if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
applicationReleases = getReleases(application, state);
application.setApplicationReleases(applicationReleases);
return application;
}
if (!application.getUnrestrictedRoles().isEmpty()) {
if (isRoleExists(application.getUnrestrictedRoles(), userName)) {
isAppAllowed = true;
}
} else {
isAppAllowed = true;
}
if (!isAppAllowed) {
return null;
}
applicationReleases = getReleases(application, state);
application.setApplicationReleases(applicationReleases);
return application;
} catch (UserStoreException e) {
throw new ApplicationManagementException(
"User-store exception while getting application with the application release UUID " + uuid);
} finally {
if (isOpenConnection) {
ConnectionManagerUtil.closeDBConnection();
}
}
}
private boolean isRoleExists(Collection<UnrestrictedRole> unrestrictedRoleList, String userName) private boolean isRoleExists(Collection<UnrestrictedRole> unrestrictedRoleList, String userName)
throws UserStoreException { throws UserStoreException {
String[] roleList; String[] roleList;
@ -467,6 +523,14 @@ public class ApplicationManagerImpl implements ApplicationManager {
if (AppLifecycleState.PUBLISHED.toString() if (AppLifecycleState.PUBLISHED.toString()
.equals(state) && filteredReleases.size() > 1) { .equals(state) && filteredReleases.size() > 1) {
log.warn("There are more than one application releases is found which is in PUBLISHED state"); log.warn("There are more than one application releases is found which is in PUBLISHED state");
filteredReleases.sort((r1, r2) -> {
if (r1.getLifecycleState().getUpdatedAt().after(r2.getLifecycleState().getUpdatedAt())) {
return -1;
} else if (r2.getLifecycleState().getUpdatedAt().after(r1.getLifecycleState().getUpdatedAt())) {
return 1;
}
return 0;
});
} }
return filteredReleases; return filteredReleases;
} }
@ -502,7 +566,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, false); changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState, false);
storedLocations.add(applicationRelease.getAppHashValue()); storedLocations.add(applicationRelease.getAppHashValue());
} }
this.applicationDAO.deleteApplication(applicationId); this.applicationDAO.deleteApplication(applicationId);
@ -537,7 +601,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, false); changeLifecycleState(applicationId, applicationRelease.getUuid(), newAppLifecycleState, false);
} 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 " +
@ -849,15 +913,14 @@ public class ApplicationManagerImpl implements ApplicationManager {
return lifecycleState; return lifecycleState;
} }
@Override @Override public void changeLifecycleState(int applicationId, String releaseUuid, LifecycleState state,
public void changeLifecycleState(int applicationId, String releaseUuid, LifecycleState state, Boolean checkExist, Boolean checkExist) throws ApplicationManagementException {
Boolean handleDBConnections) throws ApplicationManagementException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
boolean handleDBConnection = false;
try {
if (checkExist) { if (checkExist) {
if (handleDBConnections) {
ConnectionManagerUtil.openDBConnection(); ConnectionManagerUtil.openDBConnection();
} handleDBConnection = true;
if (!this.applicationDAO.verifyApplicationExistenceById(applicationId, tenantId)){ if (!this.applicationDAO.verifyApplicationExistenceById(applicationId, tenantId)){
throw new NotFoundException( throw new NotFoundException(
"Couldn't found application for the application Id: " + applicationId); "Couldn't found application for the application Id: " + applicationId);
@ -890,7 +953,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
"Failed to add lifecycle state. Application Id: " + applicationId + " Application release UUID: " "Failed to add lifecycle state. Application Id: " + applicationId + " Application release UUID: "
+ releaseUuid, e); + releaseUuid, e);
} finally { } finally {
if (handleDBConnections) { if (handleDBConnection) {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }

@ -484,7 +484,7 @@ 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, true); applicationManager.changeLifecycleState(applicationId, applicationUuid, state, true);
} catch (NotFoundException e) { } catch (NotFoundException e) {
String msg = "Could,t find application release for application id: " + applicationId String msg = "Could,t find application release for application id: " + applicationId
+ " and application release uuid: " + applicationUuid; + " and application release uuid: " + applicationUuid;

@ -30,12 +30,10 @@ import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag; import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.Filter;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse; import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import javax.validation.Valid;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.Path; import javax.ws.rs.Path;
@ -69,52 +67,14 @@ import javax.ws.rs.core.Response;
@Scope( @Scope(
name = "Get Application Details", name = "Get Application Details",
description = "Get application details", description = "Get application details",
key = "perm:application:get", key = "perm:app:store:view",
permissions = {"/device-mgt/application/get"} permissions = {"/device-mgt/application/get"}
),
@Scope(
name = "Create an Application",
description = "Create an application",
key = "perm:application:create",
permissions = {"/device-mgt/application/create"}
),
@Scope(
name = "Update an Application",
description = "Update an application",
key = "perm:application:update",
permissions = {"/device-mgt/application/update"}
),
@Scope(
name = "Create an Application",
description = "Create an application",
key = "perm:application-mgt:login",
permissions = {"/device-mgt/application-mgt/login"}
),
@Scope(
name = "Delete an Application",
description = "Delete an application",
key = "perm:application:delete",
permissions = {"/device-mgt/application/delete"}
),
@Scope(
name = "Create an application category",
description = "Create an application category",
key = "perm:application-category:create",
permissions = {"/device-mgt/application/category/create"}
),
@Scope(
name = "Delete an Application category",
description = "Delete an application category",
key = "perm:application-category:delete",
permissions = {"/device-mgt/application/category/delete"}
) )
} }
) )
@Path("/store/applications") @Path("/store/applications")
@Api(value = "Application Management", description = "This API carries all application management related operations " + @Api(value = "Application Management", description = "This API carries all app store management related operations " +
"such as get all the applications, add application, etc.") "such as get all the applications etc.")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public interface ApplicationManagementAPI { public interface ApplicationManagementAPI {
@ -143,9 +103,8 @@ public interface ApplicationManagementAPI {
message = "OK. \n Successfully got application list.", message = "OK. \n Successfully got application list.",
response = ApplicationList.class), response = ApplicationList.class),
@ApiResponse( @ApiResponse(
code = 304, code = 404,
message = "Not Modified. Empty body because the client already has the latest version " message = "Not Found. Not Found Applications."),
+ "of the requested resource."),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n Error occurred while getting the application list.", message = "Internal Server Error. \n Error occurred while getting the application list.",
@ -153,10 +112,21 @@ 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( @ApiParam(
name = "offset", name = "offset",
value = "Provide from which position apps should return", defaultValue = "0") value = "Provide from which position apps should return", defaultValue = "0")
@ -164,12 +134,16 @@ public interface ApplicationManagementAPI {
@ApiParam( @ApiParam(
name = "limit", name = "limit",
value = "Provide how many apps it should return", defaultValue = "20") value = "Provide how many apps it should return", defaultValue = "20")
@QueryParam("limit") int limit @QueryParam("limit") int limit,
@ApiParam(
name = "limit",
value = "Provide how many apps it should return", defaultValue = "ASC")
@QueryParam("sort") String sortBy
); );
@GET @GET
@Path("/{appType}") @Path("/{uuid}")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ApiOperation( @ApiOperation(
@ -201,15 +175,10 @@ public interface ApplicationManagementAPI {
}) })
Response getApplication( Response getApplication(
@ApiParam( @ApiParam(
name = "appType", name = "uuid",
value = "Type of the application", value = "Type of the application",
required = true) required = true)
@PathParam("appType") String appType, @PathParam("uuid") String uuid
@ApiParam(
name = "appName",
value = "Application name",
required = true)
@QueryParam("appName") String appName
); );

@ -21,7 +21,6 @@ package org.wso2.carbon.device.application.mgt.store.api.services.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.AppLifecycleState; import org.wso2.carbon.device.application.mgt.common.AppLifecycleState;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; import org.wso2.carbon.device.application.mgt.common.ApplicationList;
import org.wso2.carbon.device.application.mgt.common.Filter; import org.wso2.carbon.device.application.mgt.common.Filter;
@ -31,117 +30,84 @@ import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil; import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import org.wso2.carbon.device.application.mgt.store.api.services.ApplicationManagementAPI; import org.wso2.carbon.device.application.mgt.store.api.services.ApplicationManagementAPI;
import javax.validation.Valid;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/** /**
* Implementation of Application Management related APIs. * Implementation of Application Management related APIs.
*/ */
@Produces({"application/json"}) @Produces({ "application/json" })
@Path("/store/applications") @Path("/store/applications")
public class ApplicationManagementAPIImpl implements ApplicationManagementAPI { public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
private static Log log = LogFactory.getLog(ApplicationManagementAPIImpl.class); private static Log log = LogFactory.getLog(ApplicationManagementAPIImpl.class);
@GET @GET
@Consumes("application/json")
@Override @Override
@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,
ApplicationManager applicationManager = APIUtil.getApplicationManager(); @QueryParam("exact-match") boolean isFullMatch,
@DefaultValue("0") @QueryParam("offset") int offset,
@DefaultValue("20") @QueryParam("limit") int limit,
@DefaultValue("ASC") @QueryParam("sort") String sortBy) {
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);
ApplicationList applications = applicationManager.getApplications(filter); filter.setFullMatch(isFullMatch);
List<ApplicationRelease> publishedApplicationRelease = new ArrayList<>(); filter.setCurrentAppReleaseState(AppLifecycleState.PUBLISHED.toString());
if (appName != null && !appName.isEmpty()) {
for (Application application : applications.getApplications()) { filter.setAppName(appName);
for (ApplicationRelease appRelease: application.getApplicationReleases()){
if (AppLifecycleState.PUBLISHED.toString()
.equals(appRelease.getLifecycleState().getCurrentState())) {
publishedApplicationRelease.add(appRelease);
} }
if (appType != null && !appType.isEmpty()) {
filter.setAppType(appType);
} }
if (publishedApplicationRelease.size()>1){ if (appCategory != null && !appCategory.isEmpty()) {
String msg = "Application " + application.getName() filter.setAppCategory(appCategory);
+ " has more than one PUBLISHED application releases";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(msg).build();
} }
application.setApplicationReleases(publishedApplicationRelease); ApplicationList applications = applicationManager.getApplications(filter);
publishedApplicationRelease.clear(); if (applications.getApplications().isEmpty()) {
return Response.status(Response.Status.NOT_FOUND)
.entity("Couldn't find any application for requested query.").build();
} }
return Response.status(Response.Status.OK).entity(applications).build(); return Response.status(Response.Status.OK).entity(applications).build();
} catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while getting the application list"; String msg = "Error occurred while getting the application list for publisher ";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Path("/{appType}") @Path("/{uuid}")
public Response getApplication(@PathParam("appType") String appType, public Response getApplication(
@QueryParam("appName") String appName) { @PathParam("uuid") String uuid) {
ApplicationManager applicationManager = APIUtil.getApplicationManager(); ApplicationManager applicationManager = APIUtil.getApplicationManager();
List<Application> filteredApps = new ArrayList<>();
Filter filter;
try { try {
filter = new Filter(); Application application = applicationManager
filter.setOffset(0); .getApplicationByUuid(uuid, AppLifecycleState.PUBLISHED.toString());
filter.setLimit(20); return Response.status(Response.Status.OK).entity(application).build();
filter.setAppType(appType);
filter.setAppName(appName);
ApplicationList applications = applicationManager.getApplications(filter);
if (applications.getApplications().isEmpty()) {
return Response.status(Response.Status.NOT_FOUND)
.entity("Application with application type: " + appType + " not found").build();
}
for (Application application : applications.getApplications()) {
List<ApplicationRelease> publishedApplicationRelease = new ArrayList<>();
for (ApplicationRelease appRelease : application.getApplicationReleases()) {
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);
}
applications.setApplications(filteredApps);
return Response.status(Response.Status.OK).entity(applications).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).build(); String msg = "Application with application release UUID: " + uuid + " is not found";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
log.error("Error occurred while getting application with the application type: " + appType String msg = "Error occurred while getting application with the application release uuid: " + uuid;
+ " and application name: " + appName, e); log.error(msg, e);
return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }
} }
// todo --> get applications by category
} }

Loading…
Cancel
Save