Merge branch 'master' into 'master'

Performance Improvements

See merge request entgra/carbon-device-mgt-plugins!144
revert-dabc3590
Inosh Perara 5 years ago
commit c19246cf75

@ -61,9 +61,9 @@ import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceM
import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseServiceException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseServiceException;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.NotFoundException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.NotFoundException;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.UnexpectedServerErrorException;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidDeviceUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidDeviceUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidEnterpriseUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidEnterpriseUtils;
import org.wso2.carbon.device.mgt.mobile.android.api.invoker.GoogleAPIInvoker; import org.wso2.carbon.device.mgt.mobile.android.api.invoker.GoogleAPIInvoker;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException; import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
@ -737,7 +737,7 @@ public class AndroidEnterpriseAPIImpl implements AndroidEnterpriseAPI {
String trimmedPackage = productId.replaceFirst("app:", ""); String trimmedPackage = productId.replaceFirst("app:", "");
productIds.add(trimmedPackage); productIds.add(trimmedPackage);
} }
ApplicationManager appManager = AndroidEnterpriseUtils.getAppManagerServer(); ApplicationManager appManager = AndroidAPIUtils.getAppManagerService();
List<ApplicationReleaseDTO> packageDetails = appManager.getReleaseByPackageNames(productIds); List<ApplicationReleaseDTO> packageDetails = appManager.getReleaseByPackageNames(productIds);

@ -65,9 +65,9 @@ import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseU
import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser; import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.*; import org.wso2.carbon.device.mgt.mobile.android.common.exception.*;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidDeviceUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidDeviceUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidEnterpriseUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidEnterpriseUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@ -389,7 +389,7 @@ public class DeviceManagementAPIImpl implements DeviceManagementAPI {
googleAPIInvoker.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(), googleAPIInvoker.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(),
AndroidEnterpriseUtils.convertToDeviceInstance(enterpriseInstallPolicy)); AndroidEnterpriseUtils.convertToDeviceInstance(enterpriseInstallPolicy));
} }
AndroidEnterpriseUtils.getAppSubscriptionService().performEntAppSubscription(uuid, AndroidAPIUtils.getAppSubscriptionService().performEntAppSubscription(uuid,
Arrays.asList(CarbonContext.getThreadLocalCarbonContext().getUsername()), Arrays.asList(CarbonContext.getThreadLocalCarbonContext().getUsername()),
SubscriptionType.USER.toString(), SubAction.INSTALL.toString(), false); SubscriptionType.USER.toString(), SubAction.INSTALL.toString(), false);
} }

@ -38,11 +38,14 @@ package org.wso2.carbon.device.mgt.mobile.android.api.impl;
import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpStatusCodes;
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.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
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.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
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.core.operation.mgt.ProfileOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.device.mgt.mobile.android.api.DeviceManagementAdminAPI; import org.wso2.carbon.device.mgt.mobile.android.api.DeviceManagementAdminAPI;
import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse; import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationInstallationBeanWrapper; import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationInstallationBeanWrapper;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationRestrictionBeanWrapper; import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationRestrictionBeanWrapper;
@ -66,7 +69,7 @@ import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WipeDataBea
import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@ -75,6 +78,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@Path("/admin/devices") @Path("/admin/devices")
@ -1003,6 +1007,7 @@ public class DeviceManagementAdminAPIImpl implements DeviceManagementAdminAPI {
.setMessage(errorMessage).build()).build(); .setMessage(errorMessage).build()).build();
} }
} }
@POST @POST
@Path("/send-app-conf") @Path("/send-app-conf")
@Override @Override
@ -1015,9 +1020,17 @@ public class DeviceManagementAdminAPIImpl implements DeviceManagementAdminAPI {
try{ try{
AndroidService androidService = AndroidAPIUtils.getAndroidService(); AndroidService androidService = AndroidAPIUtils.getAndroidService();
ProfileOperation operation = androidService.sendApplicationConfiguration(applicationRestrictionBeanWrapper); ProfileOperation operation = androidService.sendApplicationConfiguration(applicationRestrictionBeanWrapper);
Response response = AndroidAPIUtils.getOperationResponse(applicationRestrictionBeanWrapper.getDeviceIDs(), DeviceIdentifier deviceIdentifier;
operation); List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
return Response.status(Response.Status.CREATED).entity(response).build(); for (String deviceId : applicationRestrictionBeanWrapper.getDeviceIDs()) {
deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID);
deviceIdentifiers.add(deviceIdentifier);
}
Activity activity = AndroidAPIUtils.getDeviceManagementService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers);
return Response.status(Response.Status.CREATED).entity(activity).build();
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);

@ -48,7 +48,7 @@ import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;

@ -29,7 +29,7 @@ import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EventBeanWrapper; import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EventBeanWrapper;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.*; import org.wso2.carbon.device.mgt.mobile.android.common.exception.*;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils; import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;

@ -0,0 +1,145 @@
/*
* 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.device.mgt.mobile.android.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
/**
* AndroidAPIUtil class provides utility functions used by Android REST-API classes.
*/
public class AndroidAPIUtils {
private static Log log = LogFactory.getLog(AndroidAPIUtils.class);
private static ApplicationManager applicationManager = null;
private static SubscriptionManager subscriptionManager = null;
private static DeviceManagementProviderService deviceManagementProviderService = null;
private static AndroidGoogleEnterpriseService androidGoogleEnterpriseService = null;
private static AndroidService androidService = null;
private static PolicyManagerService policyManagerService = null;
private static DeviceTypeCommonService deviceTypeCommonService = null;
private AndroidAPIUtils() {
throw new IllegalStateException("Utility class");
}
public static ApplicationManager getAppManagerService() {
if (applicationManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
applicationManager = (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
if (applicationManager == null) {
String msg = "Application Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return applicationManager;
}
public static SubscriptionManager getAppSubscriptionService() {
if (subscriptionManager == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
subscriptionManager = (SubscriptionManager) ctx.getOSGiService(SubscriptionManager.class, null);
if (subscriptionManager == null) {
String msg = "Application Subscription service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return subscriptionManager;
}
public static AndroidGoogleEnterpriseService getAndroidPluginService() {
if (androidGoogleEnterpriseService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
androidGoogleEnterpriseService =
(AndroidGoogleEnterpriseService) ctx.getOSGiService(AndroidGoogleEnterpriseService.class, null);
if (androidGoogleEnterpriseService == null) {
String msg = "Android plugin service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return androidGoogleEnterpriseService;
}
public static AndroidService getAndroidService() {
if (androidService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
androidService = (AndroidService) ctx.getOSGiService(AndroidService.class, null);
if (androidService == null) {
String msg = "Android service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return androidService;
}
public static DeviceManagementProviderService getDeviceManagementService() {
if (deviceManagementProviderService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return deviceManagementProviderService;
}
public static DeviceTypeCommonService getDeviceTypeCommonService() {
if (deviceTypeCommonService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
deviceTypeCommonService = (DeviceTypeCommonService) ctx
.getOSGiService(DeviceTypeCommonService.class, null);
if (deviceTypeCommonService == null) {
String msg = "Device Type Common service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return deviceTypeCommonService;
}
public static PolicyManagerService getPolicyManagerService() {
if (policyManagerService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
policyManagerService = (PolicyManagerService) ctx.getOSGiService(PolicyManagerService.class, null);
if (policyManagerService == null) {
String msg = "Policy Manager service has not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return policyManagerService;
}
}

@ -0,0 +1,126 @@
/*
* Copyright (c) 2016, 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.
*
*
* Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.mobile.android.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
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.ProfileFeature;
import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import java.util.ArrayList;
import java.util.List;
/**
* Util class for holding Android device related util methods.
*/
public class AndroidDeviceUtils {
private static Log log = LogFactory.getLog(AndroidDeviceUtils.class);
private AndroidDeviceUtils() {
throw new IllegalStateException("Utility class");
}
public static DeviceIdentifier convertToDeviceIdentifierObject(String deviceId) {
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setId(deviceId);
identifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
return identifier;
}
public static Activity getOperationResponse(List<String> deviceIDs, Operation operation)
throws OperationManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
if (deviceIDs == null || deviceIDs.isEmpty()) {
String errorMessage = "Device identifier list is empty";
log.error(errorMessage);
throw new BadRequestException(errorMessage);
}
DeviceIdentifier deviceIdentifier;
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
for (String deviceId : deviceIDs) {
deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID);
deviceIdentifiers.add(deviceIdentifier);
}
return AndroidAPIUtils.getDeviceManagementService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers);
}
public static String getAndroidConfig(PlatformConfiguration configuration, String key) {
String value = null;
if (configuration != null && configuration.getConfiguration() != null && configuration
.getConfiguration().size() > 0) {
List<ConfigurationEntry> configurations = configuration.getConfiguration();
for (ConfigurationEntry configurationEntry : configurations) {
if (configurationEntry.getName().equals(key)) {
value = (String)configurationEntry.getValue();
break;
}
}
}
return value;
}
public static ProfileFeature getEnrollmentFeature(DeviceIdentifier deviceIdentifier) throws
FeatureManagementException {
PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService();
List<ProfileFeature> effectiveProfileFeatures= policyManagerService.getEffectiveFeatures(deviceIdentifier);
if (effectiveProfileFeatures != null) {
for (ProfileFeature feature : effectiveProfileFeatures) {
if (AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE
.equals(feature.getFeatureCode())) {
return feature;
}
}
}
return null;
}
}

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.mobile.android.core.util; package org.wso2.carbon.device.mgt.mobile.android.api.util;
import com.google.api.services.androidenterprise.model.AppVersion; import com.google.api.services.androidenterprise.model.AppVersion;
import com.google.api.services.androidenterprise.model.AutoInstallConstraint; import com.google.api.services.androidenterprise.model.AutoInstallConstraint;
@ -43,7 +43,6 @@ import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManage
import org.wso2.carbon.device.application.mgt.common.response.Application; import org.wso2.carbon.device.application.mgt.common.response.Application;
import org.wso2.carbon.device.application.mgt.common.response.Category; import org.wso2.carbon.device.application.mgt.common.response.Category;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationUpdateWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationUpdateWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.PublicAppReleaseWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.PublicAppReleaseWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.PublicAppWrapper; import org.wso2.carbon.device.application.mgt.common.wrapper.PublicAppWrapper;
@ -80,16 +79,15 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
public class AndroidEnterpriseUtils { public class AndroidEnterpriseUtils {
private static Log log = LogFactory.getLog(AndroidEnterpriseUtils.class); private static Log log = LogFactory.getLog(AndroidEnterpriseUtils.class);
private static RealmService realmService = null;
private static List<String> templates = Arrays.asList(AndroidConstants private static List<String> templates = Arrays.asList(AndroidConstants
.USER_CLAIM_EMAIL_ADDRESS_PLACEHOLDER, AndroidConstants.USER_CLAIM_FIRST_NAME_PLACEHOLDER, .USER_CLAIM_EMAIL_ADDRESS_PLACEHOLDER, AndroidConstants.USER_CLAIM_FIRST_NAME_PLACEHOLDER,
AndroidConstants.USER_CLAIM_LAST_NAME_PLACEHOLDER); AndroidConstants.USER_CLAIM_LAST_NAME_PLACEHOLDER);
public static Device convertToDeviceInstance(EnterpriseInstallPolicy enterpriseInstallPolicy) public static Device convertToDeviceInstance(EnterpriseInstallPolicy enterpriseInstallPolicy)
throws EnterpriseServiceException { throws EnterpriseServiceException {
Device device = new Device(); Device device = new Device();
@ -171,15 +169,16 @@ public class AndroidEnterpriseUtils {
} }
private static UserStoreManager getUserStoreManager() throws EnterpriseServiceException { private static UserStoreManager getUserStoreManager() throws EnterpriseServiceException {
RealmService realmService;
UserStoreManager userStoreManager = null;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) { if (realmService == null) {
String msg = "Realm service has not initialized."; realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
log.error(msg); if (realmService == null) {
throw new IllegalStateException(msg); String msg = "Realm service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
} }
UserStoreManager userStoreManager;
int tenantId = ctx.getTenantId(); int tenantId = ctx.getTenantId();
try { try {
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
@ -224,9 +223,9 @@ public class AndroidEnterpriseUtils {
public static EnterpriseConfigs getEnterpriseConfigs() throws AndroidDeviceMgtPluginException { public static EnterpriseConfigs getEnterpriseConfigs() throws AndroidDeviceMgtPluginException {
EnterpriseConfigs enterpriseConfigs = getEnterpriseConfigsFromGoogle(); EnterpriseConfigs enterpriseConfigs = getEnterpriseConfigsFromGoogle();
if (enterpriseConfigs.getErrorResponse() != null) { if (enterpriseConfigs.getErrorResponse() != null) {
if (enterpriseConfigs.getErrorResponse().getCode() == 500l) { if (enterpriseConfigs.getErrorResponse().getCode() == 500) {
throw new UnexpectedServerErrorException(enterpriseConfigs.getErrorResponse().getMessage()); throw new UnexpectedServerErrorException(enterpriseConfigs.getErrorResponse().getMessage());
} else if (enterpriseConfigs.getErrorResponse().getCode() == 500l) { } else if (enterpriseConfigs.getErrorResponse().getCode() == 404) {
throw new NotFoundException(enterpriseConfigs.getErrorResponse().getMessage()); throw new NotFoundException(enterpriseConfigs.getErrorResponse().getMessage());
} }
} }
@ -263,25 +262,17 @@ public class AndroidEnterpriseUtils {
return enterpriseConfigs; return enterpriseConfigs;
} }
public static ApplicationManager getAppManagerServer() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
}
public static SubscriptionManager getAppSubscriptionService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return (SubscriptionManager) ctx.getOSGiService(SubscriptionManager.class, null);
}
public static void persistApp(ProductsListResponse productListResponse) throws ApplicationManagementException { public static void persistApp(ProductsListResponse productListResponse) throws ApplicationManagementException {
ApplicationManager applicationManager = getAppManagerServer(); ApplicationManager applicationManager = AndroidAPIUtils.getAppManagerService();
List<Category> categories = applicationManager.getRegisteredCategories(); List<Category> categories = applicationManager.getRegisteredCategories();
if (productListResponse != null && productListResponse.getProduct() != null if (productListResponse != null && productListResponse.getProduct() != null
&& !productListResponse.getProduct().isEmpty()) { && !productListResponse.getProduct().isEmpty()) {
List<String> packageNamesOfApps = productListResponse.getProduct().stream() List<String> packageNamesOfApps = new ArrayList<>();
.map(product -> (product.getProductId().replaceFirst("app:", ""))).collect(Collectors.toList()); for (Product product : productListResponse.getProduct()) {
packageNamesOfApps.add(product.getProductId().replaceFirst("app:", ""));
}
List<Application> existingApps = applicationManager.getApplications(packageNamesOfApps); List<Application> existingApps = applicationManager.getApplications(packageNamesOfApps);
List<Product> products = productListResponse.getProduct(); List<Product> products = productListResponse.getProduct();
@ -303,8 +294,7 @@ public class AndroidEnterpriseUtils {
publicAppReleaseWrapper.setDescription(product.getRecentChanges()); publicAppReleaseWrapper.setDescription(product.getRecentChanges());
publicAppReleaseWrapper.setReleaseType("ga"); publicAppReleaseWrapper.setReleaseType("ga");
publicAppReleaseWrapper.setVersion(getAppString(product.getAppVersion())); publicAppReleaseWrapper.setVersion(getAppString(product.getAppVersion()));
publicAppReleaseWrapper publicAppReleaseWrapper.setSupportedOsVersions(product.getMinAndroidSdkVersion() + "-ALL");
.setSupportedOsVersions(String.valueOf(product.getMinAndroidSdkVersion()) + "-ALL");
ApplicationArtifact applicationArtifact = generateArtifacts(product); ApplicationArtifact applicationArtifact = generateArtifacts(product);
applicationManager.updatePubAppRelease(app.getApplicationReleases().get(0).getUuid(), applicationManager.updatePubAppRelease(app.getApplicationReleases().get(0).getUuid(),
@ -359,13 +349,6 @@ public class AndroidEnterpriseUtils {
} }
} }
/**
* To generate {@link ApplicationUpdateWrapper}
*
* @param product {@link Product}
* @param categories List of categories registered with app manager
* @return {@link ApplicationUpdateWrapper}
*/
private static ApplicationUpdateWrapper generatePubAppUpdateWrapper(Product product, List<Category> categories) { private static ApplicationUpdateWrapper generatePubAppUpdateWrapper(Product product, List<Category> categories) {
ApplicationUpdateWrapper applicationUpdateWrapper = new ApplicationUpdateWrapper(); ApplicationUpdateWrapper applicationUpdateWrapper = new ApplicationUpdateWrapper();
applicationUpdateWrapper.setName(product.getTitle()); applicationUpdateWrapper.setName(product.getTitle());
@ -396,13 +379,6 @@ public class AndroidEnterpriseUtils {
return applicationUpdateWrapper; return applicationUpdateWrapper;
} }
/**
* To generate {@link PublicAppWrapper}
*
* @param product {@link Product}
* @param categories List of categories registered with app manager
* @return {@link PublicAppWrapper}
*/
private static PublicAppWrapper generatePubAppWrapper(Product product, List<Category> categories) { private static PublicAppWrapper generatePubAppWrapper(Product product, List<Category> categories) {
PublicAppWrapper publicAppWrapper = new PublicAppWrapper(); PublicAppWrapper publicAppWrapper = new PublicAppWrapper();
publicAppWrapper.setName(product.getTitle()); publicAppWrapper.setName(product.getTitle());
@ -434,13 +410,6 @@ public class AndroidEnterpriseUtils {
return publicAppWrapper; return publicAppWrapper;
} }
/**
* To generate {@link ApplicationArtifact}
*
* @param product {@link Product}
* @return {@link ApplicationArtifact}
* @throws ApplicationManagementException if I/O exception occurred while generating application artifact.
*/
private static ApplicationArtifact generateArtifacts(Product product) throws ApplicationManagementException { private static ApplicationArtifact generateArtifacts(Product product) throws ApplicationManagementException {
ApplicationArtifact applicationArtifact = new ApplicationArtifact(); ApplicationArtifact applicationArtifact = new ApplicationArtifact();
try { try {

@ -22,16 +22,16 @@ package org.wso2.carbon.device.mgt.mobile.android.common.config.datasource;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "iosDBConfigurations") @XmlRootElement(name = "AndroidDBConfigurations")
public class AndroidDataSourceConfigurations { public class AndroidDBConfigurations {
private MobileDataSourceConfig iosDataSourceConfiguration; private MobileDataSourceConfig DataSourceConfiguration;
@XmlElement(name = "DataSourceConfiguration") @XmlElement(name = "DataSourceConfiguration")
public MobileDataSourceConfig getIosDataSourceConfiguration() { public MobileDataSourceConfig getDataSourceConfiguration() {
return iosDataSourceConfiguration; return DataSourceConfiguration;
} }
public void setIosDataSourceConfiguration(MobileDataSourceConfig iosDataSourceConfiguration) { public void setDataSourceConfiguration(MobileDataSourceConfig DataSourceConfiguration) {
this.iosDataSourceConfiguration = iosDataSourceConfiguration; this.DataSourceConfiguration = DataSourceConfiguration;
} }
} }

@ -72,7 +72,7 @@
org.wso2.carbon.device.mgt.core.*, org.wso2.carbon.device.mgt.core.*,
org.wso2.carbon.ndatasource.core, org.wso2.carbon.ndatasource.core,
org.wso2.carbon.policy.mgt.common.*, org.wso2.carbon.policy.mgt.common.*,
org.wso2.carbon.policy.mgt.core.*, org.wso2.carbon.policy.mgt.core,
org.wso2.carbon.registry.core, org.wso2.carbon.registry.core,
org.wso2.carbon.registry.core.session, org.wso2.carbon.registry.core.session,
org.wso2.carbon.registry.core.service, org.wso2.carbon.registry.core.service,
@ -81,6 +81,8 @@
org.wso2.carbon.apimgt.application.extension.*, org.wso2.carbon.apimgt.application.extension.*,
org.wso2.carbon.analytics.datasource.commons.*, org.wso2.carbon.analytics.datasource.commons.*,
org.wso2.carbon.base, org.wso2.carbon.base,
org.wso2.carbon.analytics.api,
org.wso2.carbon.device.mgt.analytics.data.publisher.service,
com.google.gson.*, com.google.gson.*,
org.wso2.carbon.device.application.mgt.common.*, org.wso2.carbon.device.application.mgt.common.*,
org.wso2.carbon.user.core.*, org.wso2.carbon.user.core.*,

@ -0,0 +1,73 @@
/*
* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.mobile.android.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.mobile.android.common.config.datasource.AndroidDBConfigurations;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class MobileDeviceConfigFactory {
private static final Log log = LogFactory.getLog(MobileDeviceConfigFactory.class);
public static final String ANDROID_DB_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator +
"/android-dbconfig.xml";
public static AndroidDBConfigurations androidDBConfigurations;
public static AndroidDBConfigurations getDataSourceConfigurations() {
return androidDBConfigurations;
}
public static synchronized void init() throws DeviceManagementException {
try {
File mobileDeviceMgtConfig = new File(ANDROID_DB_CONFIG_PATH);
Document doc = convertToDocuments(mobileDeviceMgtConfig);
JAXBContext androidDeviceMgtContext = JAXBContext.newInstance(AndroidDBConfigurations.class);
Unmarshaller unmarshaller = androidDeviceMgtContext.createUnmarshaller();
androidDBConfigurations = (AndroidDBConfigurations) unmarshaller.unmarshal(doc);
} catch (Exception e) {
String msg = "Error occurred while initializing Mobile Device Management config";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
}
public static Document convertToDocuments(File file) throws DeviceManagementException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
String msg = "Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document : " + e.getMessage();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
}
}

@ -80,12 +80,11 @@ public abstract class AbstractMobileDeviceManagementDAOFactory {
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList = List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties(); jndiConfig.getJndiProperties();
if (jndiPropertyList != null) { if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>(); Hashtable<Object, Object> jndiProperties = new Hashtable<>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue()); jndiProperties.put(prop.getName(), prop.getValue());
} }
dataSource = dataSource = MobileDeviceManagementDAOUtil
MobileDeviceManagementDAOUtil
.lookupDataSource(jndiConfig.getJndiName(), jndiProperties); .lookupDataSource(jndiConfig.getJndiName(), jndiProperties);
} else { } else {
dataSource = MobileDeviceManagementDAOUtil dataSource = MobileDeviceManagementDAOUtil

@ -57,8 +57,8 @@ import org.wso2.carbon.device.mgt.mobile.android.common.bean.*;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.*; import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.*;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.*; import org.wso2.carbon.device.mgt.mobile.android.common.exception.*;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils; import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidDeviceUtils; import org.wso2.carbon.device.mgt.mobile.android.core.util.MobileDeviceManagementUtil;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
@ -96,7 +96,8 @@ public class AndroidServiceImpl implements AndroidService {
List<ConfigurationEntry> configs; List<ConfigurationEntry> configs;
PlatformConfiguration platformConfiguration; PlatformConfiguration platformConfiguration;
DeviceManagementProviderService deviceManagementProviderService = AndroidAPIUtils.getDeviceManagementService(); DeviceManagementProviderService deviceManagementProviderService = AndroidDeviceManagementDataHolder
.getInstance().getDeviceManagementProviderService();
platformConfiguration = deviceManagementProviderService. platformConfiguration = deviceManagementProviderService.
getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
if (platformConfiguration != null) { if (platformConfiguration != null) {
@ -141,8 +142,8 @@ public class AndroidServiceImpl implements AndroidService {
} }
configuration.setConfiguration(androidPlatformConfiguration.getConfiguration()); configuration.setConfiguration(androidPlatformConfiguration.getConfiguration());
try { try {
DeviceManagementProviderService deviceManagementProviderService = AndroidAPIUtils DeviceManagementProviderService deviceManagementProviderService = AndroidDeviceManagementDataHolder
.getDeviceManagementService(); .getInstance().getDeviceManagementProviderService();
configuration.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); configuration.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
List<ConfigurationEntry> configs = configuration.getConfiguration(); List<ConfigurationEntry> configs = configuration.getConfiguration();
NotifierFrequency notifierFrequency = new NotifierFrequency(); NotifierFrequency notifierFrequency = new NotifierFrequency();
@ -202,9 +203,8 @@ public class AndroidServiceImpl implements AndroidService {
private void notifyDevices(NotifierFrequency notifierFrequency) throws DeviceManagementException, private void notifyDevices(NotifierFrequency notifierFrequency) throws DeviceManagementException,
OperationManagementException, InvalidDeviceException { OperationManagementException, InvalidDeviceException {
List<Device> deviceList = AndroidAPIUtils. List<Device> deviceList = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
getDeviceManagementService(). .getAllDevices(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, false);
getAllDevices(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, false);
List<DeviceIdentifier> deviceIdList = new ArrayList<>(); List<DeviceIdentifier> deviceIdList = new ArrayList<>();
for (Device device : deviceList) { for (Device device : deviceList) {
if (EnrolmentInfo.Status.REMOVED != device.getEnrolmentInfo().getStatus()) { if (EnrolmentInfo.Status.REMOVED != device.getEnrolmentInfo().getStatus()) {
@ -216,7 +216,8 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.NOTIFIER_FREQUENCY); operation.setCode(AndroidConstants.OperationCodes.NOTIFIER_FREQUENCY);
operation.setPayLoad(notifierFrequency.toJSON()); operation.setPayLoad(notifierFrequency.toJSON());
operation.setEnabled(true); operation.setEnabled(true);
AndroidAPIUtils.getDeviceManagementService().addOperation( AndroidDeviceManagementDataHolder
.getInstance().getDeviceManagementProviderService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID,
operation, deviceIdList); operation, deviceIdList);
} }
@ -224,7 +225,8 @@ public class AndroidServiceImpl implements AndroidService {
@Override @Override
public Message isEnrolled(String id, DeviceIdentifier deviceIdentifier) throws DeviceManagementException { public Message isEnrolled(String id, DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
Device device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); Device device = AndroidDeviceManagementDataHolder
.getInstance().getDeviceManagementProviderService().getDevice(deviceIdentifier);
if (device != null) { if (device != null) {
String status = String.valueOf(device.getEnrolmentInfo().getStatus()); String status = String.valueOf(device.getEnrolmentInfo().getStatus());
Message responseMessage = new Message(); Message responseMessage = new Message();
@ -264,8 +266,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setPayLoad(file.toJSON()); operation.setPayLoad(file.toJSON());
try { try {
return AndroidDeviceUtils return MobileDeviceManagementUtil.getOperationResponse(fileTransferBeanWrapper.getDeviceIDs(), operation);
.getOperationResponse(fileTransferBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers ( " + fileTransferBeanWrapper.getDeviceIDs() + " ) found."; String errorMessage = "Invalid Device Identifiers ( " + fileTransferBeanWrapper.getDeviceIDs() + " ) found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -289,7 +290,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setPayLoad(lock.toJSON()); operation.setPayLoad(lock.toJSON());
try { try {
return AndroidDeviceUtils.getOperationResponse(deviceLockBeanWrapper.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(deviceLockBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -305,7 +306,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.DEVICE_UNLOCK); operation.setCode(AndroidConstants.OperationCodes.DEVICE_UNLOCK);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
operation.setEnabled(true); operation.setEnabled(true);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -315,12 +316,12 @@ public class AndroidServiceImpl implements AndroidService {
@Override @Override
public Activity getDeviceLocation(List<String> deviceIDs) public Activity getDeviceLocation(List<String> deviceIDs)
throws OperationManagementException, AndroidDeviceMgtPluginException{ throws OperationManagementException, AndroidDeviceMgtPluginException {
try { try {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.DEVICE_LOCATION); operation.setCode(AndroidConstants.OperationCodes.DEVICE_LOCATION);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -335,7 +336,7 @@ public class AndroidServiceImpl implements AndroidService {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.CLEAR_PASSWORD); operation.setCode(AndroidConstants.OperationCodes.CLEAR_PASSWORD);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -357,7 +358,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.CAMERA); operation.setCode(AndroidConstants.OperationCodes.CAMERA);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
operation.setEnabled(camera.isEnabled()); operation.setEnabled(camera.isEnabled());
return AndroidDeviceUtils.getOperationResponse(cameraBeanWrapper.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(cameraBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -372,7 +373,7 @@ public class AndroidServiceImpl implements AndroidService {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.DEVICE_INFO); operation.setCode(AndroidConstants.OperationCodes.DEVICE_INFO);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -387,7 +388,7 @@ public class AndroidServiceImpl implements AndroidService {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.LOGCAT); operation.setCode(AndroidConstants.OperationCodes.LOGCAT);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -402,7 +403,7 @@ public class AndroidServiceImpl implements AndroidService {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.ENTERPRISE_WIPE); operation.setCode(AndroidConstants.OperationCodes.ENTERPRISE_WIPE);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -424,7 +425,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.WIPE_DATA); operation.setCode(AndroidConstants.OperationCodes.WIPE_DATA);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(wipeData.toJSON()); operation.setPayLoad(wipeData.toJSON());
return AndroidDeviceUtils.getOperationResponse(wipeDataBeanWrapper.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(wipeDataBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -439,7 +440,7 @@ public class AndroidServiceImpl implements AndroidService {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.APPLICATION_LIST); operation.setCode(AndroidConstants.OperationCodes.APPLICATION_LIST);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -454,7 +455,7 @@ public class AndroidServiceImpl implements AndroidService {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.DEVICE_RING); operation.setCode(AndroidConstants.OperationCodes.DEVICE_RING);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -469,7 +470,7 @@ public class AndroidServiceImpl implements AndroidService {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.DEVICE_REBOOT); operation.setCode(AndroidConstants.OperationCodes.DEVICE_REBOOT);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -484,7 +485,7 @@ public class AndroidServiceImpl implements AndroidService {
CommandOperation operation = new CommandOperation(); CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_TASK_MODE); operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_TASK_MODE);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -500,7 +501,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.DEVICE_MUTE); operation.setCode(AndroidConstants.OperationCodes.DEVICE_MUTE);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
operation.setEnabled(true); operation.setEnabled(true);
return AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -528,7 +529,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.INSTALL_APPLICATION); operation.setCode(AndroidConstants.OperationCodes.INSTALL_APPLICATION);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(applicationInstallation.toJSON()); operation.setPayLoad(applicationInstallation.toJSON());
return AndroidDeviceUtils return MobileDeviceManagementUtil
.getOperationResponse(applicationInstallationBeanWrapper.getDeviceIDs(), operation); .getOperationResponse(applicationInstallationBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
@ -556,7 +557,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(applicationUpdate.toJSON()); operation.setPayLoad(applicationUpdate.toJSON());
return AndroidDeviceUtils return MobileDeviceManagementUtil
.getOperationResponse(applicationUpdateBeanWrapper.getDeviceIDs(), operation); .getOperationResponse(applicationUpdateBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
@ -582,7 +583,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.UNINSTALL_APPLICATION); operation.setCode(AndroidConstants.OperationCodes.UNINSTALL_APPLICATION);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(applicationUninstallation.toJSON()); operation.setPayLoad(applicationUninstallation.toJSON());
return AndroidDeviceUtils return MobileDeviceManagementUtil
.getOperationResponse(applicationUninstallationBeanWrapper.getDeviceIDs(), operation); .getOperationResponse(applicationUninstallationBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
@ -605,7 +606,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.BLACKLIST_APPLICATIONS); operation.setCode(AndroidConstants.OperationCodes.BLACKLIST_APPLICATIONS);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(blacklistApplications.toJSON()); operation.setPayLoad(blacklistApplications.toJSON());
return AndroidDeviceUtils return MobileDeviceManagementUtil
.getOperationResponse(blacklistApplicationsBeanWrapper.getDeviceIDs(), operation); .getOperationResponse(blacklistApplicationsBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
@ -630,7 +631,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.UPGRADE_FIRMWARE); operation.setCode(AndroidConstants.OperationCodes.UPGRADE_FIRMWARE);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(upgradeFirmware.toJSON()); operation.setPayLoad(upgradeFirmware.toJSON());
return AndroidDeviceUtils return MobileDeviceManagementUtil
.getOperationResponse(upgradeFirmwareBeanWrapper.getDeviceIDs(), operation); .getOperationResponse(upgradeFirmwareBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
@ -653,7 +654,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.VPN); operation.setCode(AndroidConstants.OperationCodes.VPN);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(vpn.toJSON()); operation.setPayLoad(vpn.toJSON());
return AndroidDeviceUtils.getOperationResponse(vpnConfiguration.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(vpnConfiguration.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -663,7 +664,7 @@ public class AndroidServiceImpl implements AndroidService {
@Override @Override
public Activity sendNotification(NotificationBeanWrapper notificationBeanWrapper) public Activity sendNotification(NotificationBeanWrapper notificationBeanWrapper)
throws OperationManagementException, AndroidDeviceMgtPluginException{ throws OperationManagementException, AndroidDeviceMgtPluginException {
try { try {
if (notificationBeanWrapper == null || notificationBeanWrapper.getOperation() == null) { if (notificationBeanWrapper == null || notificationBeanWrapper.getOperation() == null) {
String errorMessage = "The payload of the notification operation is incorrect"; String errorMessage = "The payload of the notification operation is incorrect";
@ -675,7 +676,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.NOTIFICATION); operation.setCode(AndroidConstants.OperationCodes.NOTIFICATION);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(notification.toJSON()); operation.setPayLoad(notification.toJSON());
return AndroidDeviceUtils.getOperationResponse(notificationBeanWrapper.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(notificationBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -698,7 +699,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(wifi.toJSON()); operation.setPayLoad(wifi.toJSON());
return AndroidDeviceUtils.getOperationResponse(wifiBeanWrapper.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(wifiBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -708,7 +709,7 @@ public class AndroidServiceImpl implements AndroidService {
@Override @Override
public Activity encryptStorage(EncryptionBeanWrapper encryptionBeanWrapper) public Activity encryptStorage(EncryptionBeanWrapper encryptionBeanWrapper)
throws OperationManagementException, AndroidDeviceMgtPluginException{ throws OperationManagementException, AndroidDeviceMgtPluginException {
try { try {
if (encryptionBeanWrapper == null || encryptionBeanWrapper.getOperation() == null) { if (encryptionBeanWrapper == null || encryptionBeanWrapper.getOperation() == null) {
String errorMessage = "The payload of the device encryption operation is incorrect"; String errorMessage = "The payload of the device encryption operation is incorrect";
@ -720,7 +721,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.ENCRYPT_STORAGE); operation.setCode(AndroidConstants.OperationCodes.ENCRYPT_STORAGE);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
operation.setEnabled(deviceEncryption.isEncrypted()); operation.setEnabled(deviceEncryption.isEncrypted());
return AndroidDeviceUtils.getOperationResponse(encryptionBeanWrapper.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(encryptionBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -742,7 +743,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_CODE); operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_CODE);
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(lockCode.toJSON()); operation.setPayLoad(lockCode.toJSON());
return AndroidDeviceUtils.getOperationResponse(lockCodeBeanWrapper.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(lockCodeBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -765,7 +766,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(passcodePolicy.toJSON()); operation.setPayLoad(passcodePolicy.toJSON());
return AndroidDeviceUtils return MobileDeviceManagementUtil
.getOperationResponse(passwordPolicyBeanWrapper.getDeviceIDs(), operation); .getOperationResponse(passwordPolicyBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
@ -790,7 +791,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(webClip.toJSON()); operation.setPayLoad(webClip.toJSON());
return AndroidDeviceUtils.getOperationResponse(webClipBeanWrapper.getDeviceIDs(), operation); return MobileDeviceManagementUtil.getOperationResponse(webClipBeanWrapper.getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found."; String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e); log.error(errorMessage, e);
@ -815,7 +816,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(globalProxy.toJSON()); operation.setPayLoad(globalProxy.toJSON());
return AndroidDeviceUtils return MobileDeviceManagementUtil
.getOperationResponse(globalProxyBeanWrapper.getDeviceIDs(), operation); .getOperationResponse(globalProxyBeanWrapper.getDeviceIDs(), operation);
} else { } else {
String errorMessage = "The payload of the global proxy operation is incorrect"; String errorMessage = "The payload of the global proxy operation is incorrect";
@ -867,7 +868,7 @@ public class AndroidServiceImpl implements AndroidService {
operation.setType(Operation.Type.PROFILE); operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(configureDisplayMessage.toJSON()); operation.setPayLoad(configureDisplayMessage.toJSON());
return AndroidDeviceUtils.getOperationResponse(displayMessageBeanWrapper. return MobileDeviceManagementUtil.getOperationResponse(displayMessageBeanWrapper.
getDeviceIDs(), operation); getDeviceIDs(), operation);
} catch (InvalidDeviceException e) { } catch (InvalidDeviceException e) {
@ -878,7 +879,6 @@ public class AndroidServiceImpl implements AndroidService {
} }
@Override @Override
public Message updateApplicationList(String id, List<AndroidApplication> androidApplications) public Message updateApplicationList(String id, List<AndroidApplication> androidApplications)
throws org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException { throws org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException {
@ -902,8 +902,8 @@ public class AndroidServiceImpl implements AndroidService {
deviceIdentifier.setId(id); deviceIdentifier.setId(id);
deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
AndroidAPIUtils.getApplicationManagerService(). AndroidDeviceManagementDataHolder.getInstance().getApplicationManagementProviderService()
updateApplicationListInstalledInDevice(deviceIdentifier, applications); .updateApplicationListInstalledInDevice(deviceIdentifier, applications);
Message responseMessage = new Message(); Message responseMessage = new Message();
responseMessage.setResponseMessage("Device information has modified successfully."); responseMessage.setResponseMessage("Device information has modified successfully.");
return responseMessage; return responseMessage;
@ -911,10 +911,13 @@ public class AndroidServiceImpl implements AndroidService {
@Override @Override
public List<? extends Operation> getPendingOperations(DeviceIdentifier deviceIdentifier, public List<? extends Operation> getPendingOperations(DeviceIdentifier deviceIdentifier,
List<? extends Operation> resultOperations) List<? extends Operation> resultOperations)
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
Device device;
try { try {
if (!AndroidDeviceUtils.isValidDeviceIdentifier(deviceIdentifier)) { device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.getDevice(deviceIdentifier, false);
if (!MobileDeviceManagementUtil.isValidDeviceIdentifier(device)) {
String msg = "Device not found for identifier '" + deviceIdentifier.getId() + "'"; String msg = "Device not found for identifier '" + deviceIdentifier.getId() + "'";
log.error(msg); log.error(msg);
throw new InvalidDeviceException(msg); throw new InvalidDeviceException(msg);
@ -923,7 +926,7 @@ public class AndroidServiceImpl implements AndroidService {
log.debug("Invoking Android pending operations:" + deviceIdentifier.getId()); log.debug("Invoking Android pending operations:" + deviceIdentifier.getId());
} }
if (resultOperations != null && !resultOperations.isEmpty()) { if (resultOperations != null && !resultOperations.isEmpty()) {
updateOperations(deviceIdentifier.getId(), resultOperations); updateOperations(device, resultOperations);
} }
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String msg = "Issue in retrieving operation management service instance"; String msg = "Issue in retrieving operation management service instance";
@ -933,7 +936,7 @@ public class AndroidServiceImpl implements AndroidService {
String msg = "Issue in updating Monitoring operation"; String msg = "Issue in updating Monitoring operation";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} catch (NotificationManagementException e) { } catch (NotificationManagementException e) {
String msg = "Issue in retrieving Notification management service instance"; String msg = "Issue in retrieving Notification management service instance";
log.error(msg, e); log.error(msg, e);
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
@ -943,7 +946,7 @@ public class AndroidServiceImpl implements AndroidService {
throw new DeviceManagementException(msg, e); throw new DeviceManagementException(msg, e);
} }
try { try {
return AndroidDeviceUtils.getPendingOperations(deviceIdentifier); return MobileDeviceManagementUtil.getPendingOperations(device);
} catch (OperationManagementException e) { } catch (OperationManagementException e) {
String msg = "Issue in retrieving operation management service instance"; String msg = "Issue in retrieving operation management service instance";
log.error(msg, e); log.error(msg, e);
@ -951,24 +954,24 @@ public class AndroidServiceImpl implements AndroidService {
} }
} }
private void updateOperations(String deviceId, List<? extends Operation> operations) private void updateOperations(Device device, List<? extends Operation> operations)
throws OperationManagementException, PolicyComplianceException, NotificationManagementException, throws OperationManagementException, PolicyComplianceException, NotificationManagementException,
DeviceManagementException, org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException { org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException {
for (org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation : operations) { for (org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation : operations) {
AndroidDeviceUtils.updateOperation(deviceId, operation); MobileDeviceManagementUtil.updateOperation(device, operation);
if (OPERATION_ERROR_STATUS.equals(operation.getStatus().toString())) { if (OPERATION_ERROR_STATUS.equals(operation.getStatus().toString())) {
org.wso2.carbon.device.mgt.common.notification.mgt.Notification notification = new org.wso2.carbon.device.mgt.common.notification.mgt.Notification notification = new
org.wso2.carbon.device.mgt.common.notification.mgt.Notification(); org.wso2.carbon.device.mgt.common.notification.mgt.Notification();
DeviceIdentifier id = new DeviceIdentifier(); DeviceIdentifier id = new DeviceIdentifier();
id.setId(deviceId); id.setId(device.getDeviceIdentifier());
id.setType(AndroidConstants.DEVICE_TYPE_ANDROID); id.setType(AndroidConstants.DEVICE_TYPE_ANDROID);
String deviceName = AndroidAPIUtils.getDeviceManagementService().getDevice(id, false).getName();
notification.setOperationId(operation.getId()); notification.setOperationId(operation.getId());
notification.setStatus(org.wso2.carbon.device.mgt.common.notification.mgt.Notification. notification.setStatus(org.wso2.carbon.device.mgt.common.notification.mgt.Notification.
Status.NEW.toString()); Status.NEW.toString());
notification.setDescription(operation.getCode() + " operation failed to execute on device " + notification.setDescription(operation.getCode() + " operation failed to execute on device " +
deviceName + " (ID: " + deviceId + ")"); device.getName() + " (ID: " + device.getDeviceIdentifier() + ")");
AndroidAPIUtils.getNotificationManagementService().addNotification(id, notification); AndroidDeviceManagementDataHolder.getInstance().getNotificationManagementService()
.addNotification(id, notification);
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Updating operation '" + operation.toString() + "'"); log.debug("Updating operation '" + operation.toString() + "'");
@ -976,15 +979,14 @@ public class AndroidServiceImpl implements AndroidService {
} }
} }
@Override @Override
public Message enrollDevice(AndroidDevice androidDevice) public Message enrollDevice(AndroidDevice androidDevice)
throws DeviceManagementException, AndroidDeviceMgtPluginException { throws DeviceManagementException {
try { try {
Device device = new Device(); Device device = new Device();
device.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); device.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
device.setEnrolmentInfo(androidDevice.getEnrolmentInfo()); device.setEnrolmentInfo(androidDevice.getEnrolmentInfo());
device.getEnrolmentInfo().setOwner(AndroidAPIUtils.getAuthenticatedUser()); device.getEnrolmentInfo().setOwner(MobileDeviceManagementUtil.getAuthenticatedUser());
device.setDeviceInfo(androidDevice.getDeviceInfo()); device.setDeviceInfo(androidDevice.getDeviceInfo());
device.setDeviceIdentifier(androidDevice.getDeviceIdentifier()); device.setDeviceIdentifier(androidDevice.getDeviceIdentifier());
device.setDescription(androidDevice.getDescription()); device.setDescription(androidDevice.getDescription());
@ -992,7 +994,8 @@ public class AndroidServiceImpl implements AndroidService {
device.setFeatures(androidDevice.getFeatures()); device.setFeatures(androidDevice.getFeatures());
device.setProperties(androidDevice.getProperties()); device.setProperties(androidDevice.getProperties());
boolean status = AndroidAPIUtils.getDeviceManagementService().enrollDevice(device); boolean status = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.enrollDevice(device);
if (status) { if (status) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(androidDevice.getDeviceIdentifier(), DeviceIdentifier deviceIdentifier = new DeviceIdentifier(androidDevice.getDeviceIdentifier(),
device.getType()); device.getType());
@ -1001,8 +1004,8 @@ public class AndroidServiceImpl implements AndroidService {
DeviceLocation deviceLocation = extractLocation(deviceIdentifier, androidDevice.getProperties()); DeviceLocation deviceLocation = extractLocation(deviceIdentifier, androidDevice.getProperties());
if (deviceLocation != null) { if (deviceLocation != null) {
try { try {
DeviceInformationManager informationManager = AndroidAPIUtils DeviceInformationManager informationManager = AndroidDeviceManagementDataHolder.getInstance()
.getDeviceInformationManagerService(); .getDeviceInformationManager();
informationManager.addDeviceLocation(deviceLocation); informationManager.addDeviceLocation(deviceLocation);
} catch (DeviceDetailsMgtException e) { } catch (DeviceDetailsMgtException e) {
String msg = "Error occurred while updating the device location upon android " + String msg = "Error occurred while updating the device location upon android " +
@ -1026,11 +1029,12 @@ public class AndroidServiceImpl implements AndroidService {
operation.setEnabled(true); operation.setEnabled(true);
operation.setType(Operation.Type.COMMAND); operation.setType(Operation.Type.COMMAND);
operation.setCode(str); operation.setCode(str);
AndroidAPIUtils.getDeviceManagementService(). AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
addOperation(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, .addOperation(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID,
operation, deviceIdentifiers); operation, deviceIdentifiers);
} }
PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService(); PolicyManagerService policyManagerService = AndroidDeviceManagementDataHolder.getInstance()
.getPolicyManagerService();
Policy effectivePolicy = policyManagerService. Policy effectivePolicy = policyManagerService.
getEffectivePolicy(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType())); getEffectivePolicy(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType()));
@ -1040,7 +1044,7 @@ public class AndroidServiceImpl implements AndroidService {
for (ProfileFeature feature : effectiveProfileFeatures) { for (ProfileFeature feature : effectiveProfileFeatures) {
if (AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE if (AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE
.equals(feature.getFeatureCode())) { .equals(feature.getFeatureCode())) {
AndroidDeviceUtils.installEnrollmentApplications(feature, deviceIdentifier); MobileDeviceManagementUtil.installEnrollmentApplications(feature, deviceIdentifier);
break; break;
} }
} }
@ -1068,13 +1072,14 @@ public class AndroidServiceImpl implements AndroidService {
@Override @Override
public boolean modifyEnrollment(String id, AndroidDevice androidDevice) public boolean modifyEnrollment(String id, AndroidDevice androidDevice)
throws DeviceManagementException, AndroidDeviceMgtPluginException { throws DeviceManagementException {
Device device; Device device;
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(id); deviceIdentifier.setId(id);
deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID);
try { try {
device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.getDevice(deviceIdentifier);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while getting enrollment details of the Android device that carries the id '" + String msg = "Error occurred while getting enrollment details of the Android device that carries the id '" +
id + "'"; id + "'";
@ -1092,34 +1097,38 @@ public class AndroidServiceImpl implements AndroidService {
log.error(errorMessage); log.error(errorMessage);
throw new NotFoundException(errorMessage); throw new NotFoundException(errorMessage);
} }
if(androidDevice.getEnrolmentInfo() != null){ if (androidDevice.getEnrolmentInfo() != null) {
device.setEnrolmentInfo(device.getEnrolmentInfo()); device.setEnrolmentInfo(device.getEnrolmentInfo());
} }
device.getEnrolmentInfo().setOwner(AndroidAPIUtils.getAuthenticatedUser()); device.getEnrolmentInfo().setOwner(MobileDeviceManagementUtil.getAuthenticatedUser());
if(androidDevice.getDeviceInfo() != null) { if (androidDevice.getDeviceInfo() != null) {
device.setDeviceInfo(androidDevice.getDeviceInfo()); device.setDeviceInfo(androidDevice.getDeviceInfo());
} }
device.setDeviceIdentifier(androidDevice.getDeviceIdentifier()); device.setDeviceIdentifier(androidDevice.getDeviceIdentifier());
if(androidDevice.getDescription() != null) { if (androidDevice.getDescription() != null) {
device.setDescription(androidDevice.getDescription()); device.setDescription(androidDevice.getDescription());
} }
if(androidDevice.getName() != null) { if (androidDevice.getName() != null) {
device.setName(androidDevice.getName()); device.setName(androidDevice.getName());
} }
if(androidDevice.getFeatures() != null) { if (androidDevice.getFeatures() != null) {
device.setFeatures(androidDevice.getFeatures()); device.setFeatures(androidDevice.getFeatures());
} }
if(androidDevice.getProperties() != null) { if (androidDevice.getProperties() != null) {
device.setProperties(androidDevice.getProperties()); device.setProperties(androidDevice.getProperties());
} }
return AndroidAPIUtils.getDeviceManagementService().modifyEnrollment(device); return AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.modifyEnrollment(device);
} }
@Override @Override
public boolean disEnrollDevice(String id) throws DeviceManagementException{ public boolean disEnrollDevice(String id) throws DeviceManagementException {
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(id);
AndroidDeviceUtils.updateDisEnrollOperationStatus(deviceIdentifier); Device device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
return AndroidAPIUtils.getDeviceManagementService().disenrollDevice(deviceIdentifier); .getDevice(deviceIdentifier, false);
MobileDeviceManagementUtil.updateDisEnrollOperationStatus(device);
return AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.disenrollDevice(deviceIdentifier);
} }
@Override @Override
@ -1137,13 +1146,14 @@ public class AndroidServiceImpl implements AndroidService {
} }
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(eventBeanWrapper.getDeviceIdentifier(), DeviceIdentifier deviceIdentifier = new DeviceIdentifier(eventBeanWrapper.getDeviceIdentifier(),
AndroidConstants.DEVICE_TYPE_ANDROID); AndroidConstants.DEVICE_TYPE_ANDROID);
device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
if (device != null && EnrolmentInfo.Status.ACTIVE != device.getEnrolmentInfo().getStatus()){ .getDevice(deviceIdentifier);
if (device != null && EnrolmentInfo.Status.ACTIVE != device.getEnrolmentInfo().getStatus()) {
Message responseMessage = new Message(); Message responseMessage = new Message();
responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_ACCEPTED)); responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_ACCEPTED));
responseMessage.setResponseMessage("Device is not in Active state."); responseMessage.setResponseMessage("Device is not in Active state.");
return responseMessage; return responseMessage;
} else if (device == null){ } else if (device == null) {
Message responseMessage = new Message(); Message responseMessage = new Message();
responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_ACCEPTED)); responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_ACCEPTED));
responseMessage.setResponseMessage("Device is not enrolled yet."); responseMessage.setResponseMessage("Device is not enrolled yet.");
@ -1180,7 +1190,7 @@ public class AndroidServiceImpl implements AndroidService {
jsonObject.get(DISTANCE).getAsDouble() jsonObject.get(DISTANCE).getAsDouble()
}; };
try { try {
if (AndroidAPIUtils.getEventPublisherService().publishEvent( if (AndroidDeviceManagementDataHolder.getInstance().getEventsPublisherService().publishEvent(
EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload)) { EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload)) {
message.setResponseCode("Event is published successfully."); message.setResponseCode("Event is published successfully.");
return message; return message;
@ -1207,7 +1217,7 @@ public class AndroidServiceImpl implements AndroidService {
long to, long to,
String type, String type,
String ifModifiedSince) throws AndroidDeviceMgtPluginException { String ifModifiedSince) throws AndroidDeviceMgtPluginException {
if (from != 0l && to != 0l && deviceId != null){ if (from != 0l && to != 0l && deviceId != null) {
return retrieveAlertFromDate(deviceId, from, to); return retrieveAlertFromDate(deviceId, from, to);
} else if (deviceId != null && type != null) { } else if (deviceId != null && type != null) {
return retrieveAlertByType(deviceId, type); return retrieveAlertByType(deviceId, type);
@ -1229,7 +1239,7 @@ public class AndroidServiceImpl implements AndroidService {
String query = "deviceIdentifier:" + deviceId; String query = "deviceIdentifier:" + deviceId;
List<DeviceState> deviceStates; List<DeviceState> deviceStates;
try { try {
deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); deviceStates = MobileDeviceManagementUtil.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query);
if (deviceStates == null) { if (deviceStates == null) {
String errorMessage = "No any alerts are " + String errorMessage = "No any alerts are " +
"published for Device: " + deviceId + "."; "published for Device: " + deviceId + ".";
@ -1255,7 +1265,7 @@ public class AndroidServiceImpl implements AndroidService {
String query = "deviceIdentifier:" + deviceId + " AND _timestamp: [" + fromDate + " TO " + toDate + "]"; String query = "deviceIdentifier:" + deviceId + " AND _timestamp: [" + fromDate + " TO " + toDate + "]";
List<DeviceState> deviceStates; List<DeviceState> deviceStates;
try { try {
deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); deviceStates = MobileDeviceManagementUtil.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query);
if (deviceStates == null) { if (deviceStates == null) {
String errorMessage = "No any alerts are " + String errorMessage = "No any alerts are " +
"published on given date for given Device: " + deviceId + "."; "published on given date for given Device: " + deviceId + ".";
@ -1280,7 +1290,7 @@ public class AndroidServiceImpl implements AndroidService {
String query = "deviceIdentifier:" + deviceId + " AND type:" + type; String query = "deviceIdentifier:" + deviceId + " AND type:" + type;
List<DeviceState> deviceStates; List<DeviceState> deviceStates;
try { try {
deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); deviceStates = MobileDeviceManagementUtil.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query);
if (deviceStates == null) { if (deviceStates == null) {
String errorMessage = "No any alerts are " + String errorMessage = "No any alerts are " +
"published for given Device: '" + deviceId + "' and given specific Type."; "published for given Device: '" + deviceId + "' and given specific Type.";
@ -1341,12 +1351,13 @@ public class AndroidServiceImpl implements AndroidService {
location = new DeviceLocation(); location = new DeviceLocation();
location.setLatitude(Double.valueOf(latitude)); location.setLatitude(Double.valueOf(latitude));
location.setLongitude(Double.valueOf(longitude)); location.setLongitude(Double.valueOf(longitude));
location.setAltitude(Double.valueOf(altitude)); location.setAltitude(Double.parseDouble(altitude));
location.setSpeed(Float.valueOf(speed)); location.setSpeed(Float.parseFloat(speed));
location.setBearing(Float.valueOf(bearing)); location.setBearing(Float.parseFloat(bearing));
location.setDistance(Double.valueOf(distance)); location.setDistance(Double.parseDouble(distance));
location.setDeviceIdentifier(deviceIdentifier); location.setDeviceIdentifier(deviceIdentifier);
Device savedDevice = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false); Device savedDevice = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.getDevice(deviceIdentifier, false);
location.setDeviceId(savedDevice.getId()); location.setDeviceId(savedDevice.getId());
} }
return location; return location;

@ -36,7 +36,7 @@ import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils; import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
@ -50,7 +50,7 @@ public class DeviceTypeCommonServiceImpl implements DeviceTypeCommonService {
@Override @Override
public Map<String, Object> getEnrollmentQRCode(String ownershipType) throws DeviceManagementException { public Map<String, Object> getEnrollmentQRCode(String ownershipType) throws DeviceManagementException {
AndroidService androidService = AndroidAPIUtils.getAndroidService(); AndroidService androidService = AndroidDeviceManagementDataHolder.getInstance().getAndroidService();
PlatformConfiguration platformConfiguration = androidService.getPlatformConfig(); PlatformConfiguration platformConfiguration = androidService.getPlatformConfig();
Map<String, Object> qrEnrollmentPayload = new HashMap<>(); Map<String, Object> qrEnrollmentPayload = new HashMap<>();

@ -18,9 +18,16 @@
package org.wso2.carbon.device.mgt.mobile.android.core.internal; package org.wso2.carbon.device.mgt.mobile.android.core.internal;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService; import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
/** /**
@ -30,6 +37,13 @@ public class AndroidDeviceManagementDataHolder {
private RegistryService registryService; private RegistryService registryService;
private AndroidGoogleEnterpriseService androidDeviceManagementService; private AndroidGoogleEnterpriseService androidDeviceManagementService;
private DeviceManagementProviderService deviceManagementProviderService;
private ApplicationManagementProviderService applicationManagementProviderService;
private NotificationManagementService notificationManagementService;
private DeviceInformationManager deviceInformationManager;
private PolicyManagerService policyManagerService;
private AnalyticsDataAPI analyticsDataAPI;
private EventsPublisherService eventsPublisherService;
private AndroidService androidService; private AndroidService androidService;
private DeviceTypeCommonService deviceTypeCommonService; private DeviceTypeCommonService deviceTypeCommonService;
@ -75,4 +89,60 @@ public class AndroidDeviceManagementDataHolder {
public void setDeviceTypeCommonService(DeviceTypeCommonService deviceTypeCommonService) { public void setDeviceTypeCommonService(DeviceTypeCommonService deviceTypeCommonService) {
this.deviceTypeCommonService = deviceTypeCommonService; this.deviceTypeCommonService = deviceTypeCommonService;
} }
public DeviceManagementProviderService getDeviceManagementProviderService() {
return deviceManagementProviderService;
}
public void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) {
this.deviceManagementProviderService = deviceManagementProviderService;
}
public ApplicationManagementProviderService getApplicationManagementProviderService() {
return applicationManagementProviderService;
}
public void setApplicationManagementProviderService(ApplicationManagementProviderService applicationManagementProviderService) {
this.applicationManagementProviderService = applicationManagementProviderService;
}
public NotificationManagementService getNotificationManagementService() {
return notificationManagementService;
}
public void setNotificationManagementService(NotificationManagementService notificationManagementService) {
this.notificationManagementService = notificationManagementService;
}
public DeviceInformationManager getDeviceInformationManager() {
return deviceInformationManager;
}
public void setDeviceInformationManager(DeviceInformationManager deviceInformationManager) {
this.deviceInformationManager = deviceInformationManager;
}
public PolicyManagerService getPolicyManagerService() {
return policyManagerService;
}
public void setPolicyManagerService(PolicyManagerService policyManagerService) {
this.policyManagerService = policyManagerService;
}
public AnalyticsDataAPI getAnalyticsDataAPI() {
return analyticsDataAPI;
}
public void setAnalyticsDataAPI(AnalyticsDataAPI analyticsDataAPI) {
this.analyticsDataAPI = analyticsDataAPI;
}
public EventsPublisherService getEventsPublisherService() {
return eventsPublisherService;
}
public void setEventsPublisherService(EventsPublisherService eventsPublisherService) {
this.eventsPublisherService = eventsPublisherService;
}
} }

@ -22,20 +22,51 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService; import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.device.mgt.mobile.android.core.MobileDeviceConfigFactory;
import org.wso2.carbon.device.mgt.mobile.android.core.dao.AbstractMobileDeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.mobile.android.core.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidGoogleEnterpriseServiceImpl; import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidGoogleEnterpriseServiceImpl;
import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl; import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl;
import org.wso2.carbon.device.mgt.mobile.android.core.impl.DeviceTypeCommonServiceImpl; import org.wso2.carbon.device.mgt.mobile.android.core.impl.DeviceTypeCommonServiceImpl;
import org.wso2.carbon.device.mgt.mobile.android.core.util.MobileDeviceManagementUtil;
import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
/** /**
* @scr.component name="org.wso2.carbon.device.mgt.mobile.android.impl.internal.AndroidPluginServiceComponent" * @scr.component name="org.wso2.carbon.device.mgt.mobile.android" immediate="true"
* immediate="true" * @scr.reference name="org.wso2.carbon.device.manager"
* interface="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceManagementService"
* unbind="unsetDeviceManagementService"
* @scr.reference name="org.wso2.carbon.devicemgt.policy.manager"
* interface="org.wso2.carbon.policy.mgt.core.PolicyManagerService"
* cardinality="1..1"
* policy="dynamic"
* bind="setPolicyManagerService"
* unbind="unsetPolicyManagerService"
* @scr.reference name="analytics.api.component"
* interface="org.wso2.carbon.analytics.api.AnalyticsDataAPI"
* cardinality="1..1"
* policy="dynamic"
* bind="setAnalyticsDataAPI"
* unbind="unsetAnalyticsDataAPI"
* @scr.reference name="org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherServiceComponent"
* interface="org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService"
* cardinality="1..1"
* policy="dynamic"
* bind="setEventsPublisherService"
* unbind="unsetEventsPublisherService"
* @scr.reference name="org.wso2.carbon.ndatasource" * @scr.reference name="org.wso2.carbon.ndatasource"
* interface="org.wso2.carbon.ndatasource.core.DataSourceService" * interface="org.wso2.carbon.ndatasource.core.DataSourceService"
* cardinality="1..1" * cardinality="1..1"
@ -43,43 +74,41 @@ import org.wso2.carbon.registry.core.service.RegistryService;
* bind="setDataSourceService" * bind="setDataSourceService"
* unbind="unsetDataSourceService" * unbind="unsetDataSourceService"
* @scr.reference name="registry.service" * @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="0..1" * interface="org.wso2.carbon.registry.core.service.RegistryService"
* policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService" * cardinality="0..1"
* <p> * policy="dynamic"
* Adding reference to API Manager Configuration service is an unavoidable hack to get rid of NPEs thrown while * bind="setRegistryService"
* initializing APIMgtDAOs attempting to register APIs programmatically. APIMgtDAO needs to be proper cleaned up * unbind="unsetRegistryService"
* to avoid as an ideal fix
*/ */
@SuppressWarnings("unused")
public class AndroidPluginServiceComponent { public class AndroidPluginServiceComponent {
private static final Log log = LogFactory.getLog(AndroidPluginServiceComponent.class); private static final Log log = LogFactory.getLog(AndroidPluginServiceComponent.class);
protected void activate(ComponentContext ctx) { protected void activate(ComponentContext componentContext) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Activating Android Mobile Device Management Service Component"); log.debug("Activating Android Mobile Device Management Service Component");
} }
try { try {
BundleContext bundleContext = ctx.getBundleContext(); BundleContext bundleContext = componentContext.getBundleContext();
MobileDeviceManagementUtil.initConfig(); MobileDeviceConfigFactory.init();
AbstractMobileDeviceManagementDAOFactory.init("android", MobileDeviceManagementUtil AbstractMobileDeviceManagementDAOFactory.init("android", MobileDeviceConfigFactory
.getIosDataSourceConfigurations().getIosDataSourceConfiguration()); .getDataSourceConfigurations().getDataSourceConfiguration());
AndroidService androidService = new AndroidServiceImpl(); AndroidService androidService = new AndroidServiceImpl();
AndroidDeviceManagementDataHolder.getInstance().setAndroidService( AndroidDeviceManagementDataHolder.getInstance().setAndroidService(androidService);
androidService); bundleContext.registerService(AndroidService.class, androidService, null);
bundleContext.registerService(AndroidService.class.getName(), androidService, null);
DeviceTypeCommonService deviceTypeCommonService = new DeviceTypeCommonServiceImpl(); DeviceTypeCommonService deviceTypeCommonService = new DeviceTypeCommonServiceImpl();
AndroidDeviceManagementDataHolder.getInstance().setDeviceTypeCommonService( AndroidDeviceManagementDataHolder.getInstance().setDeviceTypeCommonService(deviceTypeCommonService);
deviceTypeCommonService); bundleContext.registerService(DeviceTypeCommonService.class, deviceTypeCommonService, null);
bundleContext.registerService(DeviceTypeCommonService.class.getName(), deviceTypeCommonService, null);
AndroidGoogleEnterpriseService androidPluginService = new AndroidGoogleEnterpriseServiceImpl(); AndroidGoogleEnterpriseService androidPluginService = new AndroidGoogleEnterpriseServiceImpl();
AndroidDeviceManagementDataHolder.getInstance().setAndroidDeviceManagementService( AndroidDeviceManagementDataHolder.getInstance().setAndroidDeviceManagementService(androidPluginService);
androidPluginService); bundleContext.registerService(AndroidGoogleEnterpriseService.class, androidPluginService, null);
bundleContext.registerService(AndroidGoogleEnterpriseService.class.getName(), androidPluginService, null);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Android Mobile Device Management Service Component has been successfully activated"); log.debug("Android Mobile Device Management Service Component has been successfully activated");
} }
@ -88,7 +117,7 @@ public class AndroidPluginServiceComponent {
} }
} }
protected void deactivate(ComponentContext ctx) { protected void deactivate(ComponentContext componentContext) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("De-activating Android Mobile Device Management Service Component"); log.debug("De-activating Android Mobile Device Management Service Component");
} }
@ -102,6 +131,62 @@ public class AndroidPluginServiceComponent {
} }
} }
protected void setDeviceManagementService(DeviceManagementProviderService deviceManagerService) {
if (log.isDebugEnabled()) {
log.debug("Setting Device Management Service");
}
AndroidDeviceManagementDataHolder.getInstance().setDeviceManagementProviderService(deviceManagerService);
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ApplicationManagementProviderService applicationManagementProviderService =
(ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null);
AndroidDeviceManagementDataHolder.getInstance()
.setApplicationManagementProviderService(applicationManagementProviderService);
NotificationManagementService notificationManagementService =
(NotificationManagementService) ctx.getOSGiService(NotificationManagementService.class, null);
AndroidDeviceManagementDataHolder.getInstance()
.setNotificationManagementService(notificationManagementService);
DeviceInformationManager deviceInformationManager =
(DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null);
AndroidDeviceManagementDataHolder.getInstance().setDeviceInformationManager(deviceInformationManager);
}
protected void unsetDeviceManagementService(DeviceManagementProviderService deviceManagementService) {
if (log.isDebugEnabled()) {
log.debug("Removing Device Management Service");
}
AndroidDeviceManagementDataHolder.getInstance().setDeviceManagementProviderService(null);
AndroidDeviceManagementDataHolder.getInstance().setApplicationManagementProviderService(null);
AndroidDeviceManagementDataHolder.getInstance().setNotificationManagementService(null);
AndroidDeviceManagementDataHolder.getInstance().setDeviceInformationManager(null);
}
protected void setPolicyManagerService(PolicyManagerService policyManagerService) {
AndroidDeviceManagementDataHolder.getInstance().setPolicyManagerService(policyManagerService);
}
protected void unsetPolicyManagerService(PolicyManagerService policyManagerService) {
AndroidDeviceManagementDataHolder.getInstance().setPolicyManagerService(null);
}
protected void setAnalyticsDataAPI(AnalyticsDataAPI analyticsDataAPI) {
AndroidDeviceManagementDataHolder.getInstance().setAnalyticsDataAPI(analyticsDataAPI);
}
protected void unsetAnalyticsDataAPI(AnalyticsDataAPI analyticsDataAPI) {
AndroidDeviceManagementDataHolder.getInstance().setAnalyticsDataAPI(null);
}
protected void setEventsPublisherService(EventsPublisherService eventsPublisherService) {
AndroidDeviceManagementDataHolder.getInstance().setEventsPublisherService(eventsPublisherService);
}
protected void unsetEventsPublisherService(EventsPublisherService eventsPublisherService) {
AndroidDeviceManagementDataHolder.getInstance().setEventsPublisherService(null);
}
protected void setDataSourceService(DataSourceService dataSourceService) { protected void setDataSourceService(DataSourceService dataSourceService) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources /* This is to avoid mobile device management component getting initialized before the underlying datasources
are registered */ are registered */

@ -1,210 +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.device.mgt.mobile.android.core.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
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.spi.DeviceTypeCommonService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService;
import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
/**
* AndroidAPIUtil class provides utility functions used by Android REST-API classes.
*/
public class AndroidAPIUtils {
private static Log log = LogFactory.getLog(AndroidAPIUtils.class);
private AndroidAPIUtils(){
throw new IllegalStateException("Utility class");
}
public static AndroidGoogleEnterpriseService getAndroidPluginService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AndroidGoogleEnterpriseService androidPluginService =
(AndroidGoogleEnterpriseService) ctx.getOSGiService(AndroidGoogleEnterpriseService.class, null);
if (androidPluginService == null) {
String msg = "Android plugin service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return androidPluginService;
}
public static AndroidService getAndroidService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AndroidService androidService = (AndroidService) ctx.getOSGiService(AndroidService.class, null);
if (androidService == null) {
String msg = "Android service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return androidService;
}
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username != null && username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
public static DeviceTypeCommonService getDeviceTypeCommonService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceTypeCommonService deviceTypeCommonService = (DeviceTypeCommonService) ctx
.getOSGiService(DeviceTypeCommonService.class, null);
if (deviceTypeCommonService == null) {
String msg = "Device Type Common service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceTypeCommonService;
}
public static DeviceInformationManager getDeviceInformationManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceInformationManager informationManager =
(DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null);
if (informationManager == null) {
String msg = "Information Manager service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return informationManager;
}
public static PolicyManagerService getPolicyManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
PolicyManagerService policyManagerService = (PolicyManagerService) ctx.getOSGiService(
PolicyManagerService.class, null);
if (policyManagerService == null) {
String msg = "Policy Manager service has not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
return policyManagerService;
}
public static ApplicationManagementProviderService getApplicationManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ApplicationManagementProviderService applicationManagementProviderService =
(ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null);
if (applicationManagementProviderService == null) {
String msg = "Application Management provider service has not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
return applicationManagementProviderService;
}
public static NotificationManagementService getNotificationManagementService() {
NotificationManagementService notificationManagementService;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
notificationManagementService = (NotificationManagementService) ctx.getOSGiService(
NotificationManagementService.class, null);
if (notificationManagementService == null) {
String msg = "Notification Management service not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return notificationManagementService;
}
public static EventsPublisherService getEventPublisherService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventsPublisherService eventsPublisherService =
(EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null);
if (eventsPublisherService == null) {
String msg = "Event Publisher service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return eventsPublisherService;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
if (analyticsDataAPI == null) {
String msg = "Analytics api service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return analyticsDataAPI;
}
public static Response getOperationResponse(List<String> deviceIDs, Operation operation)
throws AndroidDeviceMgtPluginException, OperationManagementException, InvalidDeviceException {
if (deviceIDs == null || deviceIDs.isEmpty()) {
String errorMessage = "Device identifier list is empty";
log.error(errorMessage);
throw new BadRequestException(errorMessage);
}
DeviceIdentifier deviceIdentifier;
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
for (String deviceId : deviceIDs) {
deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID);
deviceIdentifiers.add(deviceIdentifier);
}
Activity activity = getDeviceManagementService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers);
return Response.status(Response.Status.CREATED).entity(activity).build();
}
}

@ -1,705 +0,0 @@
/*
* Copyright (c) 2016, 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.
*
*
* Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.mobile.android.core.util;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONObject;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
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.Activity;
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.ProfileFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
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.search.mgt.impl.Utils;
import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceState;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorListItem;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.apache.http.impl.client.CloseableHttpClient;
import javax.validation.ConstraintViolation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Util class for holding Android device related util methods.
*/
public class AndroidDeviceUtils {
private static Log log = LogFactory.getLog(AndroidDeviceUtils.class);
private AndroidDeviceUtils() {
throw new IllegalStateException("Utility class");
}
public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
Device device = AndroidAPIUtils.getDeviceManagementService().
getDevice(deviceIdentifier, false);
return !(device == null || device.getDeviceIdentifier() == null ||
device.getDeviceIdentifier().isEmpty() ||
device.getEnrolmentInfo() == null ||
EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus()));
}
public static DeviceIdentifier convertToDeviceIdentifierObject(String deviceId) {
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setId(deviceId);
identifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
return identifier;
}
public static Activity getOperationResponse(List<String> deviceIDs, Operation operation)
throws OperationManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
if (deviceIDs == null || deviceIDs.isEmpty()) {
String errorMessage = "Device identifier list is empty";
log.error(errorMessage);
throw new BadRequestException(errorMessage);
}
DeviceIdentifier deviceIdentifier;
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
for (String deviceId : deviceIDs) {
deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID);
deviceIdentifiers.add(deviceIdentifier);
}
return AndroidAPIUtils.getDeviceManagementService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers);
}
public static List<DeviceState> getAllEventsForDevice(String tableName, String query) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = AndroidAPIUtils.getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) {
return null;
}
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount);
List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, DeviceState> deviceStateses = createDeviceStatusData(AnalyticsDataAPIUtil.listRecords(
analyticsDataAPI, response));
return getSortedDeviceStateData(deviceStateses, resultEntries);
}
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId());
}
return ids;
}
public static Map<String, DeviceState> createDeviceStatusData(List<Record> records) {
Map<String, DeviceState> deviceStatuses = new HashMap<>();
for (Record record : records) {
DeviceState deviceState = createDeviceStatusData(record);
deviceStatuses.put(deviceState.getId(), deviceState);
}
return deviceStatuses;
}
private static DeviceState createDeviceStatusData(Record record) {
DeviceState deviceState = new DeviceState();
deviceState.setId(record.getId());
deviceState.setValues(record.getValues());
return deviceState;
}
public static List<DeviceState> getSortedDeviceStateData(Map<String, DeviceState> sensorDatas,
List<SearchResultEntry> searchResults) {
List<DeviceState> sortedRecords = new ArrayList<>();
for (SearchResultEntry searchResultEntry : searchResults) {
sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
}
return sortedRecords;
}
public static void updateOperation(String deviceId, Operation operation)
throws OperationManagementException, PolicyComplianceException,
org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
if (!Operation.Status.ERROR.equals(operation.getStatus()) &&
AndroidConstants.OperationCodes.MONITOR.equals(operation.getCode())) {
if (log.isDebugEnabled()) {
log.debug("Received compliance status from MONITOR operation ID: " + operation.getId());
}
AndroidAPIUtils.getPolicyManagerService().checkPolicyCompliance(deviceIdentifier,
getComplianceFeatures(operation.getPayLoad()));
} else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants.
OperationCodes.APPLICATION_LIST.equals(operation.getCode())) {
if (log.isDebugEnabled()) {
log.debug("Received applications list from device '" + deviceId + "'");
}
updateApplicationList(operation, deviceIdentifier);
} else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants.
OperationCodes.DEVICE_INFO.equals(operation.getCode())) {
try {
if (log.isDebugEnabled()) {
log.debug("Operation response: " + operation.getOperationResponse());
}
Device device = new Gson().fromJson(operation.getOperationResponse(), Device.class);
org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo = convertDeviceToInfo(device);
updateDeviceInfo(deviceIdentifier, deviceInfo);
} catch (DeviceDetailsMgtException e) {
throw new OperationManagementException("Error occurred while updating the device information.", e);
}
} else if (!Operation.Status.ERROR.equals(operation.getStatus()) &&
AndroidConstants.OperationCodes.DEVICE_LOCATION.equals(operation.getCode())) {
try {
DeviceLocation location = new Gson().fromJson(operation.getOperationResponse(), DeviceLocation.class);
// reason for checking "location.getLatitude() != null" because when device fails to provide
// device location and send status instead, above Gson converter create new location object
// with null attributes
if (location != null && location.getLatitude() != null) {
location.setDeviceIdentifier(deviceIdentifier);
updateDeviceLocation(location);
}
} catch (DeviceDetailsMgtException e) {
throw new OperationManagementException("Error occurred while updating the device location.", e);
}
} else if (AndroidConstants.OperationCodes.INSTALL_APPLICATION.equals(operation.getCode())
|| AndroidConstants.OperationCodes.UNINSTALL_APPLICATION.equals(operation.getCode())) {
try {
updateAppSubStatus(deviceIdentifier, operation.getId(), operation.getStatus().toString());
} catch (org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException e) {
String msg = "Error occurred while updating the app subscription for device.";
log.error(msg);
throw new OperationManagementException(msg, e);
} catch (DeviceManagementException e) {
String msg = "Error occurred while getting device data for device identifier.";
log.error(msg);
throw new OperationManagementException(msg, e);
}
}
AndroidAPIUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation);
// This has to be bellow other if blocks, since updateOperation would fail if we execute against a disenrolled
// device.
if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants.
OperationCodes.WIPE_DATA.equals(operation.getCode())) {
if (log.isDebugEnabled()) {
log.debug("Received wipe data from device '" + deviceId + "'");
}
try {
AndroidAPIUtils.getDeviceManagementService().disenrollDevice(deviceIdentifier);
} catch (DeviceManagementException e) {
throw new OperationManagementException("Error occurred while unenrolling the device.", e);
}
}
}
public static List<? extends Operation> getPendingOperations
(DeviceIdentifier deviceIdentifier) throws OperationManagementException {
List<? extends Operation> operations;
operations = AndroidAPIUtils.getDeviceManagementService().getPendingOperations(deviceIdentifier);
return operations;
}
private static void updateApplicationList(Operation operation, DeviceIdentifier deviceIdentifier)
throws org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException {
// Parsing json string to get applications list.
if (operation.getOperationResponse() != null) {
if (operation.getOperationResponse().equals("SAME_APPLICATION_LIST")) {
return;
}
JsonElement jsonElement = new JsonParser().parse(operation.getOperationResponse());
JsonArray jsonArray = jsonElement.getAsJsonArray();
Application app;
List<Application> applications = new ArrayList<>(jsonArray.size());
for (JsonElement element : jsonArray) {
app = new Application();
app.setName(element.getAsJsonObject().
get(AndroidConstants.ApplicationProperties.NAME).getAsString());
app.setApplicationIdentifier(element.getAsJsonObject().
get(AndroidConstants.ApplicationProperties.IDENTIFIER).getAsString());
app.setPlatform(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS) != null) {
app.setMemoryUsage(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS).getAsInt());
}
if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION) != null) {
app.setVersion(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION).getAsString());
}
if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE) != null) {
app.setActive(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE).getAsBoolean());
}
applications.add(app);
}
AndroidAPIUtils.getApplicationManagerService().updateApplicationListInstalledInDevice(deviceIdentifier, applications);
} else {
if (log.isDebugEnabled()) {
log.debug("Operation Response is null.");
}
}
}
private static void updateDeviceLocation(DeviceLocation deviceLocation) throws DeviceDetailsMgtException {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceInformationManager informationManager =
(DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null);
informationManager.addDeviceLocation(deviceLocation);
}
private static void updateAppSubStatus(DeviceIdentifier deviceIdentifier, int operationId, String status)
throws org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException,
DeviceManagementException {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ApplicationManager applicationManager =
(ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
Device device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier);
applicationManager.updateSubsStatus(device.getId(), operationId, status);
}
private static void updateDeviceInfo(DeviceIdentifier deviceId, DeviceInfo deviceInfo)
throws DeviceDetailsMgtException {
DeviceInformationManager informationManager = AndroidAPIUtils.getDeviceInformationManagerService();
informationManager.addDeviceInfo(deviceId, deviceInfo);
}
private static org.wso2.carbon.device.mgt.common.device.details.DeviceInfo convertDeviceToInfo(Device device) {
org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo =
new org.wso2.carbon.device.mgt.common.device.details.DeviceInfo();
if (deviceInfo.getDeviceDetailsMap() == null) {
deviceInfo.setDeviceDetailsMap(new HashMap<>());
}
List<Device.Property> props = device.getProperties();
for (Device.Property prop : props) {
if (Utils.getDeviceDetailsColumnNames().containsValue(prop.getName())) {
extractDefinedProperties(deviceInfo, prop);
} else {
extractMapProperties(deviceInfo, prop);
}
}
return deviceInfo;
}
private static void extractMapProperties(DeviceInfo deviceInfo, Device.Property prop) {
if (prop.getName().equalsIgnoreCase("CPU_INFO")) {
deviceInfo.getDeviceDetailsMap().put("cpuUser", getProperty(prop.getValue(), "User"));
deviceInfo.getDeviceDetailsMap().put("cpuSystem", getProperty(prop.getValue(), "System"));
deviceInfo.getDeviceDetailsMap().put("IOW", getProperty(prop.getValue(), "IOW"));
deviceInfo.getDeviceDetailsMap().put("IRQ", getProperty(prop.getValue(), "IRQ"));
} else if (prop.getName().equalsIgnoreCase("RAM_INFO")) {
if (!getProperty(prop.getValue(), "TOTAL_MEMORY").isEmpty()) {
deviceInfo.setTotalRAMMemory(Double.parseDouble(getProperty(prop.getValue(), "TOTAL_MEMORY")));
} else {
deviceInfo.setTotalRAMMemory(-1D);
}
if (!getProperty(prop.getValue(), "AVAILABLE_MEMORY").isEmpty()) {
deviceInfo.setAvailableRAMMemory(Double.parseDouble(
getProperty(prop.getValue(), "AVAILABLE_MEMORY")));
} else {
deviceInfo.setAvailableRAMMemory(-1D);
}
deviceInfo.getDeviceDetailsMap().put("ramThreshold", getProperty(prop.getValue(), "THRESHOLD"));
deviceInfo.getDeviceDetailsMap().put("ramLowMemory", getProperty(prop.getValue(), "LOW_MEMORY"));
} else if (prop.getName().equalsIgnoreCase("BATTERY_INFO")) {
deviceInfo.setPluggedIn(Boolean.parseBoolean(getProperty(prop.getValue(), "PLUGGED")));
deviceInfo.getDeviceDetailsMap().put("batteryLevel", getProperty(prop.getValue(), "BATTERY_LEVEL"));
deviceInfo.getDeviceDetailsMap().put("batteryScale", getProperty(prop.getValue(), "SCALE"));
deviceInfo.getDeviceDetailsMap().put("batteryVoltage",
getProperty(prop.getValue(), "BATTERY_VOLTAGE"));
deviceInfo.getDeviceDetailsMap().put("batteryTemperature",
getProperty(prop.getValue(), "TEMPERATURE"));
deviceInfo.getDeviceDetailsMap().put("batteryCurrentTemperature",
getProperty(prop.getValue(), "CURRENT_AVERAGE"));
deviceInfo.getDeviceDetailsMap().put("batteryTechnology",
getProperty(prop.getValue(), "TECHNOLOGY"));
deviceInfo.getDeviceDetailsMap().put("batteryHealth", getProperty(prop.getValue(), "HEALTH"));
deviceInfo.getDeviceDetailsMap().put("batteryStatus", getProperty(prop.getValue(), "STATUS"));
} else if (prop.getName().equalsIgnoreCase("NETWORK_INFO")) {
deviceInfo.setSsid(getProperty(prop.getValue(), "WIFI_SSID"));
deviceInfo.setConnectionType(getProperty(prop.getValue(), "CONNECTION_TYPE"));
deviceInfo.getDeviceDetailsMap().put("mobileSignalStrength",
getProperty(prop.getValue(), "MOBILE_SIGNAL_STRENGTH"));
deviceInfo.getDeviceDetailsMap().put("wifiSignalStrength",
getProperty(prop.getValue(), "WIFI_SIGNAL_STRENGTH"));
} else if (prop.getName().equalsIgnoreCase("DEVICE_INFO")) {
if (!getProperty(prop.getValue(), "BATTERY_LEVEL").isEmpty()) {
deviceInfo.setBatteryLevel(Double.parseDouble(
getProperty(prop.getValue(), "BATTERY_LEVEL")));
} else {
deviceInfo.setBatteryLevel(-1D);
}
if (!getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY").isEmpty()) {
deviceInfo.setInternalTotalMemory(Double.parseDouble(
getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY")));
} else {
deviceInfo.setInternalTotalMemory(-1D);
}
if (!getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY").isEmpty()) {
deviceInfo.setInternalAvailableMemory(Double.parseDouble(
getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY")));
} else {
deviceInfo.setInternalAvailableMemory(-1D);
}
if (!getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY").isEmpty()) {
deviceInfo.setExternalTotalMemory(Double.parseDouble(
getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY")));
} else {
deviceInfo.setExternalTotalMemory(-1D);
}
if (!getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY").isEmpty()) {
deviceInfo.setExternalAvailableMemory(Double.parseDouble(
getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY")));
} else {
deviceInfo.setExternalAvailableMemory(-1D);
}
deviceInfo.getDeviceDetailsMap().put("encryptionEnabled",
getProperty(prop.getValue(), "ENCRYPTION_ENABLED"));
deviceInfo.getDeviceDetailsMap().put("passcodeEnabled",
getProperty(prop.getValue(), "PASSCODE_ENABLED"));
deviceInfo.getDeviceDetailsMap().put("operator",
getProperty(prop.getValue(), "OPERATOR"));
deviceInfo.getDeviceDetailsMap().put("PhoneNumber",
getProperty(prop.getValue(), "PHONE_NUMBER"));
} else if (prop.getName().equalsIgnoreCase("IMEI")) {
deviceInfo.getDeviceDetailsMap().put("IMEI", prop.getValue());
} else if (prop.getName().equalsIgnoreCase("IMSI")) {
deviceInfo.getDeviceDetailsMap().put("IMSI", prop.getValue());
} else if (prop.getName().equalsIgnoreCase("MAC")) {
deviceInfo.getDeviceDetailsMap().put("mac", prop.getValue());
} else if (prop.getName().equalsIgnoreCase("SERIAL")) {
deviceInfo.getDeviceDetailsMap().put("serial", prop.getValue());
} else {
deviceInfo.getDeviceDetailsMap().put(prop.getName(), prop.getValue());
}
}
private static void extractDefinedProperties(DeviceInfo deviceInfo, Device.Property prop) {
if (prop.getName().equalsIgnoreCase("DEVICE_MODEL")) {
deviceInfo.setDeviceModel(prop.getValue());
} else if (prop.getName().equalsIgnoreCase("VENDOR")) {
deviceInfo.setVendor(prop.getValue());
} else if (prop.getName().equalsIgnoreCase("OS_VERSION")) {
deviceInfo.setOsVersion(prop.getValue());
} else if (prop.getName().equalsIgnoreCase("OS_BUILD_DATE")) {
deviceInfo.setOsBuildDate(prop.getValue());
}
}
private static String getProperty(String properties, String needed) {
// This is not a key value pair. value is the immediate element to its filed name.
// Ex:
// [{"name":"ENCRYPTION_ENABLED","value":"false"},{"name":"PASSCODE_ENABLED","value":"true"},
// {"name":"BATTERY_LEVEL","value":"100"},{"name":"INTERNAL_TOTAL_MEMORY","value":"0.76"}]
JsonElement jsonElement = new JsonParser().parse(properties);
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (JsonElement element : jsonArray) {
if (element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
if (jsonObject.has("name")
&& jsonObject.get("name").getAsString().equalsIgnoreCase(needed)) {
if (jsonObject.has("value") && jsonObject.get("value") != JsonNull.INSTANCE) {
return jsonObject.get("value").getAsString().replace("%", "");
} else {
return "";
}
}
}
}
return "";
}
private static List<ComplianceFeature> getComplianceFeatures(Object compliancePayload)
throws PolicyComplianceException {
String compliancePayloadString = new Gson().toJson(compliancePayload);
if (compliancePayload == null) {
return null;
}
// Parsing json string to get compliance features.
JsonElement jsonElement;
if (compliancePayloadString instanceof String) {
jsonElement = new JsonParser().parse(compliancePayloadString);
} else {
throw new PolicyComplianceException("Invalid policy compliance payload");
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
Gson gson = new Gson();
ComplianceFeature complianceFeature;
List<ComplianceFeature> complianceFeatures = new ArrayList<ComplianceFeature>(jsonArray.size());
for (JsonElement element : jsonArray) {
complianceFeature = gson.fromJson(element, ComplianceFeature.class);
complianceFeatures.add(complianceFeature);
}
return complianceFeatures;
}
/**
* Returns a new BadRequestException
*
* @param description description of the exception
* @return a new BadRequestException with the specified details as a response DTO
*/
public static ErrorResponse buildBadRequestException(String description) {
ErrorResponse errorResponse = getErrorResponse(AndroidConstants.
ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400l, description);
return errorResponse;
}
/**
* Returns generic ErrorResponse.
*
* @param message specific error message
* @param code error code
* @param description error description
* @return generic Response with error specific details.
*/
public static ErrorResponse getErrorResponse(String message, Long code, String description) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode(code);
errorResponse.setMoreInfo("");
errorResponse.setMessage(message);
errorResponse.setDescription(description);
return errorResponse;
}
public static <T> ErrorResponse getConstraintViolationErrorDTO(Set<ConstraintViolation<T>> violations) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setDescription("Validation Error");
errorResponse.setMessage("Bad Request");
errorResponse.setCode(400l);
errorResponse.setMoreInfo("");
List<ErrorListItem> errorListItems = new ArrayList<>();
for (ConstraintViolation violation : violations) {
ErrorListItem errorListItemDTO = new ErrorListItem();
errorListItemDTO.setCode(400 + "_" + violation.getPropertyPath());
errorListItemDTO.setMessage(violation.getPropertyPath() + ": " + violation.getMessage());
errorListItems.add(errorListItemDTO);
}
errorResponse.setErrorItems(errorListItems);
return errorResponse;
}
public static void installEnrollmentApplications(ProfileFeature feature, DeviceIdentifier deviceIdentifier)
throws PolicyManagementException {
String uuid = "";
try {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
ApiApplicationKey apiApplicationKey = OAuthUtils.getClientCredentials(tenantDomain);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName() + AndroidConstants.ApplicationInstall.AT + tenantDomain;
AccessTokenInfo tokenInfo = OAuthUtils.getOAuthCredentials(apiApplicationKey, username);
String requestUrl = AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_PROTOCOL +
System.getProperty(AndroidConstants.ApplicationInstall.IOT_CORE_HOST) +
AndroidConstants.ApplicationInstall.COLON +
System.getProperty(AndroidConstants.ApplicationInstall.IOT_CORE_PORT) +
AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_URL;
JsonElement appListElement = new JsonParser().parse(feature.getContent().toString()).getAsJsonObject()
.get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE);
JSONObject deviceObject = new JSONObject();
deviceObject.put("id", deviceIdentifier.getId());
deviceObject.put("type", deviceIdentifier.getType());
JSONArray payload = new JSONArray();
payload.put(deviceObject);
StringEntity requestEntity = new StringEntity(payload.toString(), ContentType.APPLICATION_JSON);
JsonArray appListArray = appListElement.getAsJsonArray();
for (JsonElement appElement : appListArray) {
JsonElement googlePolicyPayload = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD);
if (googlePolicyPayload == null || googlePolicyPayload.toString().equals("\"\"")) {
uuid = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_UUID).getAsString();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost postRequest = new HttpPost(requestUrl.replace("{uuid}", uuid));
postRequest.setHeader(AndroidConstants.ApplicationInstall.AUTHORIZATION,
AndroidConstants.ApplicationInstall.AUTHORIZATION_HEADER_VALUE + tokenInfo
.getAccessToken());
postRequest.setEntity(requestEntity);
httpClient.execute(postRequest);
}
}
}
} catch (UserStoreException e) {
String msg = "Error while accessing user store for user with Android device id: " +
deviceIdentifier.getId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (APIManagerException e) {
String msg = "Error while retrieving access token for Android device id: " + deviceIdentifier.getId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (HttpException e) {
String msg = "Error while calling the app store to install enrollment app with uuid: " + uuid +
" on device with id: " + deviceIdentifier.getId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (IOException e) {
String msg = "Error while installing the enrollment with uuid: " + uuid + " on device with id: " +
deviceIdentifier.getId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
}
}
/**
* Update status of pending operations to error when a dis-enroll operation is triggered.
*
* @param deviceIdentifier Identifier of the device
* @throws DeviceManagementException
*/
public static void updateDisEnrollOperationStatus(DeviceIdentifier deviceIdentifier)
throws DeviceManagementException {
try {
List<? extends Operation> pendingOperations = getPendingOperations(deviceIdentifier);
if (pendingOperations != null && !pendingOperations.isEmpty()) {
for (Operation operation : pendingOperations) {
operation.setStatus(Operation.Status.ERROR);
AndroidAPIUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation);
}
}
} catch (OperationManagementException e) {
String msg = "Error occurred while retrieving pending operations to update operation statuses of " +
"device to be dis-enrolled";
log.error(msg);
throw new DeviceManagementException(msg, e);
}
}
public static String getAndroidConfig(String key) throws DeviceManagementException {
String value = null;
PlatformConfiguration configuration = AndroidAPIUtils.getDeviceManagementService().
getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
if (configuration != null && configuration.getConfiguration() != null && configuration
.getConfiguration().size() > 0) {
List<ConfigurationEntry> configurations = configuration.getConfiguration();
for (ConfigurationEntry configurationEntry : configurations) {
if (configurationEntry.getName().equals(key)) {
value = (String)configurationEntry.getValue();
break;
}
}
}
return value;
}
public static String getAndroidConfig(PlatformConfiguration configuration, String key) {
String value = null;
if (configuration != null && configuration.getConfiguration() != null && configuration
.getConfiguration().size() > 0) {
List<ConfigurationEntry> configurations = configuration.getConfiguration();
for (ConfigurationEntry configurationEntry : configurations) {
if (configurationEntry.getName().equals(key)) {
value = (String)configurationEntry.getValue();
break;
}
}
}
return value;
}
public static ProfileFeature getEnrollmentFeature(DeviceIdentifier deviceIdentifier) throws
FeatureManagementException {
PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService();
List<ProfileFeature> effectiveProfileFeatures= policyManagerService.getEffectiveFeatures(deviceIdentifier);
if (effectiveProfileFeatures != null) {
for (ProfileFeature feature : effectiveProfileFeatures) {
if (AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE
.equals(feature.getFeatureCode())) {
return feature;
}
}
}
return null;
}
}

@ -36,379 +36,589 @@
package org.wso2.carbon.device.mgt.mobile.android.core.util; package org.wso2.carbon.device.mgt.mobile.android.core.util;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.httpclient.HttpException;
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.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
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.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; 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.Activity;
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.mobile.android.common.AndroidPluginConstants; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.mobile.android.common.config.datasource.AndroidDataSourceConfigurations; import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileDevice; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileDeviceOperationMapping; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileFeature; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileOperation; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileOperationProperty; import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils;
import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceState;
import org.wso2.carbon.device.mgt.mobile.android.common.config.datasource.AndroidDBConfigurations;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException;
import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder; import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder;
import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.registry.api.Resource; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties;
/** /**
* Provides utility methods required by the mobile device management bundle. * Provides utility methods required by the mobile device management bundle.
*/ */
public class MobileDeviceManagementUtil { public class MobileDeviceManagementUtil {
private static final Log log = LogFactory.getLog(MobileDeviceManagementUtil.class); private static final Log log = LogFactory.getLog(MobileDeviceManagementUtil.class);
private static final String MOBILE_DEVICE_IMEI = "IMEI";
private static final String MOBILE_DEVICE_IMSI = "IMSI";
private static final String MOBILE_DEVICE_VENDOR = "VENDOR";
private static final String MOBILE_DEVICE_OS_VERSION = "OS_VERSION";
private static final String MOBILE_DEVICE_MODEL = "DEVICE_MODEL";
private static final String MOBILE_DEVICE_LATITUDE = "LATITUDE";
private static final String MOBILE_DEVICE_LONGITUDE = "LONGITUDE";
private static final String MOBILE_DEVICE_ALTITUDE = "ALTITUDE";
private static final String MOBILE_DEVICE_DISTANCE = "DISTANCE";
private static final String MOBILE_DEVICE_SPEED = "SPEED";
private static final String MOBILE_DEVICE_BEARING = "BEARING";
private static final String MOBILE_DEVICE_SERIAL = "SERIAL";
private static final String MOBILE_DEVICE_OS_BUILD_DATE = "OS_BUILD_DATE";
public static Document convertToDocument(File file) throws DeviceManagementException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
throw new DeviceManagementException(
"Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document : " + e.getMessage(), e);
}
}
private static String getPropertyValue(Device device, String property) { public static Activity getOperationResponse(List<String> deviceIDs, Operation operation)
if (device != null && device.getProperties() != null) { throws AndroidDeviceMgtPluginException, OperationManagementException, InvalidDeviceException {
for (Device.Property prop : device.getProperties()) { if (deviceIDs == null || deviceIDs.isEmpty()) {
if (property.equals(prop.getName())) { String errorMessage = "Device identifier list is empty";
return prop.getValue(); log.error(errorMessage);
} throw new BadRequestException(errorMessage);
} }
} DeviceIdentifier deviceIdentifier;
return null; List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
} for (String deviceId : deviceIDs) {
deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID);
deviceIdentifiers.add(deviceIdentifier);
}
return AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers);
}
private static Device.Property getProperty(String property, String value) { public static boolean isValidDeviceIdentifier(Device device) {
if (property != null) { return !(device == null || device.getDeviceIdentifier() == null ||
Device.Property prop = new Device.Property(); device.getDeviceIdentifier().isEmpty() ||
prop.setName(property); device.getEnrolmentInfo() == null ||
prop.setValue(value); EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus()));
return prop; }
}
return null;
}
public static MobileDevice convertToMobileDevice(Device device) { public static List<? extends Operation> getPendingOperations
MobileDevice mobileDevice = null; (Device device) throws OperationManagementException {
if (device != null) { List<? extends Operation> operations;
mobileDevice = new MobileDevice(); operations = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
mobileDevice.setMobileDeviceId(device.getDeviceIdentifier()); .getPendingOperations(device);
mobileDevice.setImei(getPropertyValue(device, MOBILE_DEVICE_IMEI)); return operations;
mobileDevice.setImsi(getPropertyValue(device, MOBILE_DEVICE_IMSI)); }
mobileDevice.setModel(getPropertyValue(device, MOBILE_DEVICE_MODEL));
mobileDevice.setOsVersion(getPropertyValue(device, MOBILE_DEVICE_OS_VERSION));
mobileDevice.setVendor(getPropertyValue(device, MOBILE_DEVICE_VENDOR));
mobileDevice.setLatitude(getPropertyValue(device, MOBILE_DEVICE_LATITUDE));
mobileDevice.setLongitude(getPropertyValue(device, MOBILE_DEVICE_LONGITUDE));
mobileDevice.setAltitude(getPropertyValue(device, MOBILE_DEVICE_ALTITUDE));
mobileDevice.setDistance(getPropertyValue(device, MOBILE_DEVICE_DISTANCE));
mobileDevice.setSpeed(getPropertyValue(device, MOBILE_DEVICE_SPEED));
mobileDevice.setBearing(getPropertyValue(device, MOBILE_DEVICE_BEARING));
mobileDevice.setSerial(getPropertyValue(device, MOBILE_DEVICE_SERIAL));
mobileDevice.setOsBuildDate(getPropertyValue(device, MOBILE_DEVICE_OS_BUILD_DATE));
if (device.getProperties() != null) {
Map<String, String> deviceProperties = new HashMap<String, String>();
for (Device.Property deviceProperty : device.getProperties()) {
deviceProperties.put(deviceProperty.getName(), deviceProperty.getValue());
}
mobileDevice.setDeviceProperties(deviceProperties);
} else {
mobileDevice.setDeviceProperties(new HashMap<String, String>());
}
}
return mobileDevice;
}
public static Device convertToDevice(MobileDevice mobileDevice) { public static void updateOperation(Device device, Operation operation)
Device device = null; throws OperationManagementException, PolicyComplianceException,
if (mobileDevice != null) { org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException {
device = new Device(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
List<Device.Property> propertyList = new ArrayList<Device.Property>(); deviceIdentifier.setId(device.getDeviceIdentifier());
propertyList.add(getProperty(MOBILE_DEVICE_IMEI, mobileDevice.getImei())); deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
propertyList.add(getProperty(MOBILE_DEVICE_IMSI, mobileDevice.getImsi()));
propertyList.add(getProperty(MOBILE_DEVICE_MODEL, mobileDevice.getModel())); if (!Operation.Status.ERROR.equals(operation.getStatus()) &&
propertyList.add(getProperty(MOBILE_DEVICE_OS_VERSION, mobileDevice.getOsVersion())); AndroidConstants.OperationCodes.MONITOR.equals(operation.getCode())) {
propertyList.add(getProperty(MOBILE_DEVICE_OS_BUILD_DATE, mobileDevice.getOsBuildDate())); if (log.isDebugEnabled()) {
propertyList.add(getProperty(MOBILE_DEVICE_VENDOR, mobileDevice.getVendor())); log.debug("Received compliance status from MONITOR operation ID: " + operation.getId());
propertyList.add(getProperty(MOBILE_DEVICE_BEARING, mobileDevice.getBearing()));
propertyList.add(getProperty(MOBILE_DEVICE_SPEED, mobileDevice.getSpeed()));
propertyList.add(getProperty(MOBILE_DEVICE_DISTANCE, mobileDevice.getDistance()));
if(mobileDevice.getLatitude() != null) {
propertyList.add(getProperty(MOBILE_DEVICE_LATITUDE, mobileDevice.getLatitude()));
} }
if(mobileDevice.getLongitude() != null) { AndroidDeviceManagementDataHolder.getInstance().getPolicyManagerService()
propertyList.add(getProperty(MOBILE_DEVICE_LONGITUDE, mobileDevice.getLongitude())); .checkPolicyCompliance(deviceIdentifier, getComplianceFeatures(operation.getPayLoad()));
} else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants.
OperationCodes.APPLICATION_LIST.equals(operation.getCode())) {
if (log.isDebugEnabled()) {
log.debug("Received applications list from device '" + device.getDeviceIdentifier() + "'");
}
updateApplicationList(operation, device);
} else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants.
OperationCodes.DEVICE_INFO.equals(operation.getCode())) {
try {
if (log.isDebugEnabled()) {
log.debug("Operation response: " + operation.getOperationResponse());
}
Device deviceInfoBean = new Gson().fromJson(operation.getOperationResponse(), Device.class);
org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo = convertDeviceToInfo(deviceInfoBean);
updateDeviceInfo(device, deviceInfo);
} catch (DeviceDetailsMgtException e) {
throw new OperationManagementException("Error occurred while updating the device information.", e);
} }
if(mobileDevice.getAltitude() != null) {
propertyList.add(getProperty(MOBILE_DEVICE_ALTITUDE, mobileDevice.getAltitude()));
}
propertyList.add(getProperty(MOBILE_DEVICE_SERIAL, mobileDevice.getSerial()));
if (mobileDevice.getDeviceProperties() != null) {
for (Map.Entry<String, String> deviceProperty : mobileDevice.getDeviceProperties()
.entrySet()) {
propertyList
.add(getProperty(deviceProperty.getKey(), deviceProperty.getValue()));
}
}
device.setProperties(propertyList);
device.setDeviceIdentifier(mobileDevice.getMobileDeviceId());
}
return device;
}
public static MobileOperation convertToMobileOperation(Operation operation) { } else if (!Operation.Status.ERROR.equals(operation.getStatus()) &&
MobileOperation mobileOperation = new MobileOperation(); AndroidConstants.OperationCodes.DEVICE_LOCATION.equals(operation.getCode())) {
MobileOperationProperty operationProperty; try {
List<MobileOperationProperty> properties = new LinkedList<MobileOperationProperty>(); DeviceLocation location = new Gson().fromJson(operation.getOperationResponse(), DeviceLocation.class);
mobileOperation.setFeatureCode(operation.getCode()); // reason for checking "location.getLatitude() != null" because when device fails to provide
mobileOperation.setCreatedDate(new Date().getTime()); // device location and send status instead, above Gson converter create new location object
Properties operationProperties = operation.getProperties(); // with null attributes
for (String key : operationProperties.stringPropertyNames()) { if (location != null && location.getLatitude() != null) {
operationProperty = new MobileOperationProperty(); location.setDeviceIdentifier(deviceIdentifier);
operationProperty.setProperty(key); updateDeviceLocation(device, location);
operationProperty.setValue(operationProperties.getProperty(key)); }
properties.add(operationProperty); } catch (DeviceDetailsMgtException e) {
} throw new OperationManagementException("Error occurred while updating the device location.", e);
mobileOperation.setProperties(properties); }
return mobileOperation; } else if (AndroidConstants.OperationCodes.INSTALL_APPLICATION.equals(operation.getCode())
} || AndroidConstants.OperationCodes.UNINSTALL_APPLICATION.equals(operation.getCode())) {
try {
updateAppSubStatus(deviceIdentifier, operation.getId(), operation.getStatus().toString());
} catch (org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException e) {
String msg = "Error occurred while updating the app subscription for device.";
log.error(msg);
throw new OperationManagementException(msg, e);
} catch (DeviceManagementException e) {
String msg = "Error occurred while getting device data for device identifier.";
log.error(msg);
throw new OperationManagementException(msg, e);
}
}
AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.updateOperation(device, operation);
// This has to be bellow other if blocks, since updateOperation would fail if we execute against a disenrolled
// device.
if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants.
OperationCodes.WIPE_DATA.equals(operation.getCode())) {
if (log.isDebugEnabled()) {
log.debug("Received wipe data from device '" + device.getDeviceIdentifier() + "'");
}
try {
AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.disenrollDevice(deviceIdentifier);
} catch (DeviceManagementException e) {
throw new OperationManagementException("Error occurred while unenrolling the device.", e);
}
public static List<Integer> getMobileOperationIdsFromMobileDeviceOperations( }
List<MobileDeviceOperationMapping> mobileDeviceOperationMappings) { }
List<Integer> mobileOperationIds = new ArrayList<Integer>(mobileDeviceOperationMappings.size());
for (MobileDeviceOperationMapping mobileDeviceOperationMapping : mobileDeviceOperationMappings) {
mobileOperationIds.add(mobileDeviceOperationMapping.getOperationId());
}
return mobileOperationIds;
}
public static Operation convertMobileOperationToOperation(MobileOperation mobileOperation) { private static void updateApplicationList(Operation operation, Device device)
Operation operation = new Operation(); throws org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException {
Properties properties = new Properties(); // Parsing json string to get applications list.
operation.setCode(mobileOperation.getFeatureCode()); if (operation.getOperationResponse() != null) {
for (MobileOperationProperty mobileOperationProperty : mobileOperation.getProperties()) { if (operation.getOperationResponse().equals("SAME_APPLICATION_LIST")) {
properties return;
.put(mobileOperationProperty.getProperty(), mobileOperationProperty.getValue()); }
} JsonElement jsonElement = new JsonParser().parse(operation.getOperationResponse());
operation.setProperties(properties); JsonArray jsonArray = jsonElement.getAsJsonArray();
return operation; Application app;
} List<Application> applications = new ArrayList<>(jsonArray.size());
for (JsonElement element : jsonArray) {
app = new Application();
app.setName(element.getAsJsonObject().
get(AndroidConstants.ApplicationProperties.NAME).getAsString());
app.setApplicationIdentifier(element.getAsJsonObject().
get(AndroidConstants.ApplicationProperties.IDENTIFIER).getAsString());
app.setPlatform(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS) != null) {
app.setMemoryUsage(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS).getAsInt());
}
if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION) != null) {
app.setVersion(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION).getAsString());
}
if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE) != null) {
app.setActive(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE).getAsBoolean());
}
applications.add(app);
}
AndroidDeviceManagementDataHolder.getInstance().getApplicationManagementProviderService()
.updateApplicationListInstalledInDevice(device, applications);
} else {
if (log.isDebugEnabled()) {
log.debug("Operation Response is null.");
}
}
}
public static MobileFeature convertToMobileFeature(Feature feature) { private static void updateDeviceLocation(Device device, DeviceLocation deviceLocation)
MobileFeature mobileFeature = new MobileFeature(); throws DeviceDetailsMgtException {
mobileFeature.setName(feature.getName()); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
mobileFeature.setCode(feature.getCode()); DeviceInformationManager informationManager =
mobileFeature.setDescription(feature.getDescription()); (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null);
mobileFeature.setDeviceType(feature.getDeviceType());
mobileFeature.setType(feature.getType());
mobileFeature.setHidden(feature.isHidden());
return mobileFeature;
}
public static Feature convertToFeature(MobileFeature mobileFeature) { informationManager.addDeviceLocation(device, deviceLocation);
Feature feature = new Feature(); }
feature.setDescription(mobileFeature.getDescription());
feature.setDeviceType(mobileFeature.getDeviceType());
feature.setCode(mobileFeature.getCode());
feature.setName(mobileFeature.getName());
feature.setType(mobileFeature.getType());
feature.setHidden(mobileFeature.isHidden());
return feature;
}
public static Registry getConfigurationRegistry() throws AndroidDeviceMgtPluginException { private static void updateAppSubStatus(DeviceIdentifier deviceIdentifier, int operationId, String status)
try { throws org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException,
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); DeviceManagementException {
return AndroidDeviceManagementDataHolder.getInstance().getRegistryService() PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
.getConfigSystemRegistry( ApplicationManager applicationManager =
tenantId); (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
} catch (RegistryException e) { Device device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
throw new AndroidDeviceMgtPluginException( .getDevice(deviceIdentifier);
"Error in retrieving conf registry instance: " + applicationManager.updateSubsStatus(device.getId(), operationId, status);
e.getMessage(), e); }
}
}
public static Resource getRegistryResource(String path) throws AndroidDeviceMgtPluginException { private static void updateDeviceInfo(Device device, DeviceInfo deviceInfo)
try { throws DeviceDetailsMgtException {
if(MobileDeviceManagementUtil.getConfigurationRegistry().resourceExists(path)){ DeviceInformationManager informationManager = AndroidDeviceManagementDataHolder.getInstance()
return MobileDeviceManagementUtil.getConfigurationRegistry().get(path); .getDeviceInformationManager();
} informationManager.addDeviceInfo(device, deviceInfo);
}
private static org.wso2.carbon.device.mgt.common.device.details.DeviceInfo convertDeviceToInfo(Device device) {
org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo =
new org.wso2.carbon.device.mgt.common.device.details.DeviceInfo();
if (deviceInfo.getDeviceDetailsMap() == null) {
deviceInfo.setDeviceDetailsMap(new HashMap<>());
}
List<Device.Property> props = device.getProperties();
for (Device.Property prop : props) {
if (Utils.getDeviceDetailsColumnNames().containsValue(prop.getName())) {
extractDefinedProperties(deviceInfo, prop);
} else {
extractMapProperties(deviceInfo, prop);
}
}
return deviceInfo;
}
private static void extractMapProperties(DeviceInfo deviceInfo, Device.Property prop) {
if (prop.getName().equalsIgnoreCase("CPU_INFO")) {
deviceInfo.getDeviceDetailsMap().put("cpuUser", getProperty(prop.getValue(), "User"));
deviceInfo.getDeviceDetailsMap().put("cpuSystem", getProperty(prop.getValue(), "System"));
deviceInfo.getDeviceDetailsMap().put("IOW", getProperty(prop.getValue(), "IOW"));
deviceInfo.getDeviceDetailsMap().put("IRQ", getProperty(prop.getValue(), "IRQ"));
} else if (prop.getName().equalsIgnoreCase("RAM_INFO")) {
if (!getProperty(prop.getValue(), "TOTAL_MEMORY").isEmpty()) {
deviceInfo.setTotalRAMMemory(Double.parseDouble(getProperty(prop.getValue(), "TOTAL_MEMORY")));
} else {
deviceInfo.setTotalRAMMemory(-1D);
}
if (!getProperty(prop.getValue(), "AVAILABLE_MEMORY").isEmpty()) {
deviceInfo.setAvailableRAMMemory(Double.parseDouble(
getProperty(prop.getValue(), "AVAILABLE_MEMORY")));
} else {
deviceInfo.setAvailableRAMMemory(-1D);
}
deviceInfo.getDeviceDetailsMap().put("ramThreshold", getProperty(prop.getValue(), "THRESHOLD"));
deviceInfo.getDeviceDetailsMap().put("ramLowMemory", getProperty(prop.getValue(), "LOW_MEMORY"));
} else if (prop.getName().equalsIgnoreCase("BATTERY_INFO")) {
deviceInfo.setPluggedIn(Boolean.parseBoolean(getProperty(prop.getValue(), "PLUGGED")));
deviceInfo.getDeviceDetailsMap().put("batteryLevel", getProperty(prop.getValue(), "BATTERY_LEVEL"));
deviceInfo.getDeviceDetailsMap().put("batteryScale", getProperty(prop.getValue(), "SCALE"));
deviceInfo.getDeviceDetailsMap().put("batteryVoltage",
getProperty(prop.getValue(), "BATTERY_VOLTAGE"));
deviceInfo.getDeviceDetailsMap().put("batteryTemperature",
getProperty(prop.getValue(), "TEMPERATURE"));
deviceInfo.getDeviceDetailsMap().put("batteryCurrentTemperature",
getProperty(prop.getValue(), "CURRENT_AVERAGE"));
deviceInfo.getDeviceDetailsMap().put("batteryTechnology",
getProperty(prop.getValue(), "TECHNOLOGY"));
deviceInfo.getDeviceDetailsMap().put("batteryHealth", getProperty(prop.getValue(), "HEALTH"));
deviceInfo.getDeviceDetailsMap().put("batteryStatus", getProperty(prop.getValue(), "STATUS"));
} else if (prop.getName().equalsIgnoreCase("NETWORK_INFO")) {
deviceInfo.setSsid(getProperty(prop.getValue(), "WIFI_SSID"));
deviceInfo.setConnectionType(getProperty(prop.getValue(), "CONNECTION_TYPE"));
deviceInfo.getDeviceDetailsMap().put("mobileSignalStrength",
getProperty(prop.getValue(), "MOBILE_SIGNAL_STRENGTH"));
deviceInfo.getDeviceDetailsMap().put("wifiSignalStrength",
getProperty(prop.getValue(), "WIFI_SIGNAL_STRENGTH"));
} else if (prop.getName().equalsIgnoreCase("DEVICE_INFO")) {
if (!getProperty(prop.getValue(), "BATTERY_LEVEL").isEmpty()) {
deviceInfo.setBatteryLevel(Double.parseDouble(
getProperty(prop.getValue(), "BATTERY_LEVEL")));
} else {
deviceInfo.setBatteryLevel(-1D);
}
if (!getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY").isEmpty()) {
deviceInfo.setInternalTotalMemory(Double.parseDouble(
getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY")));
} else {
deviceInfo.setInternalTotalMemory(-1D);
}
if (!getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY").isEmpty()) {
deviceInfo.setInternalAvailableMemory(Double.parseDouble(
getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY")));
} else {
deviceInfo.setInternalAvailableMemory(-1D);
}
if (!getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY").isEmpty()) {
deviceInfo.setExternalTotalMemory(Double.parseDouble(
getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY")));
} else {
deviceInfo.setExternalTotalMemory(-1D);
}
if (!getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY").isEmpty()) {
deviceInfo.setExternalAvailableMemory(Double.parseDouble(
getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY")));
} else {
deviceInfo.setExternalAvailableMemory(-1D);
}
deviceInfo.getDeviceDetailsMap().put("encryptionEnabled",
getProperty(prop.getValue(), "ENCRYPTION_ENABLED"));
deviceInfo.getDeviceDetailsMap().put("passcodeEnabled",
getProperty(prop.getValue(), "PASSCODE_ENABLED"));
deviceInfo.getDeviceDetailsMap().put("operator",
getProperty(prop.getValue(), "OPERATOR"));
deviceInfo.getDeviceDetailsMap().put("PhoneNumber",
getProperty(prop.getValue(), "PHONE_NUMBER"));
} else if (prop.getName().equalsIgnoreCase("IMEI")) {
deviceInfo.getDeviceDetailsMap().put("IMEI", prop.getValue());
} else if (prop.getName().equalsIgnoreCase("IMSI")) {
deviceInfo.getDeviceDetailsMap().put("IMSI", prop.getValue());
} else if (prop.getName().equalsIgnoreCase("MAC")) {
deviceInfo.getDeviceDetailsMap().put("mac", prop.getValue());
} else if (prop.getName().equalsIgnoreCase("SERIAL")) {
deviceInfo.getDeviceDetailsMap().put("serial", prop.getValue());
} else {
deviceInfo.getDeviceDetailsMap().put(prop.getName(), prop.getValue());
}
}
private static void extractDefinedProperties(DeviceInfo deviceInfo, Device.Property prop) {
if (prop.getName().equalsIgnoreCase("DEVICE_MODEL")) {
deviceInfo.setDeviceModel(prop.getValue());
} else if (prop.getName().equalsIgnoreCase("VENDOR")) {
deviceInfo.setVendor(prop.getValue());
} else if (prop.getName().equalsIgnoreCase("OS_VERSION")) {
deviceInfo.setOsVersion(prop.getValue());
} else if (prop.getName().equalsIgnoreCase("OS_BUILD_DATE")) {
deviceInfo.setOsBuildDate(prop.getValue());
}
}
private static String getProperty(String properties, String needed) {
// This is not a key value pair. value is the immediate element to its filed name.
// Ex:
// [{"name":"ENCRYPTION_ENABLED","value":"false"},{"name":"PASSCODE_ENABLED","value":"true"},
// {"name":"BATTERY_LEVEL","value":"100"},{"name":"INTERNAL_TOTAL_MEMORY","value":"0.76"}]
JsonElement jsonElement = new JsonParser().parse(properties);
JsonArray jsonArray = jsonElement.getAsJsonArray();
for (JsonElement element : jsonArray) {
if (element.isJsonObject()) {
JsonObject jsonObject = element.getAsJsonObject();
if (jsonObject.has("name")
&& jsonObject.get("name").getAsString().equalsIgnoreCase(needed)) {
if (jsonObject.has("value") && jsonObject.get("value") != JsonNull.INSTANCE) {
return jsonObject.get("value").getAsString().replace("%", "");
} else {
return "";
}
}
}
}
return "";
}
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username != null && username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static void installEnrollmentApplications(ProfileFeature feature, DeviceIdentifier deviceIdentifier)
throws PolicyManagementException {
String uuid = "";
try {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
ApiApplicationKey apiApplicationKey = OAuthUtils.getClientCredentials(tenantDomain);
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName() + AndroidConstants.ApplicationInstall.AT + tenantDomain;
AccessTokenInfo tokenInfo = OAuthUtils.getOAuthCredentials(apiApplicationKey, username);
String requestUrl = AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_PROTOCOL +
System.getProperty(AndroidConstants.ApplicationInstall.IOT_CORE_HOST) +
AndroidConstants.ApplicationInstall.COLON +
System.getProperty(AndroidConstants.ApplicationInstall.IOT_CORE_PORT) +
AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_URL;
JsonElement appListElement = new JsonParser().parse(feature.getContent().toString()).getAsJsonObject()
.get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE);
JSONObject deviceObject = new JSONObject();
deviceObject.put("id", deviceIdentifier.getId());
deviceObject.put("type", deviceIdentifier.getType());
JSONArray payload = new JSONArray();
payload.put(deviceObject);
StringEntity requestEntity = new StringEntity(payload.toString(), ContentType.APPLICATION_JSON);
JsonArray appListArray = appListElement.getAsJsonArray();
for (JsonElement appElement : appListArray) {
JsonElement googlePolicyPayload = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD);
if (googlePolicyPayload == null || googlePolicyPayload.toString().equals("\"\"")) {
uuid = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_UUID).getAsString();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost postRequest = new HttpPost(requestUrl.replace("{uuid}", uuid));
postRequest.setHeader(AndroidConstants.ApplicationInstall.AUTHORIZATION,
AndroidConstants.ApplicationInstall.AUTHORIZATION_HEADER_VALUE + tokenInfo
.getAccessToken());
postRequest.setEntity(requestEntity);
httpClient.execute(postRequest);
}
}
}
} catch (UserStoreException e) {
String msg = "Error while accessing user store for user with Android device id: " +
deviceIdentifier.getId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (APIManagerException e) {
String msg = "Error while retrieving access token for Android device id: " + deviceIdentifier.getId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (HttpException e) {
String msg = "Error while calling the app store to install enrollment app with uuid: " + uuid +
" on device with id: " + deviceIdentifier.getId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
} catch (IOException e) {
String msg = "Error while installing the enrollment with uuid: " + uuid + " on device with id: " +
deviceIdentifier.getId();
log.error(msg, e);
throw new PolicyManagementException(msg, e);
}
}
/**
* Update status of pending operations to error when a dis-enroll operation is triggered.
*
* @param device the device
* @throws DeviceManagementException
*/
public static void updateDisEnrollOperationStatus(Device device)
throws DeviceManagementException {
try {
List<? extends Operation> pendingOperations = getPendingOperations(device);
if (pendingOperations != null && !pendingOperations.isEmpty()) {
for (Operation operation : pendingOperations) {
operation.setStatus(Operation.Status.ERROR);
AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.updateOperation(device, operation);
}
}
} catch (OperationManagementException e) {
String msg = "Error occurred while retrieving pending operations to update operation statuses of " +
"device to be dis-enrolled";
log.error(msg);
throw new DeviceManagementException(msg, e);
}
}
public static List<DeviceState> getAllEventsForDevice(String tableName, String query) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = AndroidDeviceManagementDataHolder.getInstance().getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) {
return null; return null;
} catch (RegistryException e) {
throw new AndroidDeviceMgtPluginException("Error in retrieving registry resource : " +
e.getMessage(), e);
} }
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount);
List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, DeviceState> deviceStateses = createDeviceStatusData(AnalyticsDataAPIUtil.listRecords(
analyticsDataAPI, response));
return getSortedDeviceStateData(deviceStateses, resultEntries);
} }
public static boolean putRegistryResource(String path, private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
Resource resource) List<String> ids = new ArrayList<>();
throws AndroidDeviceMgtPluginException { for (SearchResultEntry searchResult : searchResults) {
boolean status; ids.add(searchResult.getId());
try {
MobileDeviceManagementUtil.getConfigurationRegistry().beginTransaction();
MobileDeviceManagementUtil.getConfigurationRegistry().put(path, resource);
MobileDeviceManagementUtil.getConfigurationRegistry().commitTransaction();
status = true;
} catch (RegistryException e) {
throw new AndroidDeviceMgtPluginException(
"Error occurred while persisting registry resource : " +
e.getMessage(), e);
} }
return status; return ids;
} }
public static String getResourcePath(String resourceName, String platform) { public static Map<String, DeviceState> createDeviceStatusData(List<Record> records) {
String regPath = ""; Map<String, DeviceState> deviceStatuses = new HashMap<>();
switch (platform) { for (Record record : records) {
case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID: DeviceState deviceState = createDeviceStatusData(record);
regPath = AndroidPluginConstants.MobilePluginConstants deviceStatuses.put(deviceState.getId(), deviceState);
.MOBILE_CONFIG_REGISTRY_ROOT + "/" +
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID +
"/" + resourceName;
break;
case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS:
regPath = AndroidPluginConstants.MobilePluginConstants.MOBILE_CONFIG_REGISTRY_ROOT + "/" +
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS +
"/" + resourceName;
break;
case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS:
regPath = AndroidPluginConstants.MobilePluginConstants.MOBILE_CONFIG_REGISTRY_ROOT + "/" +
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS +
"/" + resourceName;
break;
} }
return regPath; return deviceStatuses;
} }
public static String getPlatformConfigPath(String platform) { private static DeviceState createDeviceStatusData(Record record) {
String regPath = ""; DeviceState deviceState = new DeviceState();
switch (platform) { deviceState.setId(record.getId());
case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID: deviceState.setValues(record.getValues());
regPath = DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID; return deviceState;
break;
case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS:
regPath = DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS;
break;
case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS:
regPath = DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS;
break;
}
return regPath;
} }
public static boolean createRegistryCollection(String path) public static List<DeviceState> getSortedDeviceStateData(Map<String, DeviceState> sensorDatas,
throws AndroidDeviceMgtPluginException { List<SearchResultEntry> searchResults) {
try { List<DeviceState> sortedRecords = new ArrayList<>();
if (! MobileDeviceManagementUtil.getConfigurationRegistry().resourceExists(path)) { for (SearchResultEntry searchResultEntry : searchResults) {
Resource resource = MobileDeviceManagementUtil.getConfigurationRegistry().newCollection(); sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
MobileDeviceManagementUtil.getConfigurationRegistry().beginTransaction();
MobileDeviceManagementUtil.getConfigurationRegistry().put(path, resource);
MobileDeviceManagementUtil.getConfigurationRegistry().commitTransaction();
}
return true;
} catch (AndroidDeviceMgtPluginException e) {
throw new AndroidDeviceMgtPluginException(
"Error occurred while creating a registry collection : " +
e.getMessage(), e);
} catch (RegistryException e) {
throw new AndroidDeviceMgtPluginException(
"Error occurred while creating a registry collection : " +
e.getMessage(), e);
} }
return sortedRecords;
} }
public static List<Feature> getMissingFeatures(List<Feature> supportedFeatures, List<Feature> existingFeatures) { public static DeviceIdentifier convertToDeviceIdentifierObject(String deviceId) {
HashMap<String,Feature> featureHashMap = new HashMap(); DeviceIdentifier identifier = new DeviceIdentifier();
for (Feature feature: existingFeatures) { identifier.setId(deviceId);
featureHashMap.put(feature.getCode(),feature); identifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
} return identifier;
List<Feature> missingFeatures = new ArrayList<Feature>();
for (Feature supportedFeature : supportedFeatures) {
if (featureHashMap.get(supportedFeature.getCode()) != null) {
continue;
}
missingFeatures.add(supportedFeature);
}
return missingFeatures;
} }
public static final String IOS_DB_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator + private static List<ComplianceFeature> getComplianceFeatures(Object compliancePayload)
"/android-dbconfig.xml"; throws PolicyComplianceException {
String compliancePayloadString = new Gson().toJson(compliancePayload);
if (compliancePayload == null) {
return null;
}
// Parsing json string to get compliance features.
JsonElement jsonElement;
if (compliancePayloadString instanceof String) {
jsonElement = new JsonParser().parse(compliancePayloadString);
} else {
throw new PolicyComplianceException("Invalid policy compliance payload");
}
public static AndroidDataSourceConfigurations iosDataSourceConfigurations; JsonArray jsonArray = jsonElement.getAsJsonArray();
public static AndroidDataSourceConfigurations getIosDataSourceConfigurations() { Gson gson = new Gson();
return iosDataSourceConfigurations; ComplianceFeature complianceFeature;
} List<ComplianceFeature> complianceFeatures = new ArrayList<ComplianceFeature>(jsonArray.size());
public static synchronized void initConfig() throws DeviceManagementException { for (JsonElement element : jsonArray) {
try { complianceFeature = gson.fromJson(element, ComplianceFeature.class);
File mobileDeviceMgtConfig = new File(IOS_DB_CONFIG_PATH); complianceFeatures.add(complianceFeature);
Document doc = convertToDocuments(mobileDeviceMgtConfig); }
JAXBContext iosDeviceMgtContext = JAXBContext.newInstance(AndroidDataSourceConfigurations.class); return complianceFeatures;
Unmarshaller unmarshaller = iosDeviceMgtContext.createUnmarshaller(); }
iosDataSourceConfigurations = (AndroidDataSourceConfigurations) unmarshaller.unmarshal(doc);
} catch (Exception e) {
throw new DeviceManagementException(
"Error occurred while initializing Mobile Device Management config", e);
}
}
public static Document convertToDocuments(File file) throws DeviceManagementException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
throw new DeviceManagementException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document : " + e.getMessage(), e);
}
}
} }

@ -28,18 +28,16 @@ import org.powermock.modules.testng.PowerMockObjectFactory;
import org.testng.IObjectFactory; import org.testng.IObjectFactory;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.ObjectFactory; import org.testng.annotations.ObjectFactory;
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.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
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.mobile.android.common.exception.AndroidDeviceMgtPluginException; import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl; import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl;
import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceManagementProviderServiceMock; import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceManagementProviderServiceMock;
import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.utils.TestUtils; import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.utils.TestUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils;
@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) @PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"})
@PrepareForTest(AndroidAPIUtils.class) @PrepareForTest(AndroidDeviceManagementDataHolder.class)
public class DeviceManagementAdminServiceTests { public class DeviceManagementAdminServiceTests {
private AndroidServiceImpl androidService; private AndroidServiceImpl androidService;
@ -56,7 +54,7 @@ public class DeviceManagementAdminServiceTests {
} }
private void mockDeviceManagementService() { private void mockDeviceManagementService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceManagementProviderService"))
.toReturn(new DeviceManagementProviderServiceMock()); .toReturn(new DeviceManagementProviderServiceMock());
} }

@ -36,23 +36,22 @@ 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.mobile.android.common.Message; import org.wso2.carbon.device.mgt.mobile.android.common.Message;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidDevice; import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidDevice;
import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl; import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl;
import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.ApplicationManagementProviderServiceMock; import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.ApplicationManagementProviderServiceMock;
import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceInformationManagerServiceMock; import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceInformationManagerServiceMock;
import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceManagementProviderServiceMock; import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceManagementProviderServiceMock;
import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.NotificationManagementServiceMock; import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.NotificationManagementServiceMock;
import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.PolicyManagerServiceMock; import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.PolicyManagerServiceMock;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidAPIUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.utils.TestUtils; import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.utils.TestUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidDeviceUtils; import org.wso2.carbon.device.mgt.mobile.android.core.util.MobileDeviceManagementUtil;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) @PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"})
@PrepareForTest(AndroidAPIUtils.class) @PrepareForTest({AndroidDeviceManagementDataHolder.class, MobileDeviceManagementUtil.class})
public class DeviceManagementServiceTests { public class DeviceManagementServiceTests {
private AndroidServiceImpl androidService; private AndroidServiceImpl androidService;
@ -69,32 +68,32 @@ public class DeviceManagementServiceTests {
} }
private void mockDeviceManagementService() { private void mockDeviceManagementService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceManagementService")) PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceManagementProviderService"))
.toReturn(new DeviceManagementProviderServiceMock()); .toReturn(new DeviceManagementProviderServiceMock());
} }
private void mockApplicationManagerService() { private void mockApplicationManagerService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getApplicationManagerService")) PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getApplicationManagementProviderService"))
.toReturn(new ApplicationManagementProviderServiceMock()); .toReturn(new ApplicationManagementProviderServiceMock());
} }
private void mockPolicyManagerService() { private void mockPolicyManagerService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getPolicyManagerService")) PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getPolicyManagerService"))
.toReturn(new PolicyManagerServiceMock()); .toReturn(new PolicyManagerServiceMock());
} }
private void mockDeviceInformationManagerService() { private void mockDeviceInformationManagerService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceInformationManagerService")) PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceInformationManager"))
.toReturn(new DeviceInformationManagerServiceMock()); .toReturn(new DeviceInformationManagerServiceMock());
} }
private void mockNotificationManagementService() { private void mockNotificationManagementService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getNotificationManagementService")) PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getNotificationManagementService"))
.toReturn(new NotificationManagementServiceMock()); .toReturn(new NotificationManagementServiceMock());
} }
private void mockUser() { private void mockUser() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getAuthenticatedUser")) PowerMockito.stub(PowerMockito.method(MobileDeviceManagementUtil.class, "getAuthenticatedUser"))
.toReturn("admin"); .toReturn("admin");
} }
@ -110,25 +109,25 @@ public class DeviceManagementServiceTests {
@Test (expectedExceptions = {InvalidDeviceException.class}) @Test (expectedExceptions = {InvalidDeviceException.class})
public void testGetPendingOperationsForNullDevice() public void testGetPendingOperationsForNullDevice()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
List<? extends Operation> resultOperations = new ArrayList<>(); List<? extends Operation> resultOperations = new ArrayList<>();
androidService.getPendingOperations(null, resultOperations); androidService.getPendingOperations(null, resultOperations);
} }
@Test (expectedExceptions = {InvalidDeviceException.class}) @Test (expectedExceptions = {InvalidDeviceException.class})
public void testGetPendingOperationsForInvalidDevice() public void testGetPendingOperationsForInvalidDevice()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService(); mockDeviceManagementService();
List<? extends Operation> resultOperations = new ArrayList<>(); List<? extends Operation> resultOperations = new ArrayList<>();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject("1234"); DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject("1234");
androidService.getPendingOperations(deviceIdentifier, resultOperations); androidService.getPendingOperations(deviceIdentifier, resultOperations);
} }
@Test @Test
public void testGetPendingOperationsNullResponse() public void testGetPendingOperationsNullResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService(); mockDeviceManagementService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, null); .getPendingOperations(deviceIdentifier, null);
Assert.assertNotNull(pendingOperations); Assert.assertNotNull(pendingOperations);
@ -137,10 +136,10 @@ public class DeviceManagementServiceTests {
@Test @Test
public void testGetPendingOperationsWithMonitorResponse() public void testGetPendingOperationsWithMonitorResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService(); mockDeviceManagementService();
mockPolicyManagerService(); mockPolicyManagerService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getSuccessMonitorOperationResponse()); .getPendingOperations(deviceIdentifier, TestUtils.getSuccessMonitorOperationResponse());
Assert.assertNotNull(pendingOperations); Assert.assertNotNull(pendingOperations);
@ -149,10 +148,10 @@ public class DeviceManagementServiceTests {
@Test @Test
public void testGetPendingOperationsWithApplicationResponse() public void testGetPendingOperationsWithApplicationResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService(); mockDeviceManagementService();
mockApplicationManagerService(); mockApplicationManagerService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getSuccessApplicationOperationResponse()); .getPendingOperations(deviceIdentifier, TestUtils.getSuccessApplicationOperationResponse());
Assert.assertNotNull(pendingOperations); Assert.assertNotNull(pendingOperations);
@ -161,10 +160,10 @@ public class DeviceManagementServiceTests {
@Test @Test
public void testGetPendingOperationsWithDeviceInfoResponse() public void testGetPendingOperationsWithDeviceInfoResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService(); mockDeviceManagementService();
mockDeviceInformationManagerService(); mockDeviceInformationManagerService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getSuccessInfoOperationResponse()); .getPendingOperations(deviceIdentifier, TestUtils.getSuccessInfoOperationResponse());
Assert.assertNotNull(pendingOperations); Assert.assertNotNull(pendingOperations);
@ -173,9 +172,9 @@ public class DeviceManagementServiceTests {
@Test @Test
public void testGetPendingOperationsWithInProgressResponse() public void testGetPendingOperationsWithInProgressResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService(); mockDeviceManagementService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getInProgressOperationResponse()); .getPendingOperations(deviceIdentifier, TestUtils.getInProgressOperationResponse());
Assert.assertNotNull(pendingOperations); Assert.assertNotNull(pendingOperations);
@ -184,10 +183,10 @@ public class DeviceManagementServiceTests {
@Test @Test
public void testGetPendingOperationsWithErrorResponse() public void testGetPendingOperationsWithErrorResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService(); mockDeviceManagementService();
mockNotificationManagementService(); mockNotificationManagementService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getErrorOperationResponse()); .getPendingOperations(deviceIdentifier, TestUtils.getErrorOperationResponse());
Assert.assertNotNull(pendingOperations); Assert.assertNotNull(pendingOperations);
@ -196,7 +195,7 @@ public class DeviceManagementServiceTests {
@Test @Test
public void testEnrollDeviceWithoutLocationSuccess() public void testEnrollDeviceWithoutLocationSuccess()
throws DeviceManagementException, AndroidDeviceMgtPluginException { throws DeviceManagementException {
mockDeviceManagementService(); mockDeviceManagementService();
mockPolicyManagerService(); mockPolicyManagerService();
mockUser(); mockUser();
@ -206,8 +205,7 @@ public class DeviceManagementServiceTests {
} }
@Test @Test
public void testEnrollDeviceWithLocationSuccess() public void testEnrollDeviceWithLocationSuccess() throws DeviceManagementException {
throws DeviceManagementException, AndroidDeviceMgtPluginException {
mockDeviceManagementService(); mockDeviceManagementService();
mockDeviceInformationManagerService(); mockDeviceInformationManagerService();
mockPolicyManagerService(); mockPolicyManagerService();
@ -247,8 +245,7 @@ public class DeviceManagementServiceTests {
} }
@Test @Test
public void testEnrollDeviceUnSuccess() public void testEnrollDeviceUnSuccess() throws DeviceManagementException {
throws DeviceManagementException, AndroidDeviceMgtPluginException {
mockDeviceManagementService(); mockDeviceManagementService();
mockUser(); mockUser();
AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice(); AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice();
@ -259,8 +256,7 @@ public class DeviceManagementServiceTests {
} }
@Test @Test
public void testIsEnrolledExists() public void testIsEnrolledExists() throws DeviceManagementException {
throws DeviceManagementException {
mockDeviceManagementService(); mockDeviceManagementService();
Message message = androidService.isEnrolled(TestUtils.getDeviceId(), null); Message message = androidService.isEnrolled(TestUtils.getDeviceId(), null);
Assert.assertNotNull(message); Assert.assertNotNull(message);
@ -268,8 +264,7 @@ public class DeviceManagementServiceTests {
} }
@Test @Test
public void testIsEnrolledNonExist() public void testIsEnrolledNonExist() throws DeviceManagementException {
throws DeviceManagementException {
mockDeviceManagementService(); mockDeviceManagementService();
Message message = androidService.isEnrolled("1234", null); Message message = androidService.isEnrolled("1234", null);
Assert.assertNotNull(message); Assert.assertNotNull(message);
@ -277,8 +272,7 @@ public class DeviceManagementServiceTests {
} }
@Test @Test
public void testIsEnrolledNull() public void testIsEnrolledNull() throws DeviceManagementException {
throws DeviceManagementException {
mockDeviceManagementService(); mockDeviceManagementService();
Message response = androidService.isEnrolled(null, null); Message response = androidService.isEnrolled(null, null);
Assert.assertNotNull(response); Assert.assertNotNull(response);
@ -286,8 +280,7 @@ public class DeviceManagementServiceTests {
} }
@Test @Test
public void testModifyEnrollmentSuccess() public void testModifyEnrollmentSuccess() throws DeviceManagementException {
throws DeviceManagementException, AndroidDeviceMgtPluginException {
mockDeviceManagementService(); mockDeviceManagementService();
mockUser(); mockUser();
boolean status = androidService.modifyEnrollment(TestUtils.getDeviceId(), TestUtils.getBasicAndroidDevice()); boolean status = androidService.modifyEnrollment(TestUtils.getDeviceId(), TestUtils.getBasicAndroidDevice());
@ -295,28 +288,24 @@ public class DeviceManagementServiceTests {
} }
@Test @Test
public void testModifyEnrollmentUnSuccess() public void testModifyEnrollmentUnSuccess() throws DeviceManagementException {
throws DeviceManagementException, AndroidDeviceMgtPluginException {
mockDeviceManagementService(); mockDeviceManagementService();
mockUser(); mockUser();
AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice(); AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice();
androidDevice.setDeviceIdentifier("1234"); androidDevice.setDeviceIdentifier("1234");
boolean status = androidService boolean status = androidService.modifyEnrollment(TestUtils.getDeviceId(), androidDevice);
.modifyEnrollment(TestUtils.getDeviceId(), androidDevice);
Assert.assertFalse(status); Assert.assertFalse(status);
} }
@Test @Test
public void testDisEnrollDeviceSuccess() public void testDisEnrollDeviceSuccess() throws DeviceManagementException {
throws DeviceManagementException {
mockDeviceManagementService(); mockDeviceManagementService();
boolean status = androidService.disEnrollDevice(TestUtils.getDeviceId()); boolean status = androidService.disEnrollDevice(TestUtils.getDeviceId());
Assert.assertTrue(status); Assert.assertTrue(status);
} }
@Test @Test
public void testDisEnrollUnSuccess() public void testDisEnrollUnSuccess() throws DeviceManagementException {
throws DeviceManagementException {
mockDeviceManagementService(); mockDeviceManagementService();
boolean status = androidService.disEnrollDevice("1234"); boolean status = androidService.disEnrollDevice("1234");
Assert.assertFalse(status); Assert.assertFalse(status);

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.mobile.android.core.mokcs; package org.wso2.carbon.device.mgt.mobile.android.core.mokcs;
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.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
@ -34,12 +35,22 @@ public class ApplicationManagementProviderServiceMock implements ApplicationMana
} }
@Override
public void updateApplicationListInstalledInDevice(Device device, List<Application> list) throws ApplicationManagementException {
}
@Override @Override
public List<Application> getApplicationListForDevice(DeviceIdentifier deviceIdentifier) public List<Application> getApplicationListForDevice(DeviceIdentifier deviceIdentifier)
throws ApplicationManagementException { throws ApplicationManagementException {
return null; return null;
} }
@Override
public List<Application> getApplicationListForDevice(Device device) throws ApplicationManagementException {
return null;
}
@Override @Override
public Application[] getApplications(String s, int i, int i1) throws ApplicationManagementException { public Application[] getApplications(String s, int i, int i1) throws ApplicationManagementException {
return new Application[0]; return new Application[0];

@ -1,5 +1,6 @@
package org.wso2.carbon.device.mgt.mobile.android.core.mokcs; package org.wso2.carbon.device.mgt.mobile.android.core.mokcs;
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.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
@ -9,12 +10,18 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManag
import java.util.List; import java.util.List;
public class DeviceInformationManagerServiceMock implements DeviceInformationManager { public class DeviceInformationManagerServiceMock implements DeviceInformationManager {
@Override @Override
public void addDeviceInfo(DeviceIdentifier deviceIdentifier, DeviceInfo deviceInfo) public void addDeviceInfo(DeviceIdentifier deviceIdentifier, DeviceInfo deviceInfo)
throws DeviceDetailsMgtException { throws DeviceDetailsMgtException {
} }
@Override
public void addDeviceInfo(Device device, DeviceInfo deviceInfo) throws DeviceDetailsMgtException {
}
@Override @Override
public DeviceInfo getDeviceInfo(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException { public DeviceInfo getDeviceInfo(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException {
return null; return null;
@ -30,6 +37,11 @@ public class DeviceInformationManagerServiceMock implements DeviceInformationMan
} }
@Override
public void addDeviceLocation(Device device, DeviceLocation deviceLocation) throws DeviceDetailsMgtException {
}
@Override @Override
public DeviceLocation getDeviceLocation(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException { public DeviceLocation getDeviceLocation(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException {
return null; return null;

@ -50,13 +50,13 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfiguratio
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException;
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.exceptions.UnauthorizedDeviceAccessException; import org.wso2.carbon.device.mgt.common.exceptions.UnauthorizedDeviceAccessException;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
@ -482,6 +482,11 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv
return null; return null;
} }
@Override
public List<? extends Operation> getPendingOperations(Device device) throws OperationManagementException {
return null;
}
@Override @Override
public Operation getNextPendingOperation(DeviceIdentifier deviceIdentifier) throws OperationManagementException { public Operation getNextPendingOperation(DeviceIdentifier deviceIdentifier) throws OperationManagementException {
return null; return null;
@ -499,6 +504,11 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv
} }
@Override
public void updateOperation(Device device, Operation operation) throws OperationManagementException {
}
@Override @Override
public boolean updateProperties(DeviceIdentifier deviceIdentifier, List<Device.Property> list) throws DeviceManagementException { public boolean updateProperties(DeviceIdentifier deviceIdentifier, List<Device.Property> list) throws DeviceManagementException {
return false; return false;

@ -59,7 +59,7 @@ import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.VpnBeanWrap
import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WebClipBeanWrapper; import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WebClipBeanWrapper;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WifiBeanWrapper; import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WifiBeanWrapper;
import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WipeDataBeanWrapper; import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WipeDataBeanWrapper;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidDeviceUtils; import org.wso2.carbon.device.mgt.mobile.android.core.util.MobileDeviceManagementUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -381,7 +381,7 @@ public class TestUtils {
location.setCountry("Sri Lanka"); location.setCountry("Sri Lanka");
location.setLatitude(6.9); location.setLatitude(6.9);
location.setLongitude(79.5); location.setLongitude(79.5);
location.setDeviceIdentifier(AndroidDeviceUtils.convertToDeviceIdentifierObject(getDeviceId())); location.setDeviceIdentifier(MobileDeviceManagementUtil.convertToDeviceIdentifierObject(getDeviceId()));
return location; return location;
} }

@ -160,7 +160,7 @@ function onRequest(context) {
viewModel["osBuildDate"] = new Date(filteredDeviceData["latestDeviceInfo"]["osBuildDate"] * 1000); viewModel["osBuildDate"] = new Date(filteredDeviceData["latestDeviceInfo"]["osBuildDate"] * 1000);
} }
} }
if (filteredDeviceData["latestDeviceInfo"]["location"]["latitude"] && if (filteredDeviceData["latestDeviceInfo"]["location"] && filteredDeviceData["latestDeviceInfo"]["location"]["latitude"] &&
filteredDeviceData["latestDeviceInfo"]["location"]["longitude"]) { filteredDeviceData["latestDeviceInfo"]["location"]["longitude"]) {
viewModel["location"] = {}; viewModel["location"] = {};
viewModel["location"]["latitude"] = filteredDeviceData["latestDeviceInfo"]["location"]["latitude"]; viewModel["location"]["latitude"] = filteredDeviceData["latestDeviceInfo"]["location"]["latitude"];

@ -1,8 +1,8 @@
<!-- <!--
~ /* ~ /*
~ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
~ * ~ *
~ * WSO2 Inc. licenses this file to you under the Apache License, ~ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
~ * Version 2.0 (the "License"); you may not use this file except ~ * Version 2.0 (the "License"); you may not use this file except
~ * in compliance with the License. ~ * in compliance with the License.
~ * You may obtain a copy of the License at ~ * You may obtain a copy of the License at
@ -16,10 +16,10 @@
~ * specific language governing permissions and limitations ~ * specific language governing permissions and limitations
~ * under the License. ~ * under the License.
--> -->
<iosDBConfigurations> <AndroidDBConfigurations>
<DataSourceConfiguration> <DataSourceConfiguration>
<JndiLookupDefinition> <JndiLookupDefinition>
<Name>jdbc/MobileAndroidDM_DS</Name> <Name>jdbc/MobileAndroidDM_DS</Name>
</JndiLookupDefinition> </JndiLookupDefinition>
</DataSourceConfiguration> </DataSourceConfiguration>
</iosDBConfigurations> </AndroidDBConfigurations>

Loading…
Cancel
Save