Performance Improvements

revert-dabc3590
Charitha Goonetilleke 5 years ago committed by Inosh Perara
parent 9ca405b802
commit 6c9f4883dc

@ -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.NotFoundException;
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.core.util.AndroidDeviceUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidEnterpriseUtils;
import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils;
import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidDeviceUtils;
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.policy.mgt.common.FeatureManagementException;
@ -737,7 +737,7 @@ public class AndroidEnterpriseAPIImpl implements AndroidEnterpriseAPI {
String trimmedPackage = productId.replaceFirst("app:", "");
productIds.add(trimmedPackage);
}
ApplicationManager appManager = AndroidEnterpriseUtils.getAppManagerServer();
ApplicationManager appManager = AndroidAPIUtils.getAppManagerService();
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.exception.*;
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.util.AndroidDeviceUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.AndroidEnterpriseUtils;
import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils;
import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidDeviceUtils;
import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidEnterpriseUtils;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@ -389,7 +389,7 @@ public class DeviceManagementAPIImpl implements DeviceManagementAPI {
googleAPIInvoker.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(),
AndroidEnterpriseUtils.convertToDeviceInstance(enterpriseInstallPolicy));
}
AndroidEnterpriseUtils.getAppSubscriptionService().performEntAppSubscription(uuid,
AndroidAPIUtils.getAppSubscriptionService().performEntAppSubscription(uuid,
Arrays.asList(CarbonContext.getThreadLocalCarbonContext().getUsername()),
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 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.exceptions.InvalidDeviceException;
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.core.operation.mgt.ProfileOperation;
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.wrapper.ApplicationInstallationBeanWrapper;
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.BadRequestException;
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.ws.rs.Consumes;
@ -75,6 +78,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
@Path("/admin/devices")
@ -1003,6 +1007,7 @@ public class DeviceManagementAdminAPIImpl implements DeviceManagementAdminAPI {
.setMessage(errorMessage).build()).build();
}
}
@POST
@Path("/send-app-conf")
@Override
@ -1015,9 +1020,17 @@ public class DeviceManagementAdminAPIImpl implements DeviceManagementAdminAPI {
try{
AndroidService androidService = AndroidAPIUtils.getAndroidService();
ProfileOperation operation = androidService.sendApplicationConfiguration(applicationRestrictionBeanWrapper);
Response response = AndroidAPIUtils.getOperationResponse(applicationRestrictionBeanWrapper.getDeviceIDs(),
operation);
return Response.status(Response.Status.CREATED).entity(response).build();
DeviceIdentifier deviceIdentifier;
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
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) {
String errorMessage = "Invalid Device Identifiers found.";
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.BadRequestException;
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.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.exception.*;
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.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.
*/
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.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.Category;
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.PublicAppReleaseWrapper;
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.List;
import java.util.Map;
import java.util.stream.Collectors;
public class AndroidEnterpriseUtils {
private static Log log = LogFactory.getLog(AndroidEnterpriseUtils.class);
private static RealmService realmService = null;
private static List<String> templates = Arrays.asList(AndroidConstants
.USER_CLAIM_EMAIL_ADDRESS_PLACEHOLDER, AndroidConstants.USER_CLAIM_FIRST_NAME_PLACEHOLDER,
AndroidConstants.USER_CLAIM_LAST_NAME_PLACEHOLDER);
public static Device convertToDeviceInstance(EnterpriseInstallPolicy enterpriseInstallPolicy)
throws EnterpriseServiceException {
Device device = new Device();
@ -171,15 +169,16 @@ public class AndroidEnterpriseUtils {
}
private static UserStoreManager getUserStoreManager() throws EnterpriseServiceException {
RealmService realmService;
UserStoreManager userStoreManager = null;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "Realm service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "Realm service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
UserStoreManager userStoreManager;
int tenantId = ctx.getTenantId();
try {
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
@ -224,9 +223,9 @@ public class AndroidEnterpriseUtils {
public static EnterpriseConfigs getEnterpriseConfigs() throws AndroidDeviceMgtPluginException {
EnterpriseConfigs enterpriseConfigs = getEnterpriseConfigsFromGoogle();
if (enterpriseConfigs.getErrorResponse() != null) {
if (enterpriseConfigs.getErrorResponse().getCode() == 500l) {
if (enterpriseConfigs.getErrorResponse().getCode() == 500) {
throw new UnexpectedServerErrorException(enterpriseConfigs.getErrorResponse().getMessage());
} else if (enterpriseConfigs.getErrorResponse().getCode() == 500l) {
} else if (enterpriseConfigs.getErrorResponse().getCode() == 404) {
throw new NotFoundException(enterpriseConfigs.getErrorResponse().getMessage());
}
}
@ -263,25 +262,17 @@ public class AndroidEnterpriseUtils {
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 {
ApplicationManager applicationManager = getAppManagerServer();
ApplicationManager applicationManager = AndroidAPIUtils.getAppManagerService();
List<Category> categories = applicationManager.getRegisteredCategories();
if (productListResponse != null && productListResponse.getProduct() != null
&& !productListResponse.getProduct().isEmpty()) {
List<String> packageNamesOfApps = productListResponse.getProduct().stream()
.map(product -> (product.getProductId().replaceFirst("app:", ""))).collect(Collectors.toList());
List<String> packageNamesOfApps = new ArrayList<>();
for (Product product : productListResponse.getProduct()) {
packageNamesOfApps.add(product.getProductId().replaceFirst("app:", ""));
}
List<Application> existingApps = applicationManager.getApplications(packageNamesOfApps);
List<Product> products = productListResponse.getProduct();
@ -303,8 +294,7 @@ public class AndroidEnterpriseUtils {
publicAppReleaseWrapper.setDescription(product.getRecentChanges());
publicAppReleaseWrapper.setReleaseType("ga");
publicAppReleaseWrapper.setVersion(getAppString(product.getAppVersion()));
publicAppReleaseWrapper
.setSupportedOsVersions(String.valueOf(product.getMinAndroidSdkVersion()) + "-ALL");
publicAppReleaseWrapper.setSupportedOsVersions(product.getMinAndroidSdkVersion() + "-ALL");
ApplicationArtifact applicationArtifact = generateArtifacts(product);
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) {
ApplicationUpdateWrapper applicationUpdateWrapper = new ApplicationUpdateWrapper();
applicationUpdateWrapper.setName(product.getTitle());
@ -396,13 +379,6 @@ public class AndroidEnterpriseUtils {
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) {
PublicAppWrapper publicAppWrapper = new PublicAppWrapper();
publicAppWrapper.setName(product.getTitle());
@ -434,13 +410,6 @@ public class AndroidEnterpriseUtils {
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 {
ApplicationArtifact applicationArtifact = new ApplicationArtifact();
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.XmlRootElement;
@XmlRootElement(name = "iosDBConfigurations")
public class AndroidDataSourceConfigurations {
@XmlRootElement(name = "AndroidDBConfigurations")
public class AndroidDBConfigurations {
private MobileDataSourceConfig iosDataSourceConfiguration;
private MobileDataSourceConfig DataSourceConfiguration;
@XmlElement(name = "DataSourceConfiguration")
public MobileDataSourceConfig getIosDataSourceConfiguration() {
return iosDataSourceConfiguration;
public MobileDataSourceConfig getDataSourceConfiguration() {
return DataSourceConfiguration;
}
public void setIosDataSourceConfiguration(MobileDataSourceConfig iosDataSourceConfiguration) {
this.iosDataSourceConfiguration = iosDataSourceConfiguration;
public void setDataSourceConfiguration(MobileDataSourceConfig DataSourceConfiguration) {
this.DataSourceConfiguration = DataSourceConfiguration;
}
}

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

@ -18,9 +18,16 @@
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.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.AndroidService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.registry.core.service.RegistryService;
/**
@ -30,6 +37,13 @@ public class AndroidDeviceManagementDataHolder {
private RegistryService registryService;
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 DeviceTypeCommonService deviceTypeCommonService;
@ -75,4 +89,60 @@ public class AndroidDeviceManagementDataHolder {
public void setDeviceTypeCommonService(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.osgi.framework.BundleContext;
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.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.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.impl.AndroidGoogleEnterpriseServiceImpl;
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.util.MobileDeviceManagementUtil;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.registry.core.service.RegistryService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.mobile.android.impl.internal.AndroidPluginServiceComponent"
* immediate="true"
* @scr.component name="org.wso2.carbon.device.mgt.mobile.android" 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"
* interface="org.wso2.carbon.ndatasource.core.DataSourceService"
* cardinality="1..1"
@ -43,43 +74,41 @@ import org.wso2.carbon.registry.core.service.RegistryService;
* bind="setDataSourceService"
* unbind="unsetDataSourceService"
* @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="0..1"
* policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
* <p>
* Adding reference to API Manager Configuration service is an unavoidable hack to get rid of NPEs thrown while
* initializing APIMgtDAOs attempting to register APIs programmatically. APIMgtDAO needs to be proper cleaned up
* to avoid as an ideal fix
* interface="org.wso2.carbon.registry.core.service.RegistryService"
* cardinality="0..1"
* policy="dynamic"
* bind="setRegistryService"
* unbind="unsetRegistryService"
*/
@SuppressWarnings("unused")
public class AndroidPluginServiceComponent {
private static final Log log = LogFactory.getLog(AndroidPluginServiceComponent.class);
protected void activate(ComponentContext ctx) {
protected void activate(ComponentContext componentContext) {
if (log.isDebugEnabled()) {
log.debug("Activating Android Mobile Device Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
BundleContext bundleContext = componentContext.getBundleContext();
MobileDeviceManagementUtil.initConfig();
AbstractMobileDeviceManagementDAOFactory.init("android", MobileDeviceManagementUtil
.getIosDataSourceConfigurations().getIosDataSourceConfiguration());
MobileDeviceConfigFactory.init();
AbstractMobileDeviceManagementDAOFactory.init("android", MobileDeviceConfigFactory
.getDataSourceConfigurations().getDataSourceConfiguration());
AndroidService androidService = new AndroidServiceImpl();
AndroidDeviceManagementDataHolder.getInstance().setAndroidService(
androidService);
bundleContext.registerService(AndroidService.class.getName(), androidService, null);
AndroidDeviceManagementDataHolder.getInstance().setAndroidService(androidService);
bundleContext.registerService(AndroidService.class, androidService, null);
DeviceTypeCommonService deviceTypeCommonService = new DeviceTypeCommonServiceImpl();
AndroidDeviceManagementDataHolder.getInstance().setDeviceTypeCommonService(
deviceTypeCommonService);
bundleContext.registerService(DeviceTypeCommonService.class.getName(), deviceTypeCommonService, null);
AndroidDeviceManagementDataHolder.getInstance().setDeviceTypeCommonService(deviceTypeCommonService);
bundleContext.registerService(DeviceTypeCommonService.class, deviceTypeCommonService, null);
AndroidGoogleEnterpriseService androidPluginService = new AndroidGoogleEnterpriseServiceImpl();
AndroidDeviceManagementDataHolder.getInstance().setAndroidDeviceManagementService(
androidPluginService);
bundleContext.registerService(AndroidGoogleEnterpriseService.class.getName(), androidPluginService, null);
AndroidDeviceManagementDataHolder.getInstance().setAndroidDeviceManagementService(androidPluginService);
bundleContext.registerService(AndroidGoogleEnterpriseService.class, androidPluginService, null);
if (log.isDebugEnabled()) {
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()) {
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) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources
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;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray;
import org.json.JSONObject;
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.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.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.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.mobile.android.common.AndroidPluginConstants;
import org.wso2.carbon.device.mgt.mobile.android.common.config.datasource.AndroidDataSourceConfigurations;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileDevice;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileDeviceOperationMapping;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileFeature;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileOperation;
import org.wso2.carbon.device.mgt.mobile.android.common.dto.MobileOperationProperty;
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.config.datasource.AndroidDBConfigurations;
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.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Provides utility methods required by the mobile device management bundle.
*/
public class MobileDeviceManagementUtil {
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 final Log log = LogFactory.getLog(MobileDeviceManagementUtil.class);
private static String getPropertyValue(Device device, String property) {
if (device != null && device.getProperties() != null) {
for (Device.Property prop : device.getProperties()) {
if (property.equals(prop.getName())) {
return prop.getValue();
}
}
}
return null;
}
public static Activity 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);
}
return AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers);
}
private static Device.Property getProperty(String property, String value) {
if (property != null) {
Device.Property prop = new Device.Property();
prop.setName(property);
prop.setValue(value);
return prop;
}
return null;
}
public static boolean isValidDeviceIdentifier(Device device) {
return !(device == null || device.getDeviceIdentifier() == null ||
device.getDeviceIdentifier().isEmpty() ||
device.getEnrolmentInfo() == null ||
EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus()));
}
public static MobileDevice convertToMobileDevice(Device device) {
MobileDevice mobileDevice = null;
if (device != null) {
mobileDevice = new MobileDevice();
mobileDevice.setMobileDeviceId(device.getDeviceIdentifier());
mobileDevice.setImei(getPropertyValue(device, MOBILE_DEVICE_IMEI));
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 List<? extends Operation> getPendingOperations
(Device device) throws OperationManagementException {
List<? extends Operation> operations;
operations = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.getPendingOperations(device);
return operations;
}
public static Device convertToDevice(MobileDevice mobileDevice) {
Device device = null;
if (mobileDevice != null) {
device = new Device();
List<Device.Property> propertyList = new ArrayList<Device.Property>();
propertyList.add(getProperty(MOBILE_DEVICE_IMEI, mobileDevice.getImei()));
propertyList.add(getProperty(MOBILE_DEVICE_IMSI, mobileDevice.getImsi()));
propertyList.add(getProperty(MOBILE_DEVICE_MODEL, mobileDevice.getModel()));
propertyList.add(getProperty(MOBILE_DEVICE_OS_VERSION, mobileDevice.getOsVersion()));
propertyList.add(getProperty(MOBILE_DEVICE_OS_BUILD_DATE, mobileDevice.getOsBuildDate()));
propertyList.add(getProperty(MOBILE_DEVICE_VENDOR, mobileDevice.getVendor()));
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()));
public static void updateOperation(Device device, Operation operation)
throws OperationManagementException, PolicyComplianceException,
org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(device.getDeviceIdentifier());
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());
}
if(mobileDevice.getLongitude() != null) {
propertyList.add(getProperty(MOBILE_DEVICE_LONGITUDE, mobileDevice.getLongitude()));
AndroidDeviceManagementDataHolder.getInstance().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 '" + 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) {
MobileOperation mobileOperation = new MobileOperation();
MobileOperationProperty operationProperty;
List<MobileOperationProperty> properties = new LinkedList<MobileOperationProperty>();
mobileOperation.setFeatureCode(operation.getCode());
mobileOperation.setCreatedDate(new Date().getTime());
Properties operationProperties = operation.getProperties();
for (String key : operationProperties.stringPropertyNames()) {
operationProperty = new MobileOperationProperty();
operationProperty.setProperty(key);
operationProperty.setValue(operationProperties.getProperty(key));
properties.add(operationProperty);
}
mobileOperation.setProperties(properties);
return mobileOperation;
}
} 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(device, 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);
}
}
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) {
Operation operation = new Operation();
Properties properties = new Properties();
operation.setCode(mobileOperation.getFeatureCode());
for (MobileOperationProperty mobileOperationProperty : mobileOperation.getProperties()) {
properties
.put(mobileOperationProperty.getProperty(), mobileOperationProperty.getValue());
}
operation.setProperties(properties);
return operation;
}
private static void updateApplicationList(Operation operation, Device device)
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);
}
AndroidDeviceManagementDataHolder.getInstance().getApplicationManagementProviderService()
.updateApplicationListInstalledInDevice(device, applications);
} else {
if (log.isDebugEnabled()) {
log.debug("Operation Response is null.");
}
}
}
public static MobileFeature convertToMobileFeature(Feature feature) {
MobileFeature mobileFeature = new MobileFeature();
mobileFeature.setName(feature.getName());
mobileFeature.setCode(feature.getCode());
mobileFeature.setDescription(feature.getDescription());
mobileFeature.setDeviceType(feature.getDeviceType());
mobileFeature.setType(feature.getType());
mobileFeature.setHidden(feature.isHidden());
return mobileFeature;
}
private static void updateDeviceLocation(Device device, DeviceLocation deviceLocation)
throws DeviceDetailsMgtException {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceInformationManager informationManager =
(DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null);
public static Feature convertToFeature(MobileFeature mobileFeature) {
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;
}
informationManager.addDeviceLocation(device, deviceLocation);
}
public static Registry getConfigurationRegistry() throws AndroidDeviceMgtPluginException {
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
return AndroidDeviceManagementDataHolder.getInstance().getRegistryService()
.getConfigSystemRegistry(
tenantId);
} catch (RegistryException e) {
throw new AndroidDeviceMgtPluginException(
"Error in retrieving conf registry instance: " +
e.getMessage(), e);
}
}
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 = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService()
.getDevice(deviceIdentifier);
applicationManager.updateSubsStatus(device.getId(), operationId, status);
}
public static Resource getRegistryResource(String path) throws AndroidDeviceMgtPluginException {
try {
if(MobileDeviceManagementUtil.getConfigurationRegistry().resourceExists(path)){
return MobileDeviceManagementUtil.getConfigurationRegistry().get(path);
}
private static void updateDeviceInfo(Device device, DeviceInfo deviceInfo)
throws DeviceDetailsMgtException {
DeviceInformationManager informationManager = AndroidDeviceManagementDataHolder.getInstance()
.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;
} 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,
Resource resource)
throws AndroidDeviceMgtPluginException {
boolean status;
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);
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId());
}
return status;
return ids;
}
public static String getResourcePath(String resourceName, String platform) {
String regPath = "";
switch (platform) {
case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID:
regPath = AndroidPluginConstants.MobilePluginConstants
.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;
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 regPath;
return deviceStatuses;
}
public static String getPlatformConfigPath(String platform) {
String regPath = "";
switch (platform) {
case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID:
regPath = DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID;
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;
private static DeviceState createDeviceStatusData(Record record) {
DeviceState deviceState = new DeviceState();
deviceState.setId(record.getId());
deviceState.setValues(record.getValues());
return deviceState;
}
public static boolean createRegistryCollection(String path)
throws AndroidDeviceMgtPluginException {
try {
if (! MobileDeviceManagementUtil.getConfigurationRegistry().resourceExists(path)) {
Resource resource = MobileDeviceManagementUtil.getConfigurationRegistry().newCollection();
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);
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 List<Feature> getMissingFeatures(List<Feature> supportedFeatures, List<Feature> existingFeatures) {
HashMap<String,Feature> featureHashMap = new HashMap();
for (Feature feature: existingFeatures) {
featureHashMap.put(feature.getCode(),feature);
}
List<Feature> missingFeatures = new ArrayList<Feature>();
for (Feature supportedFeature : supportedFeatures) {
if (featureHashMap.get(supportedFeature.getCode()) != null) {
continue;
}
missingFeatures.add(supportedFeature);
}
return missingFeatures;
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 final String IOS_DB_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator +
"/android-dbconfig.xml";
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");
}
public static AndroidDataSourceConfigurations iosDataSourceConfigurations;
public static AndroidDataSourceConfigurations getIosDataSourceConfigurations() {
return iosDataSourceConfigurations;
}
JsonArray jsonArray = jsonElement.getAsJsonArray();
Gson gson = new Gson();
ComplianceFeature complianceFeature;
List<ComplianceFeature> complianceFeatures = new ArrayList<ComplianceFeature>(jsonArray.size());
public static synchronized void initConfig() throws DeviceManagementException {
try {
File mobileDeviceMgtConfig = new File(IOS_DB_CONFIG_PATH);
Document doc = convertToDocuments(mobileDeviceMgtConfig);
JAXBContext iosDeviceMgtContext = JAXBContext.newInstance(AndroidDataSourceConfigurations.class);
Unmarshaller unmarshaller = iosDeviceMgtContext.createUnmarshaller();
iosDataSourceConfigurations = (AndroidDataSourceConfigurations) unmarshaller.unmarshal(doc);
} catch (Exception e) {
throw new DeviceManagementException(
"Error occurred while initializing Mobile Device Management config", e);
}
}
for (JsonElement element : jsonArray) {
complianceFeature = gson.fromJson(element, ComplianceFeature.class);
complianceFeatures.add(complianceFeature);
}
return complianceFeatures;
}
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.annotations.BeforeClass;
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.OperationManagementException;
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.internal.AndroidDeviceManagementDataHolder;
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.util.AndroidAPIUtils;
@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"})
@PrepareForTest(AndroidAPIUtils.class)
@PrepareForTest(AndroidDeviceManagementDataHolder.class)
public class DeviceManagementAdminServiceTests {
private AndroidServiceImpl androidService;
@ -56,7 +54,7 @@ public class DeviceManagementAdminServiceTests {
}
private void mockDeviceManagementService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceManagementService"))
PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceManagementProviderService"))
.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.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.exception.AndroidDeviceMgtPluginException;
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.DeviceInformationManagerServiceMock;
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.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.util.AndroidDeviceUtils;
import org.wso2.carbon.device.mgt.mobile.android.core.util.MobileDeviceManagementUtil;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"})
@PrepareForTest(AndroidAPIUtils.class)
@PrepareForTest({AndroidDeviceManagementDataHolder.class, MobileDeviceManagementUtil.class})
public class DeviceManagementServiceTests {
private AndroidServiceImpl androidService;
@ -69,32 +68,32 @@ public class DeviceManagementServiceTests {
}
private void mockDeviceManagementService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceManagementService"))
PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceManagementProviderService"))
.toReturn(new DeviceManagementProviderServiceMock());
}
private void mockApplicationManagerService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getApplicationManagerService"))
PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getApplicationManagementProviderService"))
.toReturn(new ApplicationManagementProviderServiceMock());
}
private void mockPolicyManagerService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getPolicyManagerService"))
PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getPolicyManagerService"))
.toReturn(new PolicyManagerServiceMock());
}
private void mockDeviceInformationManagerService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceInformationManagerService"))
PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceInformationManager"))
.toReturn(new DeviceInformationManagerServiceMock());
}
private void mockNotificationManagementService() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getNotificationManagementService"))
PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getNotificationManagementService"))
.toReturn(new NotificationManagementServiceMock());
}
private void mockUser() {
PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getAuthenticatedUser"))
PowerMockito.stub(PowerMockito.method(MobileDeviceManagementUtil.class, "getAuthenticatedUser"))
.toReturn("admin");
}
@ -110,25 +109,25 @@ public class DeviceManagementServiceTests {
@Test (expectedExceptions = {InvalidDeviceException.class})
public void testGetPendingOperationsForNullDevice()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
throws DeviceManagementException, InvalidDeviceException {
List<? extends Operation> resultOperations = new ArrayList<>();
androidService.getPendingOperations(null, resultOperations);
}
@Test (expectedExceptions = {InvalidDeviceException.class})
public void testGetPendingOperationsForInvalidDevice()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService();
List<? extends Operation> resultOperations = new ArrayList<>();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject("1234");
DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject("1234");
androidService.getPendingOperations(deviceIdentifier, resultOperations);
}
@Test
public void testGetPendingOperationsNullResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, null);
Assert.assertNotNull(pendingOperations);
@ -137,10 +136,10 @@ public class DeviceManagementServiceTests {
@Test
public void testGetPendingOperationsWithMonitorResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService();
mockPolicyManagerService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getSuccessMonitorOperationResponse());
Assert.assertNotNull(pendingOperations);
@ -149,10 +148,10 @@ public class DeviceManagementServiceTests {
@Test
public void testGetPendingOperationsWithApplicationResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService();
mockApplicationManagerService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getSuccessApplicationOperationResponse());
Assert.assertNotNull(pendingOperations);
@ -161,10 +160,10 @@ public class DeviceManagementServiceTests {
@Test
public void testGetPendingOperationsWithDeviceInfoResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService();
mockDeviceInformationManagerService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getSuccessInfoOperationResponse());
Assert.assertNotNull(pendingOperations);
@ -173,9 +172,9 @@ public class DeviceManagementServiceTests {
@Test
public void testGetPendingOperationsWithInProgressResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getInProgressOperationResponse());
Assert.assertNotNull(pendingOperations);
@ -184,10 +183,10 @@ public class DeviceManagementServiceTests {
@Test
public void testGetPendingOperationsWithErrorResponse()
throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException {
throws DeviceManagementException, InvalidDeviceException {
mockDeviceManagementService();
mockNotificationManagementService();
DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId());
List<? extends Operation> pendingOperations = androidService
.getPendingOperations(deviceIdentifier, TestUtils.getErrorOperationResponse());
Assert.assertNotNull(pendingOperations);
@ -196,7 +195,7 @@ public class DeviceManagementServiceTests {
@Test
public void testEnrollDeviceWithoutLocationSuccess()
throws DeviceManagementException, AndroidDeviceMgtPluginException {
throws DeviceManagementException {
mockDeviceManagementService();
mockPolicyManagerService();
mockUser();
@ -206,8 +205,7 @@ public class DeviceManagementServiceTests {
}
@Test
public void testEnrollDeviceWithLocationSuccess()
throws DeviceManagementException, AndroidDeviceMgtPluginException {
public void testEnrollDeviceWithLocationSuccess() throws DeviceManagementException {
mockDeviceManagementService();
mockDeviceInformationManagerService();
mockPolicyManagerService();
@ -247,8 +245,7 @@ public class DeviceManagementServiceTests {
}
@Test
public void testEnrollDeviceUnSuccess()
throws DeviceManagementException, AndroidDeviceMgtPluginException {
public void testEnrollDeviceUnSuccess() throws DeviceManagementException {
mockDeviceManagementService();
mockUser();
AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice();
@ -259,8 +256,7 @@ public class DeviceManagementServiceTests {
}
@Test
public void testIsEnrolledExists()
throws DeviceManagementException {
public void testIsEnrolledExists() throws DeviceManagementException {
mockDeviceManagementService();
Message message = androidService.isEnrolled(TestUtils.getDeviceId(), null);
Assert.assertNotNull(message);
@ -268,8 +264,7 @@ public class DeviceManagementServiceTests {
}
@Test
public void testIsEnrolledNonExist()
throws DeviceManagementException {
public void testIsEnrolledNonExist() throws DeviceManagementException {
mockDeviceManagementService();
Message message = androidService.isEnrolled("1234", null);
Assert.assertNotNull(message);
@ -277,8 +272,7 @@ public class DeviceManagementServiceTests {
}
@Test
public void testIsEnrolledNull()
throws DeviceManagementException {
public void testIsEnrolledNull() throws DeviceManagementException {
mockDeviceManagementService();
Message response = androidService.isEnrolled(null, null);
Assert.assertNotNull(response);
@ -286,8 +280,7 @@ public class DeviceManagementServiceTests {
}
@Test
public void testModifyEnrollmentSuccess()
throws DeviceManagementException, AndroidDeviceMgtPluginException {
public void testModifyEnrollmentSuccess() throws DeviceManagementException {
mockDeviceManagementService();
mockUser();
boolean status = androidService.modifyEnrollment(TestUtils.getDeviceId(), TestUtils.getBasicAndroidDevice());
@ -295,28 +288,24 @@ public class DeviceManagementServiceTests {
}
@Test
public void testModifyEnrollmentUnSuccess()
throws DeviceManagementException, AndroidDeviceMgtPluginException {
public void testModifyEnrollmentUnSuccess() throws DeviceManagementException {
mockDeviceManagementService();
mockUser();
AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice();
androidDevice.setDeviceIdentifier("1234");
boolean status = androidService
.modifyEnrollment(TestUtils.getDeviceId(), androidDevice);
boolean status = androidService.modifyEnrollment(TestUtils.getDeviceId(), androidDevice);
Assert.assertFalse(status);
}
@Test
public void testDisEnrollDeviceSuccess()
throws DeviceManagementException {
public void testDisEnrollDeviceSuccess() throws DeviceManagementException {
mockDeviceManagementService();
boolean status = androidService.disEnrollDevice(TestUtils.getDeviceId());
Assert.assertTrue(status);
}
@Test
public void testDisEnrollUnSuccess()
throws DeviceManagementException {
public void testDisEnrollUnSuccess() throws DeviceManagementException {
mockDeviceManagementService();
boolean status = androidService.disEnrollDevice("1234");
Assert.assertFalse(status);

@ -18,6 +18,7 @@
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.app.mgt.Application;
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
public List<Application> getApplicationListForDevice(DeviceIdentifier deviceIdentifier)
throws ApplicationManagementException {
return null;
}
@Override
public List<Application> getApplicationListForDevice(Device device) throws ApplicationManagementException {
return null;
}
@Override
public Application[] getApplications(String s, int i, int i1) throws ApplicationManagementException {
return new Application[0];

@ -1,5 +1,6 @@
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.device.details.DeviceInfo;
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;
public class DeviceInformationManagerServiceMock implements DeviceInformationManager {
@Override
public void addDeviceInfo(DeviceIdentifier deviceIdentifier, DeviceInfo deviceInfo)
throws DeviceDetailsMgtException {
}
@Override
public void addDeviceInfo(Device device, DeviceInfo deviceInfo) throws DeviceDetailsMgtException {
}
@Override
public DeviceInfo getDeviceInfo(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException {
return null;
@ -30,6 +37,11 @@ public class DeviceInformationManagerServiceMock implements DeviceInformationMan
}
@Override
public void addDeviceLocation(Device device, DeviceLocation deviceLocation) throws DeviceDetailsMgtException {
}
@Override
public DeviceLocation getDeviceLocation(DeviceIdentifier deviceIdentifier) throws DeviceDetailsMgtException {
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.DeviceConfiguration;
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.exceptions.DeviceManagementException;
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.InvalidDeviceException;
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.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
@ -482,6 +482,11 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv
return null;
}
@Override
public List<? extends Operation> getPendingOperations(Device device) throws OperationManagementException {
return null;
}
@Override
public Operation getNextPendingOperation(DeviceIdentifier deviceIdentifier) throws OperationManagementException {
return null;
@ -499,6 +504,11 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv
}
@Override
public void updateOperation(Device device, Operation operation) throws OperationManagementException {
}
@Override
public boolean updateProperties(DeviceIdentifier deviceIdentifier, List<Device.Property> list) throws DeviceManagementException {
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.WifiBeanWrapper;
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.List;
@ -381,7 +381,7 @@ public class TestUtils {
location.setCountry("Sri Lanka");
location.setLatitude(6.9);
location.setLongitude(79.5);
location.setDeviceIdentifier(AndroidDeviceUtils.convertToDeviceIdentifierObject(getDeviceId()));
location.setDeviceIdentifier(MobileDeviceManagementUtil.convertToDeviceIdentifierObject(getDeviceId()));
return location;
}

@ -160,7 +160,7 @@ function onRequest(context) {
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"]) {
viewModel["location"] = {};
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
~ * in compliance with the License.
~ * You may obtain a copy of the License at
@ -16,10 +16,10 @@
~ * specific language governing permissions and limitations
~ * under the License.
-->
<iosDBConfigurations>
<DataSourceConfiguration>
<JndiLookupDefinition>
<Name>jdbc/MobileAndroidDM_DS</Name>
</JndiLookupDefinition>
</DataSourceConfiguration>
</iosDBConfigurations>
<AndroidDBConfigurations>
<DataSourceConfiguration>
<JndiLookupDefinition>
<Name>jdbc/MobileAndroidDM_DS</Name>
</JndiLookupDefinition>
</DataSourceConfiguration>
</AndroidDBConfigurations>

Loading…
Cancel
Save