Merge branch 'performance-improvement' into 'master'

Performance improvements

See merge request entgra/carbon-device-mgt!487
feature/appm-store/pbac
Charitha Goonetilleke 5 years ago
commit c7025f07cf

@ -18,14 +18,13 @@
package org.wso2.carbon.apimgt.integration.client; package org.wso2.carbon.apimgt.integration.client;
import feign.RequestInterceptor;
import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient; import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService; import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.apimgt.integration.client.store.StoreClient; import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
public class IntegrationClientServiceImpl implements IntegrationClientService { public class IntegrationClientServiceImpl implements IntegrationClientService {
private static IntegrationClientServiceImpl instance; private static volatile IntegrationClientServiceImpl instance;
private StoreClient storeClient; private StoreClient storeClient;
private PublisherClient publisherClient; private PublisherClient publisherClient;
private OAuthRequestInterceptor oAuthRequestInterceptor; private OAuthRequestInterceptor oAuthRequestInterceptor;

@ -1,69 +0,0 @@
/*
* Copyright (c) 2015, 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.apimgt.webapp.publisher.config;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
/**
* This class will add, update custom permissions defined in resources.xml in webapps.
*/
public class APIResourceManager {
private static APIResourceManager resourceManager;
private List<APIResource> resourceList;
private APIResourceManager(){};
public static APIResourceManager getInstance() {
if (resourceManager == null) {
synchronized (APIResourceManager.class) {
if (resourceManager == null) {
resourceManager = new APIResourceManager();
}
}
}
return resourceManager;
}
public void initializeResources(InputStream resourceStream) throws APIResourceManagementException {
try {
if(resourceStream != null){
/* Un-marshaling Device Management configuration */
JAXBContext cdmContext = JAXBContext.newInstance(APIResourceConfiguration.class);
Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
APIResourceConfiguration resourcesConfiguration = (APIResourceConfiguration)
unmarshaller.unmarshal(resourceStream);
if((resourcesConfiguration != null) && (resourcesConfiguration.getResources() != null)){
this.resourceList = resourcesConfiguration.getResources();
}
}
} catch (JAXBException e) {
throw new APIResourceManagementException("Error occurred while initializing Data Source config", e);
}
}
public List<APIResource> getAPIResources(){
return resourceList;
}
}

@ -38,7 +38,7 @@ public class ConfigurationManager {
private static String configPath; private static String configPath;
private static ConfigurationManager configurationManager; private static volatile ConfigurationManager configurationManager;
private ConfigurationManager() { private ConfigurationManager() {

@ -58,11 +58,11 @@ public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class); private static Log log = LogFactory.getLog(APIUtil.class);
private static ApplicationManager applicationManager; private static volatile ApplicationManager applicationManager;
private static ApplicationStorageManager applicationStorageManager; private static volatile ApplicationStorageManager applicationStorageManager;
private static SubscriptionManager subscriptionManager; private static volatile SubscriptionManager subscriptionManager;
private static ReviewManager reviewManager; private static volatile ReviewManager reviewManager;
private static AppmDataHandler appmDataHandler; private static volatile AppmDataHandler appmDataHandler;
public static ApplicationManager getApplicationManager() { public static ApplicationManager getApplicationManager() {
if (applicationManager == null) { if (applicationManager == null) {

@ -311,9 +311,9 @@ public class DAOUtil {
} }
} }
private static ApplicationManager applicationManager; private static volatile ApplicationManager applicationManager;
private static ApplicationStorageManager applicationStorageManager; private static volatile ApplicationStorageManager applicationStorageManager;
private static SubscriptionManager subscriptionManager; private static volatile SubscriptionManager subscriptionManager;
public static ApplicationManager getApplicationManager() { public static ApplicationManager getApplicationManager() {
if (applicationManager == null) { if (applicationManager == null) {

@ -37,23 +37,15 @@ public class HelperUtil {
private static DeviceManagementProviderService deviceManagementProviderService; private static DeviceManagementProviderService deviceManagementProviderService;
private static GroupManagementProviderService groupManagementProviderService; private static GroupManagementProviderService groupManagementProviderService;
public static String generateApplicationUuid() {
return UUID.randomUUID().toString();
}
public static DeviceManagementProviderService getDeviceManagementProviderService() { public static DeviceManagementProviderService getDeviceManagementProviderService() {
if (deviceManagementProviderService == null) { if (deviceManagementProviderService == null) {
synchronized (HelperUtil.class) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
if (deviceManagementProviderService == null) { deviceManagementProviderService = (DeviceManagementProviderService) ctx
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); .getOSGiService(DeviceManagementProviderService.class, null);
deviceManagementProviderService = (DeviceManagementProviderService) ctx if (deviceManagementProviderService == null) {
.getOSGiService(DeviceManagementProviderService.class, null); String msg = "Device management provider service has not initialized.";
if (deviceManagementProviderService == null) { log.error(msg);
String msg = "Device management provider service has not initialized."; throw new IllegalStateException(msg);
log.error(msg);
throw new IllegalStateException(msg);
}
}
} }
} }
return deviceManagementProviderService; return deviceManagementProviderService;
@ -61,17 +53,13 @@ public class HelperUtil {
public static GroupManagementProviderService getGroupManagementProviderService() { public static GroupManagementProviderService getGroupManagementProviderService() {
if (groupManagementProviderService == null) { if (groupManagementProviderService == null) {
synchronized (HelperUtil.class) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
if (groupManagementProviderService == null) { groupManagementProviderService = (GroupManagementProviderService) ctx
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); .getOSGiService(GroupManagementProviderService.class, null);
groupManagementProviderService = (GroupManagementProviderService) ctx if (groupManagementProviderService == null) {
.getOSGiService(GroupManagementProviderService.class, null); String msg = "Group management provider service has not initialized.";
if (groupManagementProviderService == null) { log.error(msg);
String msg = "Group management provider service has not initialized."; throw new IllegalStateException(msg);
log.error(msg);
throw new IllegalStateException(msg);
}
}
} }
} }
return groupManagementProviderService; return groupManagementProviderService;

@ -18,6 +18,14 @@
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl; package org.wso2.carbon.certificate.mgt.cert.jaxrs.api.impl;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -31,7 +39,6 @@ import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.RequestValidationUtil
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator;
import org.wso2.carbon.certificate.mgt.core.scep.SCEPException; import org.wso2.carbon.certificate.mgt.core.scep.SCEPException;
import org.wso2.carbon.certificate.mgt.core.scep.SCEPManager; import org.wso2.carbon.certificate.mgt.core.scep.SCEPManager;
import org.wso2.carbon.certificate.mgt.core.scep.TenantedDeviceWrapper; import org.wso2.carbon.certificate.mgt.core.scep.TenantedDeviceWrapper;
@ -43,7 +50,6 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import javax.ws.rs.*;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
@ -170,71 +176,6 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
} }
} }
// @POST
// @Path("/verify/ios")
// public Response verifyIOSCertificate(@ApiParam(name = "certificate", value = "Mdm-Signature of the " +
// "certificate that needs to be verified", required = true) EnrollmentCertificate certificate) {
// try {
// CertificateManagementService certMgtService = CertificateMgtAPIUtils.getCertificateManagementService();
// X509Certificate cert = certMgtService.extractCertificateFromSignature(certificate.getPem());
// String challengeToken = certMgtService.extractChallengeToken(cert);
//
// if (challengeToken != null) {
// challengeToken = challengeToken.substring(challengeToken.indexOf("(") + 1).trim();
//
// SCEPManager scepManager = CertificateMgtAPIUtils.getSCEPManagerService();
// DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
// deviceIdentifier.setId(challengeToken);
// deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS);
// TenantedDeviceWrapper tenantedDeviceWrapper = scepManager.getValidatedDevice(deviceIdentifier);
//
// if (tenantedDeviceWrapper != null) {
// return Response.status(Response.Status.OK).entity("valid").build();
// }
// }
// } catch (SCEPException e) {
// String msg = "Error occurred while extracting information from certificate.";
// log.error(msg, e);
// return Response.serverError().entity(
// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
// } catch (KeystoreException e) {
// String msg = "Error occurred while converting PEM file to X509Certificate.";
// log.error(msg, e);
// return Response.serverError().entity(
// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
// }
// return Response.status(Response.Status.OK).entity("invalid").build();
// }
//
// @POST
// @Path("/verify/android")
// public Response verifyAndroidCertificate(@ApiParam(name = "certificate", value = "Base64 encoded .pem file of the " +
// "certificate that needs to be verified", required = true) EnrollmentCertificate certificate) {
// CertificateResponse certificateResponse = null;
// try {
// CertificateManagementService certMgtService = CertificateMgtAPIUtils.getCertificateManagementService();
// if (certificate.getSerial().toLowerCase().contains(PROXY_AUTH_MUTUAL_HEADER)) {
// certificateResponse = certMgtService.verifySubjectDN(certificate.getPem());
// } else {
// X509Certificate clientCertificate = certMgtService.pemToX509Certificate(certificate.getPem());
// if (clientCertificate != null) {
// certificateResponse = certMgtService.verifyPEMSignature(clientCertificate);
// }
// }
//
// if (certificateResponse != null && certificateResponse.getCommonName() != null && !certificateResponse
// .getCommonName().isEmpty()) {
// return Response.status(Response.Status.OK).entity("valid").build();
// }
// } catch (KeystoreException e) {
// String msg = "Error occurred while converting PEM file to X509Certificate.";
// log.error(msg, e);
// return Response.serverError().entity(
// new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
// }
// return Response.status(Response.Status.OK).entity("invalid").build();
// }
@POST @POST
@Path("/verify/{type}") @Path("/verify/{type}")
public Response verifyCertificate(@PathParam("type") String type, EnrollmentCertificate certificate) { public Response verifyCertificate(@PathParam("type") String type, EnrollmentCertificate certificate) {
@ -323,7 +264,7 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
} catch (JWTClientException e) { } catch (JWTClientException e) {
String msg = "Error occurred while converting PEM file to X509Certificate."; String msg = "Error occurred while getting jwt token.";
log.error(msg, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();

@ -38,7 +38,7 @@ public class CertificateCacheManagerImpl implements CertificateCacheManager {
private static String SERIAL_PRE = "S_"; private static String SERIAL_PRE = "S_";
private static String COMMON_NAME_PRE = "C_"; private static String COMMON_NAME_PRE = "C_";
private static CertificateCacheManager certificateCacheManager; private static volatile CertificateCacheManager certificateCacheManager;
private CertificateCacheManagerImpl() { private CertificateCacheManagerImpl() {
@ -89,10 +89,10 @@ public class CertificateCacheManagerImpl implements CertificateCacheManager {
initializeCertificateCache(); initializeCertificateCache();
} }
if (manager != null) { if (manager != null) {
certificateCache = manager.<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); certificateCache = manager.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
} else { } else {
certificateCache = Caching.getCacheManager(CertificateCacheManagerImpl.CERTIFICATE_CACHE_MANAGER). certificateCache = Caching.getCacheManager(CertificateCacheManagerImpl.CERTIFICATE_CACHE_MANAGER)
<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); .getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
} }
} }
return certificateCache; return certificateCache;
@ -107,22 +107,22 @@ public class CertificateCacheManagerImpl implements CertificateCacheManager {
isCertificateCacheInitialized = true; isCertificateCacheInitialized = true;
if (manager != null) { if (manager != null) {
if (certificateCacheExpiry > 0) { if (certificateCacheExpiry > 0) {
manager.<String, CertificateResponse>createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE). manager.createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE).
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build(); Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build();
} else { } else {
manager.<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); manager.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
} }
} else { } else {
if (certificateCacheExpiry > 0) { if (certificateCacheExpiry > 0) {
Caching.getCacheManager(). Caching.getCacheManager()
<String, CertificateResponse>createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE). .createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE).
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration. certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build(); Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build();
} else { } else {
Caching.getCacheManager().<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE); Caching.getCacheManager().getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
} }
} }
} }

@ -35,7 +35,7 @@ import java.io.File;
public class CertificateConfigurationManager { public class CertificateConfigurationManager {
private CertificateManagementConfig certificateManagementConfig; private CertificateManagementConfig certificateManagementConfig;
private static CertificateConfigurationManager certificateConfigurationManager; private static volatile CertificateConfigurationManager certificateConfigurationManager;
private final String certMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + private final String certMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
CertificateManagementConstants.CERTIFICATE_CONFIG_XML_FILE; CertificateManagementConstants.CERTIFICATE_CONFIG_XML_FILE;

@ -46,7 +46,7 @@ public class SCEPManagerImpl implements SCEPManager {
HashMap<Integer, Device> deviceHashMap = dms.getTenantedDevice(deviceIdentifier); HashMap<Integer, Device> deviceHashMap = dms.getTenantedDevice(deviceIdentifier);
Object[] keySet = deviceHashMap.keySet().toArray(); Object[] keySet = deviceHashMap.keySet().toArray();
if (keySet == null || keySet.length == 0) { if (keySet.length == 0) {
throw new SCEPException("Lookup device not found for the device identifier"); throw new SCEPException("Lookup device not found for the device identifier");
} }

@ -59,7 +59,7 @@ public class PullNotificationSubscriberImpl implements PullNotificationSubscribe
} }
@Override @Override
public void execute(DeviceIdentifier deviceIdentifier, Operation operation) throws PullNotificationExecutionFailedException { public void execute(Device device, Operation operation) throws PullNotificationExecutionFailedException {
try { try {
if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null && if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null &&
OperationCodes.POLICY_MONITOR.equals(operation.getCode())) { OperationCodes.POLICY_MONITOR.equals(operation.getCode())) {
@ -68,17 +68,17 @@ public class PullNotificationSubscriberImpl implements PullNotificationSubscribe
} }
List<ComplianceFeature> features = getComplianceFeatures(operation.getPayLoad()); List<ComplianceFeature> features = getComplianceFeatures(operation.getPayLoad());
PullNotificationDataHolder.getInstance().getPolicyManagerService() PullNotificationDataHolder.getInstance().getPolicyManagerService()
.checkCompliance(deviceIdentifier, features); .checkCompliance(device, features);
} else { } else {
PullNotificationDataHolder.getInstance().getDeviceManagementProviderService().updateOperation( PullNotificationDataHolder.getInstance().getDeviceManagementProviderService().updateOperation(
deviceIdentifier, operation); device, operation);
if (OperationCodes.INSTALL_APPLICATION.equals(operation.getCode()) if (OperationCodes.INSTALL_APPLICATION.equals(operation.getCode())
&& Operation.Status.COMPLETED == operation.getStatus()) { && Operation.Status.COMPLETED == operation.getStatus()) {
updateAppSubStatus(deviceIdentifier, operation.getId(), operation.getCode()); updateAppSubStatus(device, operation.getId(), operation.getCode());
} }
} }
} catch (OperationManagementException | DeviceManagementException | ApplicationManagementException e) { } catch (OperationManagementException | ApplicationManagementException e) {
throw new PullNotificationExecutionFailedException(e); throw new PullNotificationExecutionFailedException(e);
} catch (PolicyComplianceException e) { } catch (PolicyComplianceException e) {
throw new PullNotificationExecutionFailedException("Invalid payload format compliant feature", e); throw new PullNotificationExecutionFailedException("Invalid payload format compliant feature", e);
@ -109,10 +109,9 @@ public class PullNotificationSubscriberImpl implements PullNotificationSubscribe
return complianceFeatures; return complianceFeatures;
} }
private void updateAppSubStatus(DeviceIdentifier deviceIdentifier, int operationId, String status) private void updateAppSubStatus(Device device, int operationId, String status)
throws DeviceManagementException, ApplicationManagementException { throws ApplicationManagementException {
ApplicationManager applicationManager = PullNotificationDataHolder.getInstance().getApplicationManager(); ApplicationManager applicationManager = PullNotificationDataHolder.getInstance().getApplicationManager();
Device device = PullNotificationDataHolder.getInstance().getDeviceManagementProviderService().getDevice(deviceIdentifier);
applicationManager.updateSubsStatus(device.getId(), operationId, status); applicationManager.updateSubsStatus(device.getId(), operationId, status);
} }
} }

@ -843,7 +843,7 @@ public interface DeviceManagementService {
@POST @POST
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@Path("/type/{device-type}/id/{device-id}/rename") @Path("/type/{deviceType}/id/{deviceId}/rename")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
consumes = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON,
@ -904,14 +904,14 @@ public interface DeviceManagementService {
name = "device-type", name = "device-type",
value = "The device type, such as ios, android, or windows.", value = "The device type, such as ios, android, or windows.",
required = true) required = true)
@PathParam("device-type") @PathParam("deviceType")
@Size(max = 45) @Size(max = 45)
String deviceType, String deviceType,
@ApiParam( @ApiParam(
name = "device-id", name = "device-id",
value = "The device identifier of the device.", value = "The device identifier of the device.",
required = true) required = true)
@PathParam("device-id") @PathParam("deviceId")
@Size(max = 45) @Size(max = 45)
String deviceId); String deviceId);
@ -919,7 +919,7 @@ public interface DeviceManagementService {
//DELETE devices/type/virtual_firealarm/id/us06ww93auzp //DELETE devices/type/virtual_firealarm/id/us06ww93auzp
@DELETE @DELETE
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/type/{device-type}/id/{device-id}") @Path("/type/{deviceType}/id/{deviceId}")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE", httpMethod = "DELETE",
@ -974,14 +974,14 @@ public interface DeviceManagementService {
name = "device-type", name = "device-type",
value = "The device type, such as ios, android, or windows.", value = "The device type, such as ios, android, or windows.",
required = true) required = true)
@PathParam("device-type") @PathParam("deviceType")
@Size(max = 45) @Size(max = 45)
String deviceType, String deviceType,
@ApiParam( @ApiParam(
name = "device-id", name = "device-id",
value = "The device identifier of the device.", value = "The device identifier of the device.",
required = true) required = true)
@PathParam("device-id") @PathParam("deviceId")
@Size(max = 45) @Size(max = 45)
String deviceId); String deviceId);
@ -1923,7 +1923,7 @@ public interface DeviceManagementService {
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/compliance/{compliance-status}") @Path("/compliance/{complianceStatus}")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
@ -1958,7 +1958,7 @@ public interface DeviceManagementService {
value = "Compliance status for devices. If true, devices which are compliant with policies. " + value = "Compliance status for devices. If true, devices which are compliant with policies. " +
"If false, devices which are not compliant", "If false, devices which are not compliant",
required = true) required = true)
@PathParam("compliance-status") @PathParam("complianceStatus")
boolean complianceStatus, boolean complianceStatus,
@ApiParam( @ApiParam(
name = "policy", name = "policy",
@ -2030,7 +2030,7 @@ public interface DeviceManagementService {
int id); int id);
@GET @GET
@Path("/{device-type}/applications") @Path("/{deviceType}/applications")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
@ -2076,7 +2076,7 @@ public interface DeviceManagementService {
name = "device-type", name = "device-type",
value = "Device type (platform) of the application", value = "Device type (platform) of the application",
required = true) required = true)
@PathParam("device-type") @PathParam("deviceType")
String deviceType, String deviceType,
@ApiParam( @ApiParam(
name = "offset", name = "offset",
@ -2092,7 +2092,7 @@ public interface DeviceManagementService {
int limit); int limit);
@GET @GET
@Path("/application/{package-name}/versions") @Path("/application/{packageName}/versions")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
@ -2133,6 +2133,6 @@ public interface DeviceManagementService {
name = "package-name", name = "package-name",
value = "The package name of the app.", value = "The package name of the app.",
required = true) required = true)
@PathParam("package-name") @PathParam("packageName")
String packageName); String packageName);
} }

@ -29,11 +29,11 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature;
@ -84,7 +84,8 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
String errorMessage = "The payload of the device enrollment is incorrect."; String errorMessage = "The payload of the device enrollment is incorrect.";
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
} }
Device existingDevice = dms.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); Device existingDevice = dms.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()),
false);
if (existingDevice != null && existingDevice.getEnrolmentInfo() != null && existingDevice if (existingDevice != null && existingDevice.getEnrolmentInfo() != null && existingDevice
.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { .getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
String errorMessage = "An active enrolment exists"; String errorMessage = "An active enrolment exists";
@ -136,7 +137,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
deviceIdentifier.setId(id); deviceIdentifier.setId(id);
deviceIdentifier.setType(type); deviceIdentifier.setType(type);
try { try {
device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while getting enrollment details of the device that carries the id '" + String msg = "Error occurred while getting enrollment details of the device that carries the id '" +
id + "'"; id + "'";
@ -489,16 +490,16 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(msg); log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} }
Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false);
if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null && if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null &&
POLICY_MONITOR.equals(operation.getCode())) { POLICY_MONITOR.equals(operation.getCode())) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.info("Received compliance status from POLICY_MONITOR operation ID: " + operation.getId()); log.info("Received compliance status from POLICY_MONITOR operation ID: " + operation.getId());
} }
List<ComplianceFeature> features = getComplianceFeatures(operation.getPayLoad()); List<ComplianceFeature> features = getComplianceFeatures(operation.getPayLoad());
DeviceMgtAPIUtils.getPolicyManagementService().checkCompliance(deviceIdentifier, features); DeviceMgtAPIUtils.getPolicyManagementService().checkCompliance(device, features);
} else { } else {
DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation); DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(device, operation);
} }
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
@ -506,11 +507,11 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(errorMessage, e); log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String errorMessage = "Issue in retrieving deivce management service instance"; String errorMessage = "Issue in retrieving device management service instance";
log.error(errorMessage, e); log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
} catch (PolicyComplianceException e) { } catch (PolicyComplianceException e) {
String errorMessage = "Issue in retrieving deivce management service instance"; String errorMessage = "Issue in retrieving policy management service instance";
log.error(errorMessage, e); log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
} }
@ -596,7 +597,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
JsonArray jsonArray = jsonElement.getAsJsonArray(); JsonArray jsonArray = jsonElement.getAsJsonArray();
Gson gson = new Gson(); Gson gson = new Gson();
ComplianceFeature complianceFeature; ComplianceFeature complianceFeature;
List<ComplianceFeature> complianceFeatures = new ArrayList<ComplianceFeature>(jsonArray.size()); List<ComplianceFeature> complianceFeatures = new ArrayList<>(jsonArray.size());
for (JsonElement element : jsonArray) { for (JsonElement element : jsonArray) {
complianceFeature = gson.fromJson(element, ComplianceFeature.class); complianceFeature = gson.fromJson(element, ComplianceFeature.class);

@ -80,6 +80,7 @@ import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
@ -374,9 +375,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@DELETE @DELETE
@Override @Override
@Path("/type/{device-type}/id/{device-id}") @Path("/type/{deviceType}/id/{deviceId}")
public Response deleteDevice(@PathParam("device-type") String deviceType, public Response deleteDevice(@PathParam("deviceType") String deviceType,
@PathParam("device-id") String deviceId) { @PathParam("deviceId") String deviceId) {
DeviceManagementProviderService deviceManagementProviderService = DeviceManagementProviderService deviceManagementProviderService =
DeviceMgtAPIUtils.getDeviceManagementService(); DeviceMgtAPIUtils.getDeviceManagementService();
try { try {
@ -399,9 +400,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@POST @POST
@Override @Override
@Path("/type/{device-type}/id/{device-id}/rename") @Path("/type/{deviceType}/id/{deviceId}/rename")
public Response renameDevice(Device device, @PathParam("device-type") String deviceType, public Response renameDevice(Device device, @PathParam("deviceType") String deviceType,
@PathParam("device-id") String deviceId) { @PathParam("deviceId") String deviceId) {
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
try { try {
Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier
@ -810,9 +811,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
ApplicationManagementProviderService amc; ApplicationManagementProviderService amc;
try { try {
RequestValidationUtil.validateDeviceIdentifier(type, id); RequestValidationUtil.validateDeviceIdentifier(type, id);
Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id, false);
amc = DeviceMgtAPIUtils.getAppManagementService(); amc = DeviceMgtAPIUtils.getAppManagementService();
applications = amc.getApplicationListForDevice(new DeviceIdentifier(id, type)); applications = amc.getApplicationListForDevice(device);
return Response.status(Response.Status.OK).entity(applications).build(); return Response.status(Response.Status.OK).entity(applications).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while fetching the apps of the '" + type + "' device, which carries " + String msg = "Error occurred while fetching the apps of the '" + type + "' device, which carries " +
@ -820,6 +821,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
log.error(msg, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while getting '" + type + "' device, which carries " +
"the id '" + id + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} }
} }
@ -868,9 +875,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@HeaderParam("If-Modified-Since") String ifModifiedSince) { @HeaderParam("If-Modified-Since") String ifModifiedSince) {
try { try {
RequestValidationUtil.validateDeviceIdentifier(type, id); RequestValidationUtil.validateDeviceIdentifier(type, id);
Device device = DeviceMgtAPIUtils.getDeviceManagementService()
.getDevice(new DeviceIdentifier(id, type), false);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
Policy policy = policyManagementService.getAppliedPolicyToDevice(new DeviceIdentifier(id, type)); Policy policy = policyManagementService.getAppliedPolicyToDevice(device);
return Response.status(Response.Status.OK).entity(policy).build(); return Response.status(Response.Status.OK).entity(policy).build();
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
@ -879,6 +887,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
log.error(msg, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving '" + type + "' device, which carries the id '" + id + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} }
} }
@ -888,13 +901,23 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@PathParam("id") @Size(max = 45) String id) { @PathParam("id") @Size(max = 45) String id) {
RequestValidationUtil.validateDeviceIdentifier(type, id); RequestValidationUtil.validateDeviceIdentifier(type, id);
Device device;
try {
device = DeviceMgtAPIUtils.getDeviceManagementService()
.getDevice(new DeviceIdentifier(id, type), false);
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving '" + type + "' device, which carries the id '" + id + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
Policy policy; Policy policy;
NonComplianceData complianceData; NonComplianceData complianceData;
DeviceCompliance deviceCompliance = new DeviceCompliance(); DeviceCompliance deviceCompliance = new DeviceCompliance();
try { try {
policy = policyManagementService.getAppliedPolicyToDevice(new DeviceIdentifier(id, type)); policy = policyManagementService.getAppliedPolicyToDevice(device);
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving the current policy associated with the '" + type + String msg = "Error occurred while retrieving the current policy associated with the '" + type +
"' device, which carries the id '" + id + "'"; "' device, which carries the id '" + id + "'";
@ -910,8 +933,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} else { } else {
try { try {
policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
complianceData = policyManagementService.getDeviceCompliance( complianceData = policyManagementService.getDeviceCompliance(device);
new DeviceIdentifier(id, type));
deviceCompliance.setDeviceID(id); deviceCompliance.setDeviceID(id);
deviceCompliance.setComplianceData(complianceData); deviceCompliance.setComplianceData(complianceData);
return Response.status(Response.Status.OK).entity(deviceCompliance).build(); return Response.status(Response.Status.OK).entity(deviceCompliance).build();
@ -1090,9 +1112,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@GET @GET
@Override @Override
@Path("/compliance/{compliance-status}") @Path("/compliance/{complianceStatus}")
public Response getPolicyCompliance( public Response getPolicyCompliance(
@PathParam("compliance-status") boolean complianceStatus, @PathParam("complianceStatus") boolean complianceStatus,
@QueryParam("policy") String policyId, @QueryParam("policy") String policyId,
@DefaultValue("false") @DefaultValue("false")
@QueryParam("pending") boolean isPending, @QueryParam("pending") boolean isPending,
@ -1152,9 +1174,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@GET @GET
@Override @Override
@Path("/{device-type}/applications") @Path("/{deviceType}/applications")
public Response getApplications( public Response getApplications(
@PathParam("device-type") String deviceType, @PathParam("deviceType") String deviceType,
@DefaultValue("0") @DefaultValue("0")
@QueryParam("offset") int offset, @QueryParam("offset") int offset,
@DefaultValue("10") @DefaultValue("10")
@ -1189,10 +1211,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} }
@GET @GET
@Path("/application/{package-name}/versions") @Path("/application/{packageName}/versions")
@Override @Override
public Response getAppVersions( public Response getAppVersions(
@PathParam("package-name") String packageName) { @PathParam("packageName") String packageName) {
try { try {
List<String> versions = DeviceMgtAPIUtils.getDeviceManagementService() List<String> versions = DeviceMgtAPIUtils.getDeviceManagementService()
.getAppVersions(packageName); .getAppVersions(packageName);

@ -406,7 +406,17 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(deviceType); deviceIdentifier.setType(deviceType);
policy = policyManagementService.getAppliedPolicyToDevice(deviceIdentifier); Device device;
try {
device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving '" + deviceType + "' device, which carries the id '"
+ deviceId + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
policy = policyManagementService.getAppliedPolicyToDevice(device);
if (policy == null) { if (policy == null) {
return Response.status(Response.Status.NOT_FOUND).entity( return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage( new ErrorResponse.ErrorResponseBuilder().setMessage(

@ -215,14 +215,11 @@ public class DeviceMgtAPIUtils {
} }
public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
Device device = getDeviceManagementService().getDevice(deviceIdentifier); Device device = getDeviceManagementService().getDevice(deviceIdentifier, false);
if (device == null || device.getDeviceIdentifier() == null || if (device == null || device.getDeviceIdentifier() == null ||
device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) { device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) {
return false; return false;
} else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) { } else return !EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus());
return false;
}
return true;
} }

@ -39,10 +39,10 @@ import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublish
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl; import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherServiceImpl;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
@ -62,7 +62,6 @@ import org.wso2.carbon.policy.mgt.core.PolicyManagerServiceImpl;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import javax.cache.CacheManager;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.ArrayList; import java.util.ArrayList;
@ -88,8 +87,6 @@ public class DeviceAgentServiceTest {
private DeviceAgentService deviceAgentService; private DeviceAgentService deviceAgentService;
private EventStreamAdminServiceStub eventStreamAdminServiceStub; private EventStreamAdminServiceStub eventStreamAdminServiceStub;
private PrivilegedCarbonContext privilegedCarbonContext; private PrivilegedCarbonContext privilegedCarbonContext;
private CarbonContext carbonContext;
private CacheManager cacheManager;
private DeviceAccessAuthorizationService deviceAccessAuthorizationService; private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE"; private static final String TEST_DEVICE_TYPE = "TEST-DEVICE-TYPE";
private static final String TEST_DEVICE_IDENTIFIER = "11222334455"; private static final String TEST_DEVICE_IDENTIFIER = "11222334455";
@ -112,10 +109,8 @@ public class DeviceAgentServiceTest {
this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class, this.deviceAccessAuthorizationService = Mockito.mock(DeviceAccessAuthorizationServiceImpl.class,
Mockito.RETURNS_MOCKS); Mockito.RETURNS_MOCKS);
this.privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class, Mockito.RETURNS_MOCKS); this.privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class, Mockito.RETURNS_MOCKS);
this.carbonContext = Mockito.mock(CarbonContext.class, Mockito.RETURNS_MOCKS);
this.eventStreamAdminServiceStub = Mockito.mock(EventStreamAdminServiceStub.class, Mockito.RETURNS_MOCKS); this.eventStreamAdminServiceStub = Mockito.mock(EventStreamAdminServiceStub.class, Mockito.RETURNS_MOCKS);
demoDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); demoDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
this.cacheManager = Mockito.mock(CacheManager.class, Mockito.RETURNS_MOCKS);
} }
@Test(description = "Test device Enrollment when the device is null") @Test(description = "Test device Enrollment when the device is null")
@ -154,9 +149,11 @@ public class DeviceAgentServiceTest {
public void testEnrollExistingDevice() throws DeviceManagementException { public void testEnrollExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(demoDevice); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(demoDevice);
Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device device = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(device); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(device);
Response response = this.deviceAgentService.enrollDevice(device); Response response = this.deviceAgentService.enrollDevice(device);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode(),
@ -173,7 +170,8 @@ public class DeviceAgentServiceTest {
EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo(); EnrolmentInfo enrolmentInfo = demoDevice.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
demoDevice.setEnrolmentInfo(enrolmentInfo); demoDevice.setEnrolmentInfo(enrolmentInfo);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(demoDevice); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(demoDevice);
Response response = this.deviceAgentService.enrollDevice(demoDevice); Response response = this.deviceAgentService.enrollDevice(demoDevice);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -191,7 +189,8 @@ public class DeviceAgentServiceTest {
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo(); EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE); enrolmentInfo.setStatus(EnrolmentInfo.Status.INACTIVE);
device.setEnrolmentInfo(enrolmentInfo); device.setEnrolmentInfo(enrolmentInfo);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(device); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(device);
Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any())) Mockito.when(this.deviceManagementProviderService.enrollDevice(Mockito.any()))
.thenThrow(new DeviceManagementException()); .thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.enrollDevice(device); Response response = this.deviceAgentService.enrollDevice(device);
@ -214,7 +213,7 @@ public class DeviceAgentServiceTest {
} }
@Test(description = "Test dis-enrolling non existing device.") @Test(description = "Test dis-enrolling non existing device.")
public void testDisEnrollWithNonExistingDevice() throws DeviceManagementException { public void testDisEnrollWithNonExistingDevice() {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Response response = deviceAgentService.disEnrollDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
@ -240,7 +239,8 @@ public class DeviceAgentServiceTest {
public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException { public void testUpdateDeviceWithDeviceManagementException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenThrow(new Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenThrow(new
DeviceManagementException()); DeviceManagementException());
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -264,7 +264,8 @@ public class DeviceAgentServiceTest {
public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException { public void testUpdateDeviceWithNonExistingDevice() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(null); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(null);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
Assert.assertNotNull(response, "Response should not be null"); Assert.assertNotNull(response, "Response should not be null");
@ -281,7 +282,8 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenThrow(new DeviceAccessAuthorizationException()); .thenThrow(new DeviceAccessAuthorizationException());
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -300,7 +302,8 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService); "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(false); .thenReturn(false);
Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice); Response response = deviceAgentService.updateDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, testDevice);
@ -321,7 +324,8 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn(false);
@ -343,7 +347,8 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceManagementProviderService
.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())) Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any()))
@ -365,7 +370,7 @@ public class DeviceAgentServiceTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
"getAuthenticatedUser")).toReturn(AUTHENTICATED_USER); "getAuthenticatedUser")).toReturn(AUTHENTICATED_USER);
Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER); Device testDevice = DeviceMgtAPITestHelper.generateDummyDevice(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
Mockito.when(this.deviceManagementProviderService.getDevice((DeviceIdentifier) Mockito.any())).thenReturn(testDevice); Mockito.when(this.deviceManagementProviderService.getDevice(Mockito.any(DeviceIdentifier.class), Mockito.any(Boolean.class))).thenReturn(testDevice);
Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class))) Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
.thenReturn(true); .thenReturn(true);
Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true)); Mockito.when(this.deviceManagementProviderService.modifyEnrollment(Mockito.any())).thenReturn((true));
@ -944,7 +949,7 @@ public class DeviceAgentServiceTest {
.RETURNS_MOCKS); .RETURNS_MOCKS);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
.toReturn(policyManagementService); .toReturn(policyManagementService);
Mockito.when(policyManagementService.checkCompliance(Mockito.any(), Mockito.any())).thenReturn(true); Mockito.when(policyManagementService.checkCompliance(Mockito.any(Device.class), Mockito.any())).thenReturn(true);
Operation operation = new Operation(); Operation operation = new Operation();
operation.setCode(MONITOR_OPERATION); operation.setCode(MONITOR_OPERATION);
@ -973,7 +978,7 @@ public class DeviceAgentServiceTest {
deviceTypes.add(TEST_DEVICE_TYPE); deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes); Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()).thenReturn(deviceTypes);
Mockito.doThrow(new OperationManagementException()).when(this.deviceManagementProviderService) Mockito.doThrow(new OperationManagementException()).when(this.deviceManagementProviderService)
.updateOperation(Mockito.any(DeviceIdentifier.class), Mockito.any()); .updateOperation(Mockito.any(Device.class), Mockito.any());
Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER, Response response = this.deviceAgentService.updateOperation(TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER,
operation); operation);
Assert.assertNotNull(response, "The response should not be null"); Assert.assertNotNull(response, "The response should not be null");
@ -1013,7 +1018,7 @@ public class DeviceAgentServiceTest {
.RETURNS_MOCKS); .RETURNS_MOCKS);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
.toReturn(policyManagementService); .toReturn(policyManagementService);
Mockito.when(policyManagementService.checkCompliance(Mockito.any(), Mockito.any())) Mockito.when(policyManagementService.checkCompliance(Mockito.any(Device.class), Mockito.any()))
.thenThrow(new PolicyComplianceException()); .thenThrow(new PolicyComplianceException());
Operation operation = new Operation(); Operation operation = new Operation();
@ -1088,8 +1093,6 @@ public class DeviceAgentServiceTest {
public void testGetOperationsWithDeviceManagementException() throws DeviceManagementException { public void testGetOperationsWithDeviceManagementException() throws DeviceManagementException {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
List<String> deviceTypes = new ArrayList<>();
deviceTypes.add(TEST_DEVICE_TYPE);
Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes()) Mockito.when(this.deviceManagementProviderService.getAvailableDeviceTypes())
.thenThrow(new DeviceManagementException()); .thenThrow(new DeviceManagementException());
Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE, Response response = this.deviceAgentService.getOperationsByDeviceAndStatus(TEST_DEVICE_TYPE,

@ -621,6 +621,8 @@ public class DeviceManagementServiceImplTest {
.mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS); .mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService"))
.toReturn(applicationManagementProviderService); .toReturn(applicationManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5); .getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -633,8 +635,10 @@ public class DeviceManagementServiceImplTest {
.mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS); .mock(ApplicationManagementProviderService.class, Mockito.RETURNS_MOCKS);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getAppManagementService"))
.toReturn(applicationManagementProviderService); .toReturn(applicationManagementProviderService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when( Mockito.when(
applicationManagementProviderService.getApplicationListForDevice(Mockito.any(DeviceIdentifier.class))) applicationManagementProviderService.getApplicationListForDevice(Mockito.any(Device.class)))
.thenThrow(new ApplicationManagementException()); .thenThrow(new ApplicationManagementException());
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5); .getInstalledApplications(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), "", 10, 5);
@ -671,6 +675,8 @@ public class DeviceManagementServiceImplTest {
PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS); PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
.toReturn(policyManagerService); .toReturn(policyManagerService);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); .getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -682,7 +688,9 @@ public class DeviceManagementServiceImplTest {
PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS); PolicyManagerService policyManagerService = Mockito.mock(PolicyManagerService.class, Mockito.RETURNS_MOCKS);
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService")) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPolicyManagementService"))
.toReturn(policyManagerService); .toReturn(policyManagerService);
Mockito.when(policyManagerService.getAppliedPolicyToDevice(Mockito.any(DeviceIdentifier.class))) PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Mockito.when(policyManagerService.getAppliedPolicyToDevice(Mockito.any(Device.class)))
.thenThrow(new PolicyManagementException()); .thenThrow(new PolicyManagementException());
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null); .getEffectivePolicyOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.common.notification.mgt; package org.wso2.carbon.device.mgt.common.notification.mgt;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
@ -38,9 +39,13 @@ public interface NotificationManagementService {
* @throws NotificationManagementException * @throws NotificationManagementException
* if something goes wrong while adding the Notification. * if something goes wrong while adding the Notification.
*/ */
@Deprecated
boolean addNotification(DeviceIdentifier deviceId, boolean addNotification(DeviceIdentifier deviceId,
Notification notification) throws NotificationManagementException; Notification notification) throws NotificationManagementException;
boolean addNotification(Device device,
Notification notification) throws NotificationManagementException;
/** /**
* Method to update a notification in the database. * Method to update a notification in the database.
* *

@ -75,7 +75,6 @@ public interface OperationManager {
* @throws OperationManagementException If some unusual behaviour is observed while fetching the * @throws OperationManagementException If some unusual behaviour is observed while fetching the
* operation list. * operation list.
*/ */
@Deprecated
List<? extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException; List<? extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException;
List<? extends Operation> getPendingOperations(Device device) throws OperationManagementException; List<? extends Operation> getPendingOperations(Device device) throws OperationManagementException;

@ -18,8 +18,7 @@
*/ */
package org.wso2.carbon.device.mgt.common.pull.notification; package org.wso2.carbon.device.mgt.common.pull.notification;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import java.util.Map; import java.util.Map;
@ -31,7 +30,7 @@ public interface PullNotificationSubscriber {
void init(Map<String, String> properties); void init(Map<String, String> properties);
void execute(DeviceIdentifier deviceIdentifier, Operation operation) throws PullNotificationExecutionFailedException; void execute(Device device, Operation operation) throws PullNotificationExecutionFailedException;
void clean(); void clean();
} }

@ -96,7 +96,7 @@ public class DeviceManagementDAOFactory {
private static DataSource dataSource; private static DataSource dataSource;
private static String databaseEngine; private static String databaseEngine;
private static final Log log = LogFactory.getLog(DeviceManagementDAOFactory.class); private static final Log log = LogFactory.getLog(DeviceManagementDAOFactory.class);
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>(); private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public static DeviceDAO getDeviceDAO() { public static DeviceDAO getDeviceDAO() {
if (databaseEngine != null) { if (databaseEngine != null) {

@ -73,6 +73,7 @@ public interface DeviceInformationManager {
* @param deviceLocation - Device location object. * @param deviceLocation - Device location object.
* @throws DeviceDetailsMgtException * @throws DeviceDetailsMgtException
*/ */
@Deprecated
void addDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException; void addDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException;
void addDeviceLocation(Device device, DeviceLocation deviceLocation) throws DeviceDetailsMgtException; void addDeviceLocation(Device device, DeviceLocation deviceLocation) throws DeviceDetailsMgtException;

@ -291,6 +291,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
} }
@Override @Override
@Deprecated
public void addDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException { public void addDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException {
try { try {
Device device = DeviceManagementDataHolder.getInstance(). Device device = DeviceManagementDataHolder.getInstance().

@ -54,19 +54,32 @@ public class NotificationManagementServiceImpl implements NotificationManagement
} }
@Override @Override
@Deprecated
public boolean addNotification(DeviceIdentifier deviceId, public boolean addNotification(DeviceIdentifier deviceId,
Notification notification) throws NotificationManagementException { Notification notification) throws NotificationManagementException {
if (log.isDebugEnabled()) { Device device;
log.debug("Adding a Notification : [" + notification.toString() + "]"); try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider()
.getDevice(deviceId, false);
} catch (DeviceManagementException e) {
throw new NotificationManagementException("Error occurred while retrieving device data for " +
" adding notification", e);
} }
int notificationId;
int tenantId = NotificationDAOUtil.getTenantId();
Device device = this.getDevice(deviceId);
if (device == null) { if (device == null) {
throw new EntityDoesNotExistException("No device is found with type '" + deviceId.getType() + throw new EntityDoesNotExistException("No device is found with type '" + deviceId.getType() +
"' and id '" + deviceId.getId() + "'"); "' and id '" + deviceId.getId() + "'");
} }
return addNotification(device, notification);
}
@Override
public boolean addNotification(Device device,
Notification notification) throws NotificationManagementException {
if (log.isDebugEnabled()) {
log.debug("Adding a Notification : [" + notification.toString() + "]");
}
int notificationId;
int tenantId = NotificationDAOUtil.getTenantId();
try { try {
NotificationManagementDAOFactory.beginTransaction(); NotificationManagementDAOFactory.beginTransaction();
@ -84,17 +97,6 @@ public class NotificationManagementServiceImpl implements NotificationManagement
return true; return true;
} }
private Device getDevice(DeviceIdentifier deviceId) throws NotificationManagementException {
Device device;
try {
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId, false);
} catch (DeviceManagementException e) {
throw new NotificationManagementException("Error occurred while retrieving device data for " +
" adding notification", e);
}
return device;
}
@Override @Override
public boolean updateNotification(Notification notification) throws NotificationManagementException { public boolean updateNotification(Notification notification) throws NotificationManagementException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {

@ -1147,7 +1147,6 @@ public class OperationManagerImpl implements OperationManager {
try { try {
DeviceManagementDAOFactory.beginTransaction(); DeviceManagementDAOFactory.beginTransaction();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
String user = this.getUser();
updateStatus = enrollmentDAO.setStatus(enrolmentId, status, tenantId); updateStatus = enrollmentDAO.setStatus(enrolmentId, status, tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
@ -1174,10 +1173,6 @@ public class OperationManagerImpl implements OperationManager {
return false; return false;
} }
private boolean isSameUser(String user, String owner) {
return user.equalsIgnoreCase(owner);
}
private List<? extends Operation> getOperations(DeviceIdentifier deviceId, Operation.Status status, int enrolmentId) private List<? extends Operation> getOperations(DeviceIdentifier deviceId, Operation.Status status, int enrolmentId)
throws OperationManagementException { throws OperationManagementException {
List<Operation> operations = new ArrayList<>(); List<Operation> operations = new ArrayList<>();

@ -197,6 +197,7 @@ public interface DeviceManagementProviderService {
* @return Device returns null when device is not available. * @return Device returns null when device is not available.
* @throws DeviceManagementException * @throws DeviceManagementException
*/ */
@Deprecated
Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException; Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException;
/** /**
@ -656,7 +657,6 @@ public interface DeviceManagementProviderService {
PaginationResult getOperations(DeviceIdentifier deviceId, PaginationResult getOperations(DeviceIdentifier deviceId,
PaginationRequest request) throws OperationManagementException; PaginationRequest request) throws OperationManagementException;
@Deprecated
List<? extends Operation> getPendingOperations( List<? extends Operation> getPendingOperations(
DeviceIdentifier deviceId) throws OperationManagementException; DeviceIdentifier deviceId) throws OperationManagementException;
@ -770,15 +770,14 @@ public interface DeviceManagementProviderService {
/** /**
* This retrieves the device pull notification payload and passes to device type pull notification subscriber. * This retrieves the device pull notification payload and passes to device type pull notification subscriber.
* @throws PullNotificationExecutionFailedException
*/ */
void notifyPullNotificationSubscriber(DeviceIdentifier deviceIdentifier, Operation operation) void notifyPullNotificationSubscriber(Device device, Operation operation)
throws PullNotificationExecutionFailedException; throws PullNotificationExecutionFailedException;
List<Integer> getDeviceEnrolledTenants() throws DeviceManagementException; List<Integer> getDeviceEnrolledTenants() throws DeviceManagementException;
List<GeoCluster> findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, List<GeoCluster> findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast,
int geohashLength) throws DeviceManagementException; int geohashLength) throws DeviceManagementException;
int getDeviceCountOfTypeByStatus(String deviceType, String deviceStatus) throws DeviceManagementException; int getDeviceCountOfTypeByStatus(String deviceType, String deviceStatus) throws DeviceManagementException;

@ -1193,7 +1193,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
log.debug("No device is found upon the type '" + deviceIdentifier.getType() + "' and id '" + log.debug("No device is found upon the type '" + deviceIdentifier.getType() + "' and id '" +
deviceIdentifier.getId() + "'"); deviceIdentifier.getId() + "'");
} }
return null; return new HashMap<>();
} }
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
String msg = "Error occurred while obtaining the device for id '" + deviceIdentifier.getId() + "'"; String msg = "Error occurred while obtaining the device for id '" + deviceIdentifier.getId() + "'";
@ -1214,6 +1214,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
@Override @Override
@Deprecated
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
return this.getDevice(deviceId, true); return this.getDevice(deviceId, true);
} }
@ -3043,15 +3044,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
@Override @Override
public void notifyPullNotificationSubscriber(DeviceIdentifier deviceIdentifier, Operation operation) public void notifyPullNotificationSubscriber(Device device, Operation operation)
throws PullNotificationExecutionFailedException { throws PullNotificationExecutionFailedException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Notify pull notification subscriber"); log.debug("Notify pull notification subscriber");
} }
DeviceManagementService dms = DeviceManagementService dms =
pluginRepository.getDeviceManagementService(deviceIdentifier.getType(), this.getTenantId()); pluginRepository.getDeviceManagementService(device.getType(), this.getTenantId());
if (dms == null) { if (dms == null) {
String message = "Device type '" + deviceIdentifier.getType() + "' does not have an associated " + String message = "Device type '" + device.getType() + "' does not have an associated " +
"device management plugin registered within the framework"; "device management plugin registered within the framework";
log.error(message); log.error(message);
throw new PullNotificationExecutionFailedException(message); throw new PullNotificationExecutionFailedException(message);
@ -3059,11 +3060,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
PullNotificationSubscriber pullNotificationSubscriber = dms.getPullNotificationSubscriber(); PullNotificationSubscriber pullNotificationSubscriber = dms.getPullNotificationSubscriber();
if (pullNotificationSubscriber == null) { if (pullNotificationSubscriber == null) {
String message = "Pull Notification Subscriber is not configured " + String message = "Pull Notification Subscriber is not configured " +
"for device type" + deviceIdentifier.getType(); "for device type" + device.getType();
log.error(message); log.error(message);
throw new PullNotificationExecutionFailedException(message); throw new PullNotificationExecutionFailedException(message);
} }
pullNotificationSubscriber.execute(deviceIdentifier, operation); pullNotificationSubscriber.execute(device, operation);
} }
/** /**
@ -3427,7 +3428,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceLocation.setDistance(Double.parseDouble(distance)); deviceLocation.setDistance(Double.parseDouble(distance));
deviceLocation.setSpeed(Float.parseFloat(speed)); deviceLocation.setSpeed(Float.parseFloat(speed));
deviceLocation.setBearing(Float.parseFloat(bearing)); deviceLocation.setBearing(Float.parseFloat(bearing));
deviceInformationManager.addDeviceLocation(deviceLocation); deviceInformationManager.addDeviceLocation(device, deviceLocation);
} catch (Exception e) { } catch (Exception e) {
//We are not failing the execution since this is not critical for the functionality. But logging as //We are not failing the execution since this is not critical for the functionality. But logging as
// a warning for reference. // a warning for reference.

@ -125,8 +125,7 @@ public class NotificationManagementServiceImplTests {
Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(), Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(),
testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123, testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123,
NOTIFICATION_OPERATION_ID, DEVICE_TYPE); NOTIFICATION_OPERATION_ID, DEVICE_TYPE);
notificationManagementService.addNotification(new DeviceIdentifier(DEVICE_ID_PREFIX + 123, notificationManagementService.addNotification(testDeviceIdentifier, notification);
DEVICE_TYPE), notification);
} }
@Test(expectedExceptions = NotificationManagementException.class, description = "This tests the method getDevice which" + @Test(expectedExceptions = NotificationManagementException.class, description = "This tests the method getDevice which" +
@ -136,7 +135,7 @@ public class NotificationManagementServiceImplTests {
Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(), Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(),
testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123, testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123,
NOTIFICATION_OPERATION_ID, DEVICE_TYPE); NOTIFICATION_OPERATION_ID, DEVICE_TYPE);
notificationManagementService.addNotification(null, notification); notificationManagementService.addNotification((DeviceIdentifier) null, notification);
} }
@Test(dependsOnMethods = "addNotification", description = "This tests the updateNotification Method" + @Test(dependsOnMethods = "addNotification", description = "This tests the updateNotification Method" +

@ -19,6 +19,7 @@
package org.wso2.carbon.policy.mgt.core; package org.wso2.carbon.policy.mgt.core;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
@ -72,16 +73,28 @@ public interface PolicyManagerService {
int getPolicyCount() throws PolicyManagementException; int getPolicyCount() throws PolicyManagementException;
Policy getAppliedPolicyToDevice( @Deprecated
DeviceIdentifier deviceIdentifier) throws PolicyManagementException; Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException;
Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException;
@Deprecated
List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object
deviceResponse) throws PolicyComplianceException; deviceResponse) throws PolicyComplianceException;
List<ComplianceFeature> checkPolicyCompliance(Device device, Object
deviceResponse) throws PolicyComplianceException;
@Deprecated
boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws PolicyComplianceException; boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws PolicyComplianceException;
boolean checkCompliance(Device device, Object response) throws PolicyComplianceException;
@Deprecated
NonComplianceData getDeviceCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; NonComplianceData getDeviceCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException;
NonComplianceData getDeviceCompliance(Device device) throws PolicyComplianceException;
boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException;
PaginationResult getPolicyCompliance( PaginationResult getPolicyCompliance(

@ -37,6 +37,7 @@ package org.wso2.carbon.policy.mgt.core;
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.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
@ -216,36 +217,56 @@ public class PolicyManagerServiceImpl implements PolicyManagerService {
} }
@Override @Override
public Policy getAppliedPolicyToDevice( @Deprecated
DeviceIdentifier deviceIdentifier) throws PolicyManagementException { public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException {
return policyManager.getAppliedPolicyToDevice(deviceIdentifier); return policyManager.getAppliedPolicyToDevice(deviceIdentifier);
} }
@Override @Override
public Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException {
return policyManager.getAppliedPolicyToDevice(device);
}
@Override
@Deprecated
public List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object public List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object
deviceResponse) throws PolicyComplianceException { deviceResponse) throws PolicyComplianceException {
return monitoringManager.checkPolicyCompliance(deviceIdentifier, deviceResponse); return monitoringManager.checkPolicyCompliance(deviceIdentifier, deviceResponse);
} }
@Override @Override
public List<ComplianceFeature> checkPolicyCompliance(Device device, Object
deviceResponse) throws PolicyComplianceException {
return monitoringManager.checkPolicyCompliance(device, deviceResponse);
}
@Override
@Deprecated
public boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws public boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws
PolicyComplianceException { PolicyComplianceException {
List<ComplianceFeature> complianceFeatures = List<ComplianceFeature> complianceFeatures =
monitoringManager.checkPolicyCompliance(deviceIdentifier, response); monitoringManager.checkPolicyCompliance(deviceIdentifier, response);
if(complianceFeatures == null || complianceFeatures.isEmpty()) { return complianceFeatures == null || complianceFeatures.isEmpty();
return true; }
} else {
return false;
}
@Override
public boolean checkCompliance(Device device, Object response) throws PolicyComplianceException {
List<ComplianceFeature> complianceFeatures =
monitoringManager.checkPolicyCompliance(device, response);
return complianceFeatures == null || complianceFeatures.isEmpty();
} }
@Override @Override
@Deprecated
public NonComplianceData getDeviceCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { public NonComplianceData getDeviceCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
return monitoringManager.getDevicePolicyCompliance(deviceIdentifier); return monitoringManager.getDevicePolicyCompliance(deviceIdentifier);
} }
@Override
public NonComplianceData getDeviceCompliance(Device device) throws PolicyComplianceException {
return monitoringManager.getDevicePolicyCompliance(device);
}
@Override @Override
public boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { public boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException {
return monitoringManager.isCompliant(deviceIdentifier); return monitoringManager.isCompliant(deviceIdentifier);

@ -85,7 +85,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
identifier.setId(device.getDeviceIdentifier()); identifier.setId(device.getDeviceIdentifier());
identifier.setType(device.getType()); identifier.setType(device.getType());
Policy devicePolicy = this.getAppliedPolicyToDevice(identifier); Policy devicePolicy = this.getAppliedPolicyToDevice(device);
Policy policy = this.getEffectivePolicy(identifier); Policy policy = this.getEffectivePolicy(identifier);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>(); List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(identifier); deviceIdentifiers.add(identifier);
@ -193,14 +193,14 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
/** /**
* Provides the applied policy for give device * Provides the applied policy for give device
* *
* @param identifier Device Identifier * @param device Device
* @return Applied Policy * @return Applied Policy
* @throws PolicyDelegationException exception throws when retrieving applied policy for given device * @throws PolicyDelegationException exception throws when retrieving applied policy for given device
*/ */
public Policy getAppliedPolicyToDevice(DeviceIdentifier identifier) throws PolicyDelegationException { public Policy getAppliedPolicyToDevice(Device device) throws PolicyDelegationException {
try { try {
PolicyManagerService policyManagerService = new PolicyManagerServiceImpl(); PolicyManagerService policyManagerService = new PolicyManagerServiceImpl();
return policyManagerService.getAppliedPolicyToDevice(identifier); return policyManagerService.getAppliedPolicyToDevice(device);
} catch (PolicyManagementException e) { } catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving the applied policy for devices."; String msg = "Error occurred while retrieving the applied policy for devices.";
log.error(msg, e); log.error(msg, e);

@ -16,7 +16,6 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.policy.mgt.core.mgt; package org.wso2.carbon.policy.mgt.core.mgt;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
@ -31,21 +30,27 @@ import java.util.List;
public interface MonitoringManager { public interface MonitoringManager {
@Deprecated
List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse) List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse)
throws PolicyComplianceException; throws PolicyComplianceException;
List<ComplianceFeature> checkPolicyCompliance(Device device, Object deviceResponse)
throws PolicyComplianceException;
boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; boolean isCompliant(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException;
@Deprecated
NonComplianceData getDevicePolicyCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; NonComplianceData getDevicePolicyCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException;
NonComplianceData getDevicePolicyCompliance(Device device) throws PolicyComplianceException;
void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException; void addMonitoringOperation(List<Device> devices) throws PolicyComplianceException;
List<String> getDeviceTypes() throws PolicyComplianceException; List<String> getDeviceTypes() throws PolicyComplianceException;
PaginationResult getPolicyCompliance( PaginationResult getPolicyCompliance(
PaginationRequest paginationRequest, String policyId, boolean complianceStatus, boolean isPending, String fromDate, String toDate) PaginationRequest paginationRequest, String policyId, boolean complianceStatus, boolean isPending,
throws PolicyComplianceException; String fromDate, String toDate) throws PolicyComplianceException;
List<ComplianceFeature> getNoneComplianceFeatures(int complianceStatusId) List<ComplianceFeature> getNoneComplianceFeatures(int complianceStatusId)
throws PolicyComplianceException; throws PolicyComplianceException;

@ -80,8 +80,11 @@ public interface PolicyManager {
int getPolicyCount() throws PolicyManagementException; int getPolicyCount() throws PolicyManagementException;
@Deprecated
Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException;
Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException;
HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagementException; HashMap<Integer, Integer> getAppliedPolicyIdsDeviceIds() throws PolicyManagementException;
List<Policy> getPolicies(String type) throws PolicyManagementException; List<Policy> getPolicies(String type) throws PolicyManagementException;

@ -28,20 +28,23 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceData;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint;
import org.wso2.carbon.policy.mgt.common.monitor.*; import org.wso2.carbon.policy.mgt.common.monitor.PolicyDeviceWrapper;
import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAO;
import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException;
import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl; import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl;
import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder;
import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager;
@ -58,7 +61,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
private PolicyDAO policyDAO; private PolicyDAO policyDAO;
private MonitoringDAO monitoringDAO; private MonitoringDAO monitoringDAO;
private ComplianceDecisionPoint complianceDecisionPoint; private ComplianceDecisionPoint complianceDecisionPoint;
private PolicyConfiguration policyConfiguration;
private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class); private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class);
private static final String OPERATION_MONITOR = "MONITOR"; private static final String OPERATION_MONITOR = "MONITOR";
@ -68,34 +70,44 @@ public class MonitoringManagerImpl implements MonitoringManager {
this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO(); this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO();
this.monitoringDAO = PolicyManagementDAOFactory.getMonitoringDAO(); this.monitoringDAO = PolicyManagementDAOFactory.getMonitoringDAO();
this.complianceDecisionPoint = new ComplianceDecisionPointImpl(); this.complianceDecisionPoint = new ComplianceDecisionPointImpl();
this.policyConfiguration =
DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getPolicyConfiguration();
} }
@Override @Override
public List<ComplianceFeature> checkPolicyCompliance( @Deprecated
DeviceIdentifier deviceIdentifier, public List<ComplianceFeature> checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse)
Object deviceResponse) throws PolicyComplianceException { throws PolicyComplianceException {
DeviceManagementProviderService service =
PolicyManagementDataHolder.getInstance().getDeviceManagementService();
Device device;
try {
device = service.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
throw new PolicyComplianceException("Unable tor retrieve device data from DB for " +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e);
}
return checkPolicyCompliance(device, deviceResponse);
}
@Override
public List<ComplianceFeature> checkPolicyCompliance(Device device, Object deviceResponse)
throws PolicyComplianceException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(device.getDeviceIdentifier(), device.getType());
List<ComplianceFeature> complianceFeatures = new ArrayList<>(); List<ComplianceFeature> complianceFeatures = new ArrayList<>();
try { try {
DeviceManagementProviderService service =
PolicyManagementDataHolder.getInstance().getDeviceManagementService();
PolicyManager manager = PolicyManagementDataHolder.getInstance().getPolicyManager(); PolicyManager manager = PolicyManagementDataHolder.getInstance().getPolicyManager();
Device device = service.getDevice(deviceIdentifier, false); Policy policy = manager.getAppliedPolicyToDevice(device);
Policy policy = manager.getAppliedPolicyToDevice(deviceIdentifier);
if (policy != null) { if (policy != null) {
PolicyMonitoringManager monitoringService = PolicyManagementDataHolder.getInstance(). PolicyMonitoringManager monitoringService = PolicyManagementDataHolder.getInstance().
getDeviceManagementService().getPolicyMonitoringManager(deviceIdentifier.getType()); getDeviceManagementService().getPolicyMonitoringManager(device.getType());
NonComplianceData complianceData; NonComplianceData complianceData;
// This was retrieved from database because compliance id must be present for other dao operations to // This was retrieved from database because compliance id must be present for other dao operations to
// run. // run.
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
NonComplianceData cmd = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId()); NonComplianceData cmd = monitoringDAO.getCompliance(device.getId(),
complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier, device.getEnrolmentInfo().getId());
policy, deviceResponse); complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier, policy, deviceResponse);
if (cmd != null) { if (cmd != null) {
complianceData.setId(cmd.getId()); complianceData.setId(cmd.getId());
complianceData.setPolicy(policy); complianceData.setPolicy(policy);
@ -109,7 +121,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
} catch (MonitoringDAOException e) { } catch (MonitoringDAOException e) {
throw new PolicyComplianceException( throw new PolicyComplianceException(
"Unable to add the none compliance features to database for device " + "Unable to add the none compliance features to database for device " +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); device.getDeviceIdentifier() + " - " + device.getType(), e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
@ -133,7 +145,7 @@ public class MonitoringManagerImpl implements MonitoringManager {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyComplianceException( throw new PolicyComplianceException(
"Unable to add the none compliance features to database for device " + "Unable to add the none compliance features to database for device " +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); device.getDeviceIdentifier() + " - " + device.getType(), e);
} finally { } finally {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
@ -167,9 +179,6 @@ public class MonitoringManagerImpl implements MonitoringManager {
log.debug("There is no policy applied to this device, hence compliance monitoring was not called."); log.debug("There is no policy applied to this device, hence compliance monitoring was not called.");
} }
} }
} catch (DeviceManagementException e) {
throw new PolicyComplianceException("Unable tor retrieve device data from DB for " +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e);
} catch (PolicyManagerDAOException | PolicyManagementException e) { } catch (PolicyManagerDAOException | PolicyManagementException e) {
throw new PolicyComplianceException("Unable tor retrieve policy data from DB for device " + throw new PolicyComplianceException("Unable tor retrieve policy data from DB for device " +
deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e);
@ -208,26 +217,33 @@ public class MonitoringManagerImpl implements MonitoringManager {
} }
@Override @Override
@Deprecated
public NonComplianceData getDevicePolicyCompliance(DeviceIdentifier deviceIdentifier) throws public NonComplianceData getDevicePolicyCompliance(DeviceIdentifier deviceIdentifier) throws
PolicyComplianceException { PolicyComplianceException {
DeviceManagementProviderService service =
PolicyManagementDataHolder.getInstance().getDeviceManagementService();
Device device;
try {
device = service.getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
throw new PolicyComplianceException("Unable to retrieve device data for " + deviceIdentifier.getId() +
" - " + deviceIdentifier.getType(), e);
}
return getDevicePolicyCompliance(device);
}
@Override
public NonComplianceData getDevicePolicyCompliance(Device device) throws PolicyComplianceException {
NonComplianceData complianceData; NonComplianceData complianceData;
try { try {
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
DeviceManagementProviderService service =
PolicyManagementDataHolder.getInstance().getDeviceManagementService();
Device device = service.getDevice(deviceIdentifier, false);
complianceData = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId()); complianceData = monitoringDAO.getCompliance(device.getId(), device.getEnrolmentInfo().getId());
List<ComplianceFeature> complianceFeatures = List<ComplianceFeature> complianceFeatures =
monitoringDAO.getNoneComplianceFeatures(complianceData.getId()); monitoringDAO.getNoneComplianceFeatures(complianceData.getId());
complianceData.setComplianceFeatures(complianceFeatures); complianceData.setComplianceFeatures(complianceFeatures);
} catch (DeviceManagementException e) {
throw new PolicyComplianceException("Unable to retrieve device data for " + deviceIdentifier.getId() +
" - " + deviceIdentifier.getType(), e);
} catch (MonitoringDAOException e) { } catch (MonitoringDAOException e) {
throw new PolicyComplianceException("Unable to retrieve compliance data for " + deviceIdentifier.getId() + throw new PolicyComplianceException("Unable to retrieve compliance data for " + device.getType() +
" - " + deviceIdentifier.getType(), e); " device " + device.getDeviceIdentifier(), e);
} catch (SQLException e) { } catch (SQLException e) {
throw new PolicyComplianceException("Error occurred while opening a connection to the data source", e); throw new PolicyComplianceException("Error occurred while opening a connection to the data source", e);
} finally { } finally {

@ -31,7 +31,7 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.policy.mgt.core.mgt.impl; package org.wso2.carbon.policy.mgt.core.mgt.impl;
@ -145,7 +145,7 @@ public class PolicyManagerImpl implements PolicyManager {
if (policy.getCorrectiveActions() != null && !policy.getCorrectiveActions().isEmpty()) { if (policy.getCorrectiveActions() != null && !policy.getCorrectiveActions().isEmpty()) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Adding corrective actions for policy " + policy.getPolicyName() + log.debug("Adding corrective actions for policy " + policy.getPolicyName() +
" having policy id " + policy.getId()); " having policy id " + policy.getId());
} }
policyDAO.addCorrectiveActionsOfPolicy(policy.getCorrectiveActions(), policy.getId()); policyDAO.addCorrectiveActionsOfPolicy(policy.getCorrectiveActions(), policy.getId());
} }
@ -308,7 +308,7 @@ public class PolicyManagerImpl implements PolicyManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Updating corrective actions for policy " + policy.getPolicyName() + log.debug("Updating corrective actions for policy " + policy.getPolicyName() +
" having policy id " + policy.getId()); " having policy id " + policy.getId());
} }
if (!correctiveActionsToUpdate.isEmpty()) { if (!correctiveActionsToUpdate.isEmpty()) {
@ -655,7 +655,7 @@ public class PolicyManagerImpl implements PolicyManager {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Retrieving corrective actions of policy " + policy.getPolicyName() + log.debug("Retrieving corrective actions of policy " + policy.getPolicyName() +
" having policy id " + policy.getId()); " having policy id " + policy.getId());
} }
policy.setCorrectiveActions(policyDAO.getCorrectiveActionsOfPolicy(policyId)); policy.setCorrectiveActions(policyDAO.getCorrectiveActionsOfPolicy(policyId));
@ -986,7 +986,7 @@ public class PolicyManagerImpl implements PolicyManager {
PolicyManagementDAOFactory.rollbackTransaction(); PolicyManagementDAOFactory.rollbackTransaction();
throw new PolicyManagementException("Error occurred while applying the changes to policy operations.", e); throw new PolicyManagementException("Error occurred while applying the changes to policy operations.", e);
} finally { } finally {
if(transactionDone) { if (transactionDone) {
PolicyManagementDAOFactory.closeConnection(); PolicyManagementDAOFactory.closeConnection();
} }
} }
@ -1113,8 +1113,8 @@ public class PolicyManagerImpl implements PolicyManager {
} }
@Override @Override
@Deprecated
public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceId) throws PolicyManagementException { public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceId) throws PolicyManagementException {
Policy policy;
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl(); DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device; Device device;
try { try {
@ -1129,6 +1129,12 @@ public class PolicyManagerImpl implements PolicyManager {
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting device id.", e); throw new PolicyManagementException("Error occurred while getting device id.", e);
} }
return getAppliedPolicyToDevice(device);
}
@Override
public Policy getAppliedPolicyToDevice(Device device) throws PolicyManagementException {
Policy policy;
try { try {
//int policyId = policyDAO.getAppliedPolicyId(device.getId()); //int policyId = policyDAO.getAppliedPolicyId(device.getId());
PolicyManagementDAOFactory.openConnection(); PolicyManagementDAOFactory.openConnection();
@ -1262,7 +1268,7 @@ public class PolicyManagerImpl implements PolicyManager {
policy.setDeviceGroups(deviceGroupWrappers); policy.setDeviceGroups(deviceGroupWrappers);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Retrieving corrective actions for policy " + policy.getPolicyName() + log.debug("Retrieving corrective actions for policy " + policy.getPolicyName() +
" having policy id " + policy.getId()); " having policy id " + policy.getId());
} }
policy.setCorrectiveActions(policyDAO.getCorrectiveActionsOfPolicy(policy.getId())); policy.setCorrectiveActions(policyDAO.getCorrectiveActionsOfPolicy(policy.getId()));
} }

Loading…
Cancel
Save