Performance improvements

feature/appm-store/pbac
Charitha Goonetilleke 5 years ago
parent f1aa82c2b8
commit 4454ef26de

@ -18,14 +18,13 @@
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.service.IntegrationClientService;
import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
public class IntegrationClientServiceImpl implements IntegrationClientService {
private static IntegrationClientServiceImpl instance;
private static volatile IntegrationClientServiceImpl instance;
private StoreClient storeClient;
private PublisherClient publisherClient;
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 ConfigurationManager configurationManager;
private static volatile ConfigurationManager configurationManager;
private ConfigurationManager() {

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

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

@ -37,13 +37,7 @@ public class HelperUtil {
private static DeviceManagementProviderService deviceManagementProviderService;
private static GroupManagementProviderService groupManagementProviderService;
public static String generateApplicationUuid() {
return UUID.randomUUID().toString();
}
public static DeviceManagementProviderService getDeviceManagementProviderService() {
if (deviceManagementProviderService == null) {
synchronized (HelperUtil.class) {
if (deviceManagementProviderService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
deviceManagementProviderService = (DeviceManagementProviderService) ctx
@ -54,14 +48,10 @@ public class HelperUtil {
throw new IllegalStateException(msg);
}
}
}
}
return deviceManagementProviderService;
}
public static GroupManagementProviderService getGroupManagementProviderService() {
if (groupManagementProviderService == null) {
synchronized (HelperUtil.class) {
if (groupManagementProviderService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
groupManagementProviderService = (GroupManagementProviderService) ctx
@ -72,8 +62,6 @@ public class HelperUtil {
throw new IllegalStateException(msg);
}
}
}
}
return groupManagementProviderService;
}
}

@ -18,6 +18,14 @@
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 org.apache.commons.logging.Log;
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.exception.CertificateManagementException;
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.SCEPManager;
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.service.JWTClientManagerService;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.security.cert.X509Certificate;
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
@Path("/verify/{type}")
public Response verifyCertificate(@PathParam("type") String type, EnrollmentCertificate certificate) {
@ -323,7 +264,7 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()).build();
} 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);
return Response.serverError().entity(
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 COMMON_NAME_PRE = "C_";
private static CertificateCacheManager certificateCacheManager;
private static volatile CertificateCacheManager certificateCacheManager;
private CertificateCacheManagerImpl() {
@ -89,10 +89,10 @@ public class CertificateCacheManagerImpl implements CertificateCacheManager {
initializeCertificateCache();
}
if (manager != null) {
certificateCache = manager.<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
certificateCache = manager.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
} else {
certificateCache = Caching.getCacheManager(CertificateCacheManagerImpl.CERTIFICATE_CACHE_MANAGER).
<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
certificateCache = Caching.getCacheManager(CertificateCacheManagerImpl.CERTIFICATE_CACHE_MANAGER)
.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
}
}
return certificateCache;
@ -107,22 +107,22 @@ public class CertificateCacheManagerImpl implements CertificateCacheManager {
isCertificateCacheInitialized = true;
if (manager != null) {
if (certificateCacheExpiry > 0) {
manager.<String, CertificateResponse>createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE).
manager.createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE).
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build();
} else {
manager.<String, CertificateResponse>getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
manager.getCache(CertificateCacheManagerImpl.CERTIFICATE_CACHE);
}
} else {
if (certificateCacheExpiry > 0) {
Caching.getCacheManager().
<String, CertificateResponse>createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE).
Caching.getCacheManager()
.createCacheBuilder(CertificateCacheManagerImpl.CERTIFICATE_CACHE).
setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
certificateCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
Duration(TimeUnit.SECONDS, certificateCacheExpiry)).setStoreByValue(true).build();
} 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 {
private CertificateManagementConfig certificateManagementConfig;
private static CertificateConfigurationManager certificateConfigurationManager;
private static volatile CertificateConfigurationManager certificateConfigurationManager;
private final String certMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + File.separator +
CertificateManagementConstants.CERTIFICATE_CONFIG_XML_FILE;

@ -46,7 +46,7 @@ public class SCEPManagerImpl implements SCEPManager {
HashMap<Integer, Device> deviceHashMap = dms.getTenantedDevice(deviceIdentifier);
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");
}

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

@ -843,7 +843,7 @@ public interface DeviceManagementService {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/type/{device-type}/id/{device-id}/rename")
@Path("/type/{deviceType}/id/{deviceId}/rename")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
consumes = MediaType.APPLICATION_JSON,
@ -904,14 +904,14 @@ public interface DeviceManagementService {
name = "device-type",
value = "The device type, such as ios, android, or windows.",
required = true)
@PathParam("device-type")
@PathParam("deviceType")
@Size(max = 45)
String deviceType,
@ApiParam(
name = "device-id",
value = "The device identifier of the device.",
required = true)
@PathParam("device-id")
@PathParam("deviceId")
@Size(max = 45)
String deviceId);
@ -919,7 +919,7 @@ public interface DeviceManagementService {
//DELETE devices/type/virtual_firealarm/id/us06ww93auzp
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("/type/{device-type}/id/{device-id}")
@Path("/type/{deviceType}/id/{deviceId}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "DELETE",
@ -974,14 +974,14 @@ public interface DeviceManagementService {
name = "device-type",
value = "The device type, such as ios, android, or windows.",
required = true)
@PathParam("device-type")
@PathParam("deviceType")
@Size(max = 45)
String deviceType,
@ApiParam(
name = "device-id",
value = "The device identifier of the device.",
required = true)
@PathParam("device-id")
@PathParam("deviceId")
@Size(max = 45)
String deviceId);
@ -1923,7 +1923,7 @@ public interface DeviceManagementService {
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/compliance/{compliance-status}")
@Path("/compliance/{complianceStatus}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
@ -1958,7 +1958,7 @@ public interface DeviceManagementService {
value = "Compliance status for devices. If true, devices which are compliant with policies. " +
"If false, devices which are not compliant",
required = true)
@PathParam("compliance-status")
@PathParam("complianceStatus")
boolean complianceStatus,
@ApiParam(
name = "policy",
@ -2030,7 +2030,7 @@ public interface DeviceManagementService {
int id);
@GET
@Path("/{device-type}/applications")
@Path("/{deviceType}/applications")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
@ -2076,7 +2076,7 @@ public interface DeviceManagementService {
name = "device-type",
value = "Device type (platform) of the application",
required = true)
@PathParam("device-type")
@PathParam("deviceType")
String deviceType,
@ApiParam(
name = "offset",
@ -2092,7 +2092,7 @@ public interface DeviceManagementService {
int limit);
@GET
@Path("/application/{package-name}/versions")
@Path("/application/{packageName}/versions")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
@ -2133,6 +2133,6 @@ public interface DeviceManagementService {
name = "package-name",
value = "The package name of the app.",
required = true)
@PathParam("package-name")
@PathParam("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.common.Device;
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.exceptions.InvalidConfigurationException;
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.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.OperationManagementException;
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.";
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
.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
String errorMessage = "An active enrolment exists";
@ -136,7 +137,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
deviceIdentifier.setId(id);
deviceIdentifier.setType(type);
try {
device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier);
device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false);
} catch (DeviceManagementException e) {
String msg = "Error occurred while getting enrollment details of the device that carries the id '" +
id + "'";
@ -489,16 +490,16 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(msg);
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 &&
POLICY_MONITOR.equals(operation.getCode())) {
if (log.isDebugEnabled()) {
log.info("Received compliance status from POLICY_MONITOR operation ID: " + operation.getId());
}
List<ComplianceFeature> features = getComplianceFeatures(operation.getPayLoad());
DeviceMgtAPIUtils.getPolicyManagementService().checkCompliance(deviceIdentifier, features);
DeviceMgtAPIUtils.getPolicyManagementService().checkCompliance(device, features);
} else {
DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation);
DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(device, operation);
}
return Response.status(Response.Status.OK).build();
} catch (OperationManagementException e) {
@ -506,11 +507,11 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
} 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);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
} 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);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
}
@ -596,7 +597,7 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
JsonArray jsonArray = jsonElement.getAsJsonArray();
Gson gson = new Gson();
ComplianceFeature complianceFeature;
List<ComplianceFeature> complianceFeatures = new ArrayList<ComplianceFeature>(jsonArray.size());
List<ComplianceFeature> complianceFeatures = new ArrayList<>(jsonArray.size());
for (JsonElement element : jsonArray) {
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.device.details.mgt.DeviceDetailsMgtException;
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.ConfigOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
@ -374,9 +375,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@DELETE
@Override
@Path("/type/{device-type}/id/{device-id}")
public Response deleteDevice(@PathParam("device-type") String deviceType,
@PathParam("device-id") String deviceId) {
@Path("/type/{deviceType}/id/{deviceId}")
public Response deleteDevice(@PathParam("deviceType") String deviceType,
@PathParam("deviceId") String deviceId) {
DeviceManagementProviderService deviceManagementProviderService =
DeviceMgtAPIUtils.getDeviceManagementService();
try {
@ -399,9 +400,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@POST
@Override
@Path("/type/{device-type}/id/{device-id}/rename")
public Response renameDevice(Device device, @PathParam("device-type") String deviceType,
@PathParam("device-id") String deviceId) {
@Path("/type/{deviceType}/id/{deviceId}/rename")
public Response renameDevice(Device device, @PathParam("deviceType") String deviceType,
@PathParam("deviceId") String deviceId) {
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
try {
Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier
@ -810,9 +811,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
ApplicationManagementProviderService amc;
try {
RequestValidationUtil.validateDeviceIdentifier(type, id);
Device device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id, false);
amc = DeviceMgtAPIUtils.getAppManagementService();
applications = amc.getApplicationListForDevice(new DeviceIdentifier(id, type));
applications = amc.getApplicationListForDevice(device);
return Response.status(Response.Status.OK).entity(applications).build();
} catch (ApplicationManagementException e) {
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);
return Response.serverError().entity(
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) {
try {
RequestValidationUtil.validateDeviceIdentifier(type, id);
Device device = DeviceMgtAPIUtils.getDeviceManagementService()
.getDevice(new DeviceIdentifier(id, type), false);
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();
} catch (PolicyManagementException e) {
@ -879,6 +887,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
log.error(msg, e);
return Response.serverError().entity(
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) {
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();
Policy policy;
NonComplianceData complianceData;
DeviceCompliance deviceCompliance = new DeviceCompliance();
try {
policy = policyManagementService.getAppliedPolicyToDevice(new DeviceIdentifier(id, type));
policy = policyManagementService.getAppliedPolicyToDevice(device);
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving the current policy associated with the '" + type +
"' device, which carries the id '" + id + "'";
@ -910,8 +933,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} else {
try {
policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
complianceData = policyManagementService.getDeviceCompliance(
new DeviceIdentifier(id, type));
complianceData = policyManagementService.getDeviceCompliance(device);
deviceCompliance.setDeviceID(id);
deviceCompliance.setComplianceData(complianceData);
return Response.status(Response.Status.OK).entity(deviceCompliance).build();
@ -1090,9 +1112,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@GET
@Override
@Path("/compliance/{compliance-status}")
@Path("/compliance/{complianceStatus}")
public Response getPolicyCompliance(
@PathParam("compliance-status") boolean complianceStatus,
@PathParam("complianceStatus") boolean complianceStatus,
@QueryParam("policy") String policyId,
@DefaultValue("false")
@QueryParam("pending") boolean isPending,
@ -1152,9 +1174,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@GET
@Override
@Path("/{device-type}/applications")
@Path("/{deviceType}/applications")
public Response getApplications(
@PathParam("device-type") String deviceType,
@PathParam("deviceType") String deviceType,
@DefaultValue("0")
@QueryParam("offset") int offset,
@DefaultValue("10")
@ -1189,10 +1211,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
@GET
@Path("/application/{package-name}/versions")
@Path("/application/{packageName}/versions")
@Override
public Response getAppVersions(
@PathParam("package-name") String packageName) {
@PathParam("packageName") String packageName) {
try {
List<String> versions = DeviceMgtAPIUtils.getDeviceManagementService()
.getAppVersions(packageName);

@ -406,7 +406,17 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
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) {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(

@ -215,14 +215,11 @@ public class DeviceMgtAPIUtils {
}
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 ||
device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) {
return false;
} else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) {
return false;
}
return true;
} else return !EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus());
}

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

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

@ -18,6 +18,7 @@
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.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
@ -38,9 +39,13 @@ public interface NotificationManagementService {
* @throws NotificationManagementException
* if something goes wrong while adding the Notification.
*/
@Deprecated
boolean addNotification(DeviceIdentifier deviceId,
Notification notification) throws NotificationManagementException;
boolean addNotification(Device device,
Notification notification) throws NotificationManagementException;
/**
* 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
* operation list.
*/
@Deprecated
List<? extends Operation> getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException;
List<? extends Operation> getPendingOperations(Device device) throws OperationManagementException;

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

@ -96,7 +96,7 @@ public class DeviceManagementDAOFactory {
private static DataSource dataSource;
private static String databaseEngine;
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() {
if (databaseEngine != null) {

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

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

@ -54,19 +54,32 @@ public class NotificationManagementServiceImpl implements NotificationManagement
}
@Override
@Deprecated
public boolean addNotification(DeviceIdentifier deviceId,
Notification notification) throws NotificationManagementException {
if (log.isDebugEnabled()) {
log.debug("Adding a Notification : [" + notification.toString() + "]");
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);
}
int notificationId;
int tenantId = NotificationDAOUtil.getTenantId();
Device device = this.getDevice(deviceId);
if (device == null) {
throw new EntityDoesNotExistException("No device is found with type '" + deviceId.getType() +
"' 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 {
NotificationManagementDAOFactory.beginTransaction();
@ -84,17 +97,6 @@ public class NotificationManagementServiceImpl implements NotificationManagement
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
public boolean updateNotification(Notification notification) throws NotificationManagementException {
if (log.isDebugEnabled()) {

@ -1147,7 +1147,6 @@ public class OperationManagerImpl implements OperationManager {
try {
DeviceManagementDAOFactory.beginTransaction();
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
String user = this.getUser();
updateStatus = enrollmentDAO.setStatus(enrolmentId, status, tenantId);
DeviceManagementDAOFactory.commitTransaction();
} catch (DeviceManagementDAOException e) {
@ -1174,10 +1173,6 @@ public class OperationManagerImpl implements OperationManager {
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)
throws OperationManagementException {
List<Operation> operations = new ArrayList<>();

@ -197,6 +197,7 @@ public interface DeviceManagementProviderService {
* @return Device returns null when device is not available.
* @throws DeviceManagementException
*/
@Deprecated
Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException;
/**
@ -656,7 +657,6 @@ public interface DeviceManagementProviderService {
PaginationResult getOperations(DeviceIdentifier deviceId,
PaginationRequest request) throws OperationManagementException;
@Deprecated
List<? extends Operation> getPendingOperations(
DeviceIdentifier deviceId) throws OperationManagementException;
@ -770,9 +770,8 @@ public interface DeviceManagementProviderService {
/**
* 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;
List<Integer> getDeviceEnrolledTenants() throws DeviceManagementException;

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

@ -125,8 +125,7 @@ public class NotificationManagementServiceImplTests {
Notification notification = TestDataHolder.getNotification(1, Notification.Status.NEW.toString(),
testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123,
NOTIFICATION_OPERATION_ID, DEVICE_TYPE);
notificationManagementService.addNotification(new DeviceIdentifier(DEVICE_ID_PREFIX + 123,
DEVICE_TYPE), notification);
notificationManagementService.addNotification(testDeviceIdentifier, notification);
}
@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(),
testDeviceIdentifier.toString(), TEST_NOTIFICATION_DESCRIPTION, DEVICE_ID_PREFIX + 123,
NOTIFICATION_OPERATION_ID, DEVICE_TYPE);
notificationManagementService.addNotification(null, notification);
notificationManagementService.addNotification((DeviceIdentifier) null, notification);
}
@Test(dependsOnMethods = "addNotification", description = "This tests the updateNotification Method" +

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

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

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

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

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

@ -1113,8 +1113,8 @@ public class PolicyManagerImpl implements PolicyManager {
}
@Override
@Deprecated
public Policy getAppliedPolicyToDevice(DeviceIdentifier deviceId) throws PolicyManagementException {
Policy policy;
DeviceManagementProviderService service = new DeviceManagementProviderServiceImpl();
Device device;
try {
@ -1129,6 +1129,12 @@ public class PolicyManagerImpl implements PolicyManager {
} catch (DeviceManagementException 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 {
//int policyId = policyDAO.getAppliedPolicyId(device.getId());
PolicyManagementDAOFactory.openConnection();

Loading…
Cancel
Save