Merge branch 'application-mgt-new' into 'master'

Add new entgra app manager components and remove wso2 app manager integration.

See merge request entgra/carbon-device-mgt-plugins!103
revert-dabc3590
Milan Perera 5 years ago
commit b54e158735

@ -26,6 +26,7 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;

@ -10,7 +10,6 @@ import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;

@ -18,7 +18,6 @@
package org.wso2.carbon.device.mgt.iot.arduino.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
@ -30,6 +29,8 @@ import org.wso2.carbon.apimgt.application.extension.exception.APIManagerExceptio
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
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.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
@ -46,7 +47,6 @@ import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;

@ -25,7 +25,7 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.constants.ArduinoConstants;
import javax.ws.rs.HttpMethod;

@ -18,29 +18,23 @@
package org.wso2.carbon.device.mgt.iot.arduino.service.impl.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

@ -18,7 +18,6 @@
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
@ -30,6 +29,8 @@ import org.wso2.carbon.apimgt.application.extension.exception.APIManagerExceptio
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
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.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
@ -46,7 +47,6 @@ import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.*;

@ -25,10 +25,10 @@ import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.BufferedOutputStream;

@ -18,7 +18,6 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
@ -30,10 +29,10 @@ import org.wso2.carbon.apimgt.application.extension.exception.APIManagerExceptio
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
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.group.mgt.DeviceGroupConstants;
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.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord;
@ -53,7 +52,6 @@ import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@ -25,10 +25,10 @@ import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp.XmppConfig;
import org.wso2.carbon.utils.CarbonUtils;

@ -1,175 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>appm-connector</artifactId>
<version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.appmgt.mdm.osgiconnector</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - App Manager WSO2 MDM OSGI Connector Component</name>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Private-Package>org.wso2.carbon.appmgt.mdm.osgiconnector.internal</Private-Package>
<Import-Package>
org.wso2.carbon.device.mgt.core.*,
org.wso2.carbon.appmgt.mobile.utils.*,
org.wso2.carbon.appmgt.mobile.mdm.*,
org.wso2.carbon.appmgt.mobile.interfaces.*,
*;resolution:=optional
</Import-Package>
<Export-Package>
!org.wso2.carbon.appmgt.mdm.osgiconnector.internal,
org.wso2.carbon.appmgt.mdm.osgiconnector.*
</Export-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.appmgt</groupId>
<artifactId>org.wso2.carbon.appmgt.mobile</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.policy.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-impl</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-io.wso2</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.plist</groupId>
<artifactId>dd-plist</artifactId>
</dependency>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.scr</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
</project>

@ -1,463 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.appmgt.impl.service.ServiceReferenceHolder;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.MobileApp;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.MobileAppTypes;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.util.AndroidApplicationOperationUtil;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.util.IOSApplicationOperationUtil;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.util.MDMAppConstants;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.util.MDMServiceAPIUtils;
import org.wso2.carbon.appmgt.mobile.beans.ApplicationOperationAction;
import org.wso2.carbon.appmgt.mobile.beans.ApplicationOperationDevice;
import org.wso2.carbon.appmgt.mobile.interfaces.ApplicationOperations;
import org.wso2.carbon.appmgt.mobile.mdm.App;
import org.wso2.carbon.appmgt.mobile.mdm.Device;
import org.wso2.carbon.appmgt.mobile.store.Generic;
import org.wso2.carbon.appmgt.mobile.utils.MobileApplicationException;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Platform;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.appmgt.mobile.utils.User;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.session.UserRegistry;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class ApplicationOperationsImpl implements ApplicationOperations {
private static final Log log = LogFactory.getLog(ApplicationOperationsImpl.class);
private static final String MEDIA_TYPE_XML = "application/xml";
private static final String INSTALL = "install";
private static final String UNINSTALL = "uninstall";
/**
* @param applicationOperationAction holds the information needs to perform an action on mdm.
* @throws MobileApplicationException If error occurred while performing the action.
*/
public String performAction(ApplicationOperationAction applicationOperationAction)
throws MobileApplicationException {
if (log.isDebugEnabled()) {
log.debug(applicationOperationAction.getAction() + " action is triggered for " +
applicationOperationAction.getType() + ".");
}
Operation operation = null;
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
List<org.wso2.carbon.device.mgt.common.Device> deviceList;
if (MDMAppConstants.USER.equals(applicationOperationAction.getType())) {
String userName = null;
try {
for (String param : applicationOperationAction.getParams()) {
userName = param;
deviceList = MDMServiceAPIUtils
.getDeviceManagementService(applicationOperationAction.getTenantId()).
getDevicesOfUser(userName);
for (org.wso2.carbon.device.mgt.common.Device device : deviceList) {
if (MDMAppConstants.WEBAPP.equals(applicationOperationAction.getApp().getPlatform()) ||
applicationOperationAction.getApp().getPlatform().equalsIgnoreCase(device.getType())) {
if (MDMAppConstants.ACTIVE.equalsIgnoreCase(device.getEnrolmentInfo().
getStatus().toString())) {
deviceIdentifiers.add(getDeviceIdentifierByDevice(device));
}
}
}
}
} catch (DeviceManagementException devEx) {
String errorMsg = "Error occurred fetch device for user " + userName + " at app installation";
logError(errorMsg, devEx);
throw new MobileApplicationException(errorMsg, devEx);
}
} else if (MDMAppConstants.ROLE.equals(applicationOperationAction.getType())) {
String userRole = null;
try {
for (String param : applicationOperationAction.getParams()) {
userRole = param;
deviceList = MDMServiceAPIUtils
.getDeviceManagementService(applicationOperationAction.getTenantId()).
getAllDevicesOfRole(userRole);
for (org.wso2.carbon.device.mgt.common.Device device : deviceList) {
if (MDMAppConstants.WEBAPP.equals(applicationOperationAction.getApp().getPlatform())
|| applicationOperationAction.getApp().getPlatform()
.equalsIgnoreCase(device.getType())) {
if (MDMAppConstants.ACTIVE
.equalsIgnoreCase(device.getEnrolmentInfo().getStatus().toString())) {
deviceIdentifiers.add(getDeviceIdentifierByDevice(device));
}
}
}
}
} catch (DeviceManagementException devMgtEx) {
String errorMsg = "Error occurred fetch device for user role " + userRole + " at app installation";
logError(errorMsg, devMgtEx);
throw new MobileApplicationException(errorMsg, devMgtEx);
}
} else if (MDMAppConstants.DEVICE.equals(applicationOperationAction.getType())) {
DeviceIdentifier deviceIdentifier;
for (String param : applicationOperationAction.getParams()) {
deviceIdentifier = new DeviceIdentifier();
if (isValidJSON(param)) {
JSONParser parser = new JSONParser();
try {
JSONObject parsedObj = (JSONObject) parser.parse(param);
deviceIdentifier.setId((String) parsedObj.get(MDMAppConstants.ID));
deviceIdentifier.setType((String) parsedObj.get(MDMAppConstants.TYPE));
deviceIdentifiers.add(deviceIdentifier);
} catch (ParseException e) {
logError("Device Identifier is not valid json object.", e);
throw new MobileApplicationException(e);
}
}
}
} else {
throw new IllegalStateException("invalid type is received from app store.");
}
App app = applicationOperationAction.getApp();
MobileApp mobileApp = new MobileApp();
mobileApp.setId(app.getId());
mobileApp.setType(MobileAppTypes.valueOf(app.getType().toUpperCase()));
mobileApp.setAppIdentifier(app.getAppIdentifier());
mobileApp.setIconImage(app.getIconImage());
mobileApp.setIdentifier(app.getIdentifier());
mobileApp.setLocation(app.getLocation());
mobileApp.setName(app.getName());
mobileApp.setPackageName(app.getPackageName());
mobileApp.setPlatform(app.getPlatform());
mobileApp.setVersion(app.getVersion());
Properties properties = new Properties();
if (MDMAppConstants.IOS.equals(app.getPlatform())) {
if (MDMAppConstants.ENTERPRISE.equals(app.getType())) {
properties.put(MDMAppConstants.IOSConstants.IS_REMOVE_APP, true);
properties.put(MDMAppConstants.IOSConstants.IS_PREVENT_BACKUP, true);
} else if (MDMAppConstants.IOSConstants.PUBLIC.equals(app.getType())) {
properties.put(MDMAppConstants.IOSConstants.I_TUNES_ID, app.getIdentifier());
properties.put(MDMAppConstants.IOSConstants.IS_REMOVE_APP, true);
properties.put(MDMAppConstants.IOSConstants.IS_PREVENT_BACKUP, true);
} else if (MDMAppConstants.WEBAPP.equals(app.getType())) {
properties.put(MDMAppConstants.IOSConstants.LABEL, app.getName());
properties.put(MDMAppConstants.IOSConstants.IS_REMOVE_APP, true);
}
} else if (MDMAppConstants.WEBAPP.equals(app.getPlatform())) {
properties.put(MDMAppConstants.IOSConstants.LABEL, app.getName());
properties.put(MDMAppConstants.IOSConstants.IS_REMOVE_APP, true);
}
mobileApp.setProperties(properties);
Activity activity = null;
try {
if (deviceIdentifiers.size() > 0) {
if (deviceIdentifiers.get(0).getType().equalsIgnoreCase(Platform.ANDROID.toString())) {
if (MDMAppConstants.INSTALL.equals(applicationOperationAction.getAction())) {
operation = AndroidApplicationOperationUtil
.createInstallAppOperation(mobileApp, applicationOperationAction.getSchedule());
} else if (MDMAppConstants.UPDATE.equals(applicationOperationAction.getAction())) {
operation = AndroidApplicationOperationUtil
.createUpdateAppOperation(mobileApp, applicationOperationAction.getSchedule());
} else {
operation = AndroidApplicationOperationUtil
.createAppUninstallOperation(mobileApp, applicationOperationAction.getSchedule());
}
} else if (deviceIdentifiers.get(0).getType().equalsIgnoreCase(Platform.IOS.toString())) {
if (MDMAppConstants.INSTALL.equals(applicationOperationAction.getAction())) {
operation =
IOSApplicationOperationUtil.createInstallAppOperation(mobileApp);
} else {
if (MDMAppConstants.WEBAPP.equals(app.getPlatform())) {
operation = IOSApplicationOperationUtil.createWebClipUninstallOperation(mobileApp);
} else {
operation = IOSApplicationOperationUtil.createAppUninstallOperation(mobileApp);
}
}
}
activity = MDMServiceAPIUtils.getAppManagementService(applicationOperationAction.getTenantId())
.installApplicationForDevices(operation, deviceIdentifiers);
}
if (activity != null) {
return activity.getActivityId();
}
return null;
} catch (DeviceApplicationException mdmExce) {
logError("Error in creating operation object using app.", mdmExce);
throw new MobileApplicationException(mdmExce.getMessage());
} catch (ApplicationManagementException appMgtExce) {
logError("Error in app installation.", appMgtExce);
throw new MobileApplicationException(appMgtExce.getErrorMessage());
}
}
/**
* Create a new device identifier from Device object.
*
* @param device device which is to be retrieved type and id
* @return created device identifier
*/
private static DeviceIdentifier getDeviceIdentifierByDevice(org.wso2.carbon.device.mgt.common.Device device) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(device.getDeviceIdentifier());
deviceIdentifier.setType(device.getType());
return deviceIdentifier;
}
/**
* @param applicationOperationDevice holds the information needs to retrieve device list.
* @return List of devices
* @throws MobileApplicationException If an error occurred in getting devices or if app platform is not supported.
*/
public List<Device> getDevices(ApplicationOperationDevice applicationOperationDevice)
throws MobileApplicationException {
List<Device> devices;
List<org.wso2.carbon.device.mgt.common.Device> deviceList;
try {
final int tenantId = applicationOperationDevice.getTenantId();
final String username = applicationOperationDevice.getCurrentUser().getUsername();
final String platform = applicationOperationDevice.getPlatform();
DeviceAccessAuthorizationService deviceAccessAuthorizationService = MDMServiceAPIUtils
.getDeviceAccessAuthorizationService(applicationOperationDevice.getTenantId());
DeviceManagementProviderService deviceManagementService = MDMServiceAPIUtils
.getDeviceManagementService(tenantId);
boolean isAdmin = deviceAccessAuthorizationService.isDeviceAdminUser();
switch (platform) {
case MDMAppConstants.WEBAPP:
deviceList = isAdmin ? deviceManagementService.getAllDevices() :
deviceManagementService.getDevicesOfUser(username);
break;
case MDMAppConstants.ANDROID:
deviceList = isAdmin ? deviceManagementService.getAllDevices(MDMAppConstants.ANDROID) :
deviceManagementService.getDevicesOfUser(username, MDMAppConstants.ANDROID);
break;
case MDMAppConstants.IOS:
deviceList = isAdmin ? deviceManagementService.getAllDevices(MDMAppConstants.IOS) :
deviceManagementService.getDevicesOfUser(username, MDMAppConstants.IOS);
break;
default:
throw new MobileApplicationException("App platform: [" + platform + "] is not supported.");
}
devices = new ArrayList<>(deviceList.size());
if (log.isDebugEnabled()) {
log.debug("device list got from mdm " + deviceList.toString());
}
for (org.wso2.carbon.device.mgt.common.Device commonDevice : deviceList) {
if (MDMAppConstants.ACTIVE
.equals(commonDevice.getEnrolmentInfo().getStatus().toString().
toLowerCase())) {
Device device = new Device();
org.wso2.carbon.appmgt.mobile.beans.DeviceIdentifier deviceIdentifier =
new org.wso2.carbon.appmgt.mobile.beans.DeviceIdentifier();
deviceIdentifier.setId(commonDevice.getDeviceIdentifier());
deviceIdentifier.setType(commonDevice.getType());
device.setDeviceIdentifier(deviceIdentifier);
device.setName(commonDevice.getName());
device.setModel(commonDevice.getName());
device.setType(MDMAppConstants.MOBILE_DEVICE);
String imgUrl;
if (MDMAppConstants.ANDROID.equalsIgnoreCase(commonDevice.getType())) {
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.NEXUS);
} else if (MDMAppConstants.IOS.equalsIgnoreCase(commonDevice.getType())) {
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.IPHONE);
} else {
imgUrl = String.format(applicationOperationDevice.getConfigParams()
.get(MDMAppConstants.IMAGE_URL),
MDMAppConstants.NONE);
}
device.setImage(imgUrl);
device.setPlatform(commonDevice.getType());
devices.add(device);
}
}
} catch (DeviceManagementException e) {
logError("Error While retrieving Device List.", e);
throw new MobileApplicationException(e.getMessage());
} catch (DeviceAccessAuthorizationException e) {
throw new MobileApplicationException("Error while checking user permissions", e);
}
return devices;
}
private boolean isValidJSON(String json) {
JSONParser parser = new JSONParser();
try {
parser.parse(json);
} catch (ParseException e) {
return false;
}
return true;
}
private void logError(String errorMessage, Throwable e) {
if (log.isDebugEnabled()) {
log.error(errorMessage, e);
} else {
log.error(errorMessage);
}
}
private static UserStoreManager getUserStoreManager() throws UserStoreException {
RealmService realmService;
UserStoreManager userStoreManager;
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);
}
int tenantId = ctx.getTenantId();
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
return userStoreManager;
}
class ApplicationSubscription extends Thread {
User currentUser;
String action;
App app;
int tenantId;
String type;
String[] params;
UserStoreManager userStoreManager;
UserRegistry userRegistry;
public ApplicationSubscription(User currentUser, String action, App app, int tenantId, final String type,
final String[] params) {
this.currentUser = currentUser;
this.action = action;
this.app = app;
this.tenantId = tenantId;
this.type = type;
this.params = params;
}
@Override
public void run() {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
privilegedCarbonContext.setTenantId(tenantId);
RealmService realmService = (RealmService) privilegedCarbonContext.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "RealmService is not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
String tenantDomain;
try {
tenantDomain = realmService.getTenantManager().getDomain(tenantId);
privilegedCarbonContext.setTenantDomain(tenantDomain);
privilegedCarbonContext.setUsername(currentUser.getUsername());
userStoreManager = getUserStoreManager();
userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
.getGovernanceUserRegistry(currentUser.getUsername(), tenantId);
} catch (UserStoreException e) {
log.error("Error occured while fetching user store", e);
} catch (RegistryException e) {
log.error("Error occured while fetching registry instance", e);
}
String basePath = "/users/";
String subscriptionPath = "/subscriptions/mobileapp/";
String path;
if (type != null && type.equals("role")) {
for (String param : params) {
String[] users;
if (log.isDebugEnabled()) {
log.debug("role being added:" + param);
}
try {
users = userStoreManager.getUserListOfRole(param);
for (String user : users) {
path = basePath + user + subscriptionPath + app.getId();
updateSubscription(action, path, user, userRegistry);
}
} catch (UserStoreException e) {
log.error("Error occured while getting user list of role " + param, e);
}
}
} else if (type != null && type.equals("user")) {
for (String user : params) {
if (log.isDebugEnabled()) {
log.debug("user:" + user);
}
path = basePath + user + subscriptionPath + app.getId();
updateSubscription(action, path, user, userRegistry);
}
} else if (type != null && type.equals("device")) {
log.debug("device user:" + currentUser.getUsername());
path = basePath + currentUser.getUsername() + subscriptionPath + app.getId();
updateSubscription(action, path, currentUser.getUsername(), userRegistry);
}
log.info("registry subscription complete.");
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
private void updateSubscription(String action, String path, String username, UserRegistry userRegistry) {
if (log.isDebugEnabled()) {
log.debug("update subscribe user:" + username + " , action:" + action + " ,path:" + path);
}
if (action != null && action.equals(INSTALL)) {
try {
if (!userRegistry.resourceExists(path)) {
Resource resource = userRegistry.newResource();
resource.setMediaType(MEDIA_TYPE_XML);
userRegistry.put(path, resource);
Generic generic = new Generic();
generic.showAppVisibilityToUser(path, username, "ALLOW");
}
} catch (RegistryException e) {
log.error("Error occured while accessing registry.", e);
}
} else if (action != null && action.equals(UNINSTALL)) {
try {
if (userRegistry.resourceExists(path)) {
userRegistry.delete(path);
Generic generic = new Generic();
generic.showAppVisibilityToUser(path, username, "DENY");
}
} catch (RegistryException e) {
log.error("Error occured while accessing registry.", e);
}
}
}
}

@ -1,60 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.appmgt.mdm.osgiconnector.ApplicationOperationsImpl;
import org.wso2.carbon.appmgt.mobile.interfaces.ApplicationOperations;
/**
* @scr.component name="org.wso2.carbon.appmgt.mdm.osgiconnector" immediate="true"
*/
public class DeviceApplicationServiceComponent {
private static final Log log = LogFactory.getLog(DeviceApplicationServiceComponent.class);
private ServiceRegistration mdmServiceRegistration;
protected void activate(ComponentContext context) {
BundleContext bundleContext = context.getBundleContext();
mdmServiceRegistration = bundleContext
.registerService(ApplicationOperations.class.getName(), new ApplicationOperationsImpl(), null);
if (log.isDebugEnabled()) {
log.debug("Device Application Service Component activated.");
}
}
protected void deactivate(ComponentContext context) {
if (mdmServiceRegistration != null) {
mdmServiceRegistration.unregister();
mdmServiceRegistration = null;
}
if (log.isDebugEnabled()) {
log.debug("Device Application Service Component deactivated.");
}
}
}

@ -1,126 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans;
import java.util.Properties;
/**
* This class represents the generic mobile Application information
* which is used by AppM.
*/
public class MobileApp {
private String id;
private String name;
private MobileAppTypes type;
private String platform;
private String version;
private String identifier;
private String iconImage;
private String packageName;
private String appIdentifier;
private String location;
private Properties properties;
public MobileAppTypes getType() {
return type;
}
public void setType(MobileAppTypes type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getIconImage() {
return iconImage;
}
public void setIconImage(String iconImage) {
this.iconImage = iconImage;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppIdentifier() {
return appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}

@ -1,21 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans;
public enum MobileAppTypes {
ENTERPRISE, WEBAPP, PUBLIC
}

@ -1,46 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
public class AndroidApplication {
private String type;
private String appIdentifier;
public String getAppIdentifier() {
return appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toJSON() throws DeviceApplicationException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,28 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
import java.io.Serializable;
/**
* This class represents the Appstore Application information.
*/
public class AppStoreApplication extends AndroidApplication implements Serializable {
}

@ -1,55 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
import java.io.Serializable;
/**
* This class represents the Enterprise Application information.
*/
public class EnterpriseApplication extends AndroidApplication implements Serializable {
private String url;
private String schedule;
private String packageName;
public String getSchedule() {
return schedule;
}
public void setSchedule(String schedule) {
this.schedule = schedule;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
}

@ -1,61 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
import java.io.Serializable;
/**
* This class represents the Web Application information.
*/
public class WebApplication implements Serializable {
private String name;
private String url;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toJSON() throws DeviceApplicationException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,34 +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.
*/
package org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.ios;
import java.io.Serializable;
public class AppStoreApplication extends IOSApplication implements Serializable {
private int iTunesStoreID;
public int getiTunesStoreID() {
return iTunesStoreID;
}
public void setiTunesStoreID(int iTunesStoreID) {
this.iTunesStoreID = iTunesStoreID;
}
}

@ -1,35 +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.
*
*/
package org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.ios;
import java.io.Serializable;
public class EnterpriseApplication extends IOSApplication implements Serializable {
private String manifestURL;
public String getManifestURL() {
return manifestURL;
}
public void setManifestURL(String manifestURL) {
this.manifestURL = manifestURL;
}
}

@ -1,74 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
public class IOSApplication {
private String identifier;
private boolean removeAppUponMDMProfileRemoval;
private boolean preventBackupOfAppData;
private String bundleId;
private String UUID;
public String getUUID() {
return UUID;
}
public void setUUID(String UUID) {
this.UUID = UUID;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public boolean isRemoveAppUponMDMProfileRemoval() {
return removeAppUponMDMProfileRemoval;
}
public void setRemoveAppUponMDMProfileRemoval(boolean removeAppUponMDMProfileRemoval) {
this.removeAppUponMDMProfileRemoval = removeAppUponMDMProfileRemoval;
}
public boolean isPreventBackupOfAppData() {
return preventBackupOfAppData;
}
public void setPreventBackupOfAppData(boolean preventBackupOfAppData) {
this.preventBackupOfAppData = preventBackupOfAppData;
}
public String getBundleId() {
return bundleId;
}
public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
public String toJSON() throws DeviceApplicationException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,49 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
import java.io.Serializable;
public class RemoveApplication implements Serializable {
private String bundleId;
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getBundleId() {
return bundleId;
}
public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
public String toJSON() throws DeviceApplicationException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,75 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
public class WebClip {
private String URL;
private String label;
private String icon;
private String isRemovable;
private String UUID;
public String getUUID() {
return UUID;
}
public void setUUID(String UUID) {
this.UUID = UUID;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getIsRemovable() {
return isRemovable;
}
public void setIsRemovable(String isRemovable) {
this.isRemovable = isRemovable;
}
public String toJSON() throws DeviceApplicationException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,50 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.common;
public class DeviceApplicationException extends Exception {
private static final long serialVersionUID = 5136875495185597926L;
private String errorMessage;
public DeviceApplicationException(String msg, Exception e) {
super(msg, e);
setErrorMessage(msg);
}
public DeviceApplicationException(String msg, Throwable cause) {
super(msg, cause);
setErrorMessage(msg);
}
public DeviceApplicationException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DeviceApplicationException() {
super();
}
public DeviceApplicationException(Throwable cause) {
super(cause);
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -1,152 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.util;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.MobileApp;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.android.AppStoreApplication;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.android.EnterpriseApplication;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.android.WebApplication;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
/**
* This class contains the all the operations related to Android.
*/
public class AndroidApplicationOperationUtil {
/**
* Create Install Application operation.
*
* @param application MobileApp application
* @return operation
* @throws DeviceApplicationException
*/
public static Operation createInstallAppOperation(MobileApp application, String schedule) throws
DeviceApplicationException {
ProfileOperation operation = new ProfileOperation();
operation.setCode(MDMAppConstants.AndroidConstants.OPCODE_INSTALL_APPLICATION);
operation.setType(Operation.Type.PROFILE);
switch (application.getType()) {
case ENTERPRISE:
EnterpriseApplication enterpriseApplication = new EnterpriseApplication();
enterpriseApplication.setType(application.getType().toString());
enterpriseApplication.setUrl(application.getLocation());
enterpriseApplication.setSchedule(schedule);
enterpriseApplication.setPackageName(application.getPackageName());
operation.setPayLoad(enterpriseApplication.toJSON());
break;
case PUBLIC:
setOperationForPublicApp(operation, application);
break;
case WEBAPP:
setOperationForWebApp(operation, application);
break;
default:
String errorMessage = "Invalid application type.";
throw new DeviceApplicationException(errorMessage);
}
return operation;
}
/**
* Create Update Application operation.
*
* @param application MobileApp application
* @return operation
* @throws DeviceApplicationException
*/
public static Operation createUpdateAppOperation(MobileApp application, String schedule) throws
DeviceApplicationException {
ProfileOperation operation = new ProfileOperation();
operation.setCode(MDMAppConstants.AndroidConstants.OPCODE_UPDATE_APPLICATION);
operation.setType(Operation.Type.PROFILE);
switch (application.getType()) {
case ENTERPRISE:
EnterpriseApplication enterpriseApplication = new EnterpriseApplication();
enterpriseApplication.setType(application.getType().toString());
enterpriseApplication.setUrl(application.getLocation());
enterpriseApplication.setSchedule(schedule);
operation.setPayLoad(enterpriseApplication.toJSON());
break;
case PUBLIC:
setOperationForPublicApp(operation, application);
break;
case WEBAPP:
setOperationForWebApp(operation, application);
break;
default:
String errorMessage = "Invalid application type.";
throw new DeviceApplicationException(errorMessage);
}
return operation;
}
/**
* Create Uninstall Application operation.
*
* @param application MobileApp application
* @return operation
* @throws DeviceApplicationException
*/
public static Operation createAppUninstallOperation(MobileApp application, String schedule) throws
DeviceApplicationException {
ProfileOperation operation = new ProfileOperation();
operation.setCode(MDMAppConstants.AndroidConstants.OPCODE_UNINSTALL_APPLICATION);
operation.setType(Operation.Type.PROFILE);
switch (application.getType()) {
case ENTERPRISE:
EnterpriseApplication enterpriseApplication = new EnterpriseApplication();
enterpriseApplication.setType(application.getType().toString());
enterpriseApplication.setAppIdentifier(application.getIdentifier());
enterpriseApplication.setSchedule(schedule);
operation.setPayLoad(enterpriseApplication.toJSON());
break;
case PUBLIC:
setOperationForPublicApp(operation, application);
break;
case WEBAPP:
setOperationForWebApp(operation, application);
break;
default:
String errorMessage = "Invalid application type.";
throw new DeviceApplicationException(errorMessage);
}
return operation;
}
private static void setOperationForPublicApp(Operation operation, MobileApp application)
throws DeviceApplicationException {
AppStoreApplication appStoreApplication = new AppStoreApplication();
appStoreApplication.setType(application.getType().toString());
appStoreApplication.setAppIdentifier(application.getIdentifier());
operation.setPayLoad(appStoreApplication.toJSON());
}
private static void setOperationForWebApp(Operation operation, MobileApp application)
throws DeviceApplicationException {
WebApplication webApplication = new WebApplication();
webApplication.setUrl(application.getLocation());
webApplication.setName(application.getName());
webApplication.setType(application.getType().toString());
operation.setPayLoad(webApplication.toJSON());
}
}

@ -1,131 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.util;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.MobileApp;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.ios.AppStoreApplication;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.ios.WebClip;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.common.DeviceApplicationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.ios.EnterpriseApplication;
import org.wso2.carbon.appmgt.mdm.osgiconnector.mdmmgt.beans.ios.RemoveApplication;
import java.util.Properties;
/**
* This class contains the all the operations related to IOS.
*/
public class IOSApplicationOperationUtil {
/**
* Create Install Application operation.
*
* @param application MobileApp application
* @return operation
* @throws DeviceApplicationException
*/
public static Operation createInstallAppOperation(MobileApp application) throws
DeviceApplicationException {
ProfileOperation operation = new ProfileOperation();
switch (application.getType()) {
case ENTERPRISE:
EnterpriseApplication enterpriseApplication = new EnterpriseApplication();
enterpriseApplication.setBundleId(application.getId());
enterpriseApplication.setIdentifier(application.getIdentifier());
enterpriseApplication.setManifestURL(application.getLocation());
Properties properties = application.getProperties();
enterpriseApplication.setPreventBackupOfAppData(
(Boolean) properties.get(MDMAppConstants.IOSConstants.IS_PREVENT_BACKUP));
enterpriseApplication.setRemoveAppUponMDMProfileRemoval(
(Boolean) properties.get(MDMAppConstants.IOSConstants.IS_REMOVE_APP));
operation.setCode(
MDMAppConstants.IOSConstants.OPCODE_INSTALL_ENTERPRISE_APPLICATION);
operation.setPayLoad(enterpriseApplication.toJSON());
operation.setType(Operation.Type.COMMAND);
break;
case PUBLIC:
AppStoreApplication appStoreApplication = new AppStoreApplication();
appStoreApplication.setRemoveAppUponMDMProfileRemoval(
(Boolean) application.getProperties()
.get(MDMAppConstants.IOSConstants.IS_REMOVE_APP));
appStoreApplication.setIdentifier(application.getIdentifier());
appStoreApplication.setPreventBackupOfAppData((Boolean) application.getProperties().
get(MDMAppConstants.IOSConstants.IS_PREVENT_BACKUP));
appStoreApplication.setBundleId(application.getId());
appStoreApplication.setiTunesStoreID(Integer.parseInt((String)application.getProperties().
get(MDMAppConstants.IOSConstants.I_TUNES_ID)));
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_INSTALL_STORE_APPLICATION);
operation.setType(Operation.Type.COMMAND);
operation.setPayLoad(appStoreApplication.toJSON());
break;
case WEBAPP:
WebClip webClip = new WebClip();
webClip.setIcon(application.getIconImage());
webClip.setIsRemovable(application.getProperties().
getProperty(MDMAppConstants.IOSConstants.IS_REMOVE_APP));
webClip.setLabel(application.getProperties().
getProperty(MDMAppConstants.IOSConstants.LABEL));
webClip.setURL(application.getLocation());
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_INSTALL_WEB_APPLICATION);
operation.setType(Operation.Type.PROFILE);
operation.setPayLoad(webClip.toJSON());
break;
default:
String errorMessage = "Invalid application type.";
throw new DeviceApplicationException(errorMessage);
}
return operation;
}
/**
* Create uninstall operations.
*
* @param application
* @return Uninstall operation
* @throws DeviceApplicationException
*/
public static Operation createAppUninstallOperation(MobileApp application) throws
DeviceApplicationException {
ProfileOperation operation = new ProfileOperation();
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_REMOVE_APPLICATION);
operation.setType(Operation.Type.PROFILE);
RemoveApplication removeApplication = new RemoveApplication();
removeApplication.setBundleId(application.getPackageName());
operation.setPayLoad(removeApplication.toJSON());
return operation;
}
/**
* Create uninstall operations for webclip.
*
* @param application
* @return Uninstall operation
* @throws DeviceApplicationException
*/
public static Operation createWebClipUninstallOperation(MobileApp application) throws
DeviceApplicationException {
ProfileOperation operation = new ProfileOperation();
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_REMOVE_APPLICATION);
operation.setType(Operation.Type.PROFILE);
RemoveApplication removeApplication = new RemoveApplication();
removeApplication.setUrl(application.getIdentifier());
operation.setPayLoad(removeApplication.toJSON());
return operation;
}
}

@ -1,82 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.util;
/**
* This class holds all the constants used for IOS and Android.
*/
public class MDMAppConstants {
public static final String USER = "user";
public static final String ROLE = "role";
public static final String IOS = "ios";
public static final String ANDROID = "android";
public static final String WEBAPP = "webapp";
public static final String INSTALL = "install";
public static final String UPDATE = "update";
public static final String ACTIVE = "active";
public static final String ENTERPRISE = "enterprise";
public static final String DEVICE = "device";
public static final String MOBILE_DEVICE = "mobileDevice";
public static final String NEXUS = "nexus";
public static final String IPHONE = "iphone";
public static final String NONE = "none";
public static final String IMAGE_URL = "ImageURL";
public static final String TYPE = "type";
public static final String ID = "id";
public class IOSConstants {
private IOSConstants() {
throw new AssertionError();
}
public static final String IS_REMOVE_APP = "isRemoveApp";
public static final String IS_PREVENT_BACKUP = "isPreventBackup";
public static final String I_TUNES_ID = "iTunesId";
public static final String LABEL = "label";
public static final String PUBLIC = "public";
public static final String OPCODE_INSTALL_ENTERPRISE_APPLICATION =
"INSTALL_ENTERPRISE_APPLICATION";
public static final String OPCODE_INSTALL_STORE_APPLICATION = "INSTALL_STORE_APPLICATION";
public static final String OPCODE_INSTALL_WEB_APPLICATION = "WEB_CLIP";
public static final String OPCODE_REMOVE_APPLICATION = "REMOVE_APPLICATION";
}
public class AndroidConstants {
private AndroidConstants() {
throw new AssertionError();
}
public static final String OPCODE_INSTALL_APPLICATION = "INSTALL_APPLICATION";
public static final String OPCODE_UPDATE_APPLICATION = "UPDATE_APPLICATION";
public static final String OPCODE_UNINSTALL_APPLICATION = "UNINSTALL_APPLICATION";
}
public class RegistryConstants {
private RegistryConstants() {
throw new AssertionError();
}
public static final String GENERAL_CONFIG_RESOURCE_PATH = "general";
}
public class APPManagerConstants {
private static final String APP_MANAGER_MDM_SERVICE_NAME =
"org.wso2.carbon.appmgt.mobile.interfaces.MDMOperations";
}
}

@ -1,95 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed 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.appmgt.mdm.osgiconnector.mdmmgt.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
/**
* MDMServiceAPIUtils class provides utility function.
*/
public class MDMServiceAPIUtils {
private static Log log = LogFactory.getLog(MDMServiceAPIUtils.class);
/**
* Returns the DeviceManagementProviderService osgi service.
*
* @param tenantId tenant id
* @return DeviceManagementProviderService
*/
public static DeviceManagementProviderService getDeviceManagementService(int tenantId) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantId(tenantId, true);
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx
.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management provider service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
/**
* Returns the DeviceAccessAuthorizationService osgi service.
*
* @param tenantId tenant id
* @return {@link DeviceAccessAuthorizationService}
*/
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService(int tenantId) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantId(tenantId, true);
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
(DeviceAccessAuthorizationService) ctx
.getOSGiService(DeviceAccessAuthorizationService.class, null);
if (deviceAccessAuthorizationService == null) {
String msg = "Device Access Authorization service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceAccessAuthorizationService;
}
/**
* Returns the ApplicationManagementProviderService osgi service.
*
* @param tenantId tenant id
* @return ApplicationManagementProviderService
*/
public static ApplicationManagementProviderService getAppManagementService(int tenantId) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantId(tenantId, true);
ApplicationManagementProviderService applicationManagementProviderService =
(ApplicationManagementProviderService) ctx.
getOSGiService(
ApplicationManagementProviderService.class,
null);
if (applicationManagementProviderService == null) {
String msg = "Application management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return applicationManagementProviderService;
}
}

@ -1,158 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>appm-connector</artifactId>
<version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.appmgt.mdm.restconnector</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - App Manager WSO2 MDM REST Connector Component</name>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Private-Package>org.wso2.carbon.appmgt.mdm.restconnector.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.wso2.carbon.appmgt.mobile.utils.*,
org.wso2.carbon.appmgt.mobile.mdm.*,
org.wso2.carbon.appmgt.mobile.interfaces.*,
org.apache.commons.*,
org.wso2.carbon.user.core.service,
org.wso2.carbon.user.core.tenant,
org.wso2.carbon.user.api,
feign,
feign.auth,
feign.codec,
feign.gson,
org.json.simple.*,
org.wso2.carbon.appmgt.mobile.beans,
org.wso2.carbon.base,
org.wso2.carbon.context,
javax.net.ssl,
feign.slf4j
</Import-Package>
<Export-Package>
!org.wso2.carbon.appmgt.mdm.restconnector.internal,
org.wso2.carbon.appmgt.mdm.restconnector.*
</Export-Package>
<Embed-Dependency>
jsr311-api,
feign-jaxrs
</Embed-Dependency>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.appmgt</groupId>
<artifactId>org.wso2.carbon.appmgt.mobile</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
</dependency>
</dependencies>
</project>

@ -1,383 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector;
import feign.Client;
import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.Response;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.OAuthRequestInterceptor;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.Activity;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApplicationManagementAdminService;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApplicationWrapper;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.DeviceManagementAdminService;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.MobileApp;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.MobileAppTypes;
import org.wso2.carbon.appmgt.mdm.restconnector.config.AuthorizationConfigurationManager;
import org.wso2.carbon.appmgt.mobile.beans.ApplicationOperationAction;
import org.wso2.carbon.appmgt.mobile.beans.ApplicationOperationDevice;
import org.wso2.carbon.appmgt.mobile.beans.DeviceIdentifier;
import org.wso2.carbon.appmgt.mobile.interfaces.ApplicationOperations;
import org.wso2.carbon.appmgt.mobile.mdm.App;
import org.wso2.carbon.appmgt.mobile.mdm.Device;
import org.wso2.carbon.appmgt.mobile.utils.MobileApplicationException;
import org.wso2.carbon.appmgt.mobile.utils.MobileConfigurations;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class ApplicationOperationsImpl implements ApplicationOperations {
private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0";
private static DeviceManagementAdminService deviceManagementAdminService;
private static final Log log = LogFactory.getLog(ApplicationOperationsImpl.class);
private static ApplicationManagementAdminService applicationManagementAdminService;
/**
* Constructor.
*/
public ApplicationOperationsImpl() {
String authorizationConfigManagerServerURL = AuthorizationConfigurationManager.getInstance().getServerURL();
OAuthRequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor();
deviceManagementAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
Logger.Level.FULL).requestInterceptor(oAuthRequestInterceptor)
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(DeviceManagementAdminService.class,
authorizationConfigManagerServerURL + CDMF_SERVER_BASE_CONTEXT);
applicationManagementAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
Logger.Level.FULL).requestInterceptor(oAuthRequestInterceptor)
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(ApplicationManagementAdminService.class,
authorizationConfigManagerServerURL + CDMF_SERVER_BASE_CONTEXT);
}
/**
* Install, uninstall, reinstall application in devices.
*
* @param applicationOperationAction {@link ApplicationOperationAction} object
* @return Activity id
* @throws MobileApplicationException on errors while trying to perform action in devices
*/
@Override
public String performAction(ApplicationOperationAction applicationOperationAction)
throws MobileApplicationException {
ApplicationWrapper applicationWrapper = new ApplicationWrapper();
MobileApp mobileApp = new MobileApp();
String type = applicationOperationAction.getType();
String[] params = applicationOperationAction.getParams();
int tenantId = applicationOperationAction.getTenantId();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
List<org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.Device> deviceList;
if (Constants.USER.equals(type)) {
String platform = applicationOperationAction.getApp().getPlatform();
String userName;
for (String param : params) {
userName = param;
deviceList = deviceManagementAdminService.getDevices(userName, null).getList();
for (org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.Device device : deviceList) {
if (Constants.WEBAPP.equals(platform) || platform.equalsIgnoreCase(device.getType())) {
if (Constants.ACTIVE.equalsIgnoreCase(device.getEnrolmentInfo().getStatus().toString())) {
deviceIdentifiers.add(getDeviceIdentifierByDevice(device));
}
}
}
}
} else if (Constants.ROLE.equals(type)) {
String userRole;
for (String param : applicationOperationAction.getParams()) {
userRole = param;
deviceList = deviceManagementAdminService.getDevices(null, userRole).getList();
for (org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.Device device : deviceList) {
if (Constants.ACTIVE.equalsIgnoreCase(device.getEnrolmentInfo().getStatus().toString())) {
deviceIdentifiers.add(getDeviceIdentifierByDevice(device));
}
}
}
} else if (Constants.DEVICE.equals(type)) {
DeviceIdentifier deviceIdentifier;
for (String param : params) {
deviceIdentifier = new DeviceIdentifier();
if (isValidJSON(param)) {
JSONParser parser = new JSONParser();
try {
JSONObject parsedObj = (JSONObject) parser.parse(param);
deviceIdentifier.setId((String) parsedObj.get(Constants.ID));
String deviceType = (String) parsedObj.get(Constants.TYPE);
deviceIdentifier.setType(deviceType);
deviceIdentifiers.add(deviceIdentifier);
} catch (ParseException e) {
throw new MobileApplicationException("Device Identifier is not valid json object.", e);
}
}
}
} else {
throw new IllegalStateException("Invalid type is received from app store.");
}
App app = applicationOperationAction.getApp();
mobileApp.setId(app.getId());
mobileApp.setType(MobileAppTypes.valueOf(app.getType().toUpperCase()));
mobileApp.setAppIdentifier(app.getAppIdentifier());
mobileApp.setIconImage(app.getIconImage());
mobileApp.setIdentifier(app.getIdentifier());
mobileApp.setLocation(app.getLocation());
mobileApp.setName(app.getName());
mobileApp.setPackageName(app.getPackageName());
mobileApp.setPlatform(app.getPlatform());
mobileApp.setVersion(app.getVersion());
Properties mobileAppProperties = new Properties();
if (Constants.IOS.equals(app.getPlatform())) {
if (Constants.ENTERPRISE.equals(app.getType())) {
mobileAppProperties.put(Constants.IOSConstants.IS_REMOVE_APP, true);
mobileAppProperties.put(Constants.IOSConstants.IS_PREVENT_BACKUP, true);
} else if (Constants.IOSConstants.PUBLIC.equals(app.getType())) {
mobileAppProperties.put(Constants.IOSConstants.I_TUNES_ID, app.getIdentifier());
mobileAppProperties.put(Constants.IOSConstants.IS_REMOVE_APP, true);
mobileAppProperties.put(Constants.IOSConstants.IS_PREVENT_BACKUP, true);
} else if (Constants.WEBAPP.equals(app.getType())) {
mobileAppProperties.put(Constants.IOSConstants.LABEL, app.getName());
mobileAppProperties.put(Constants.IOSConstants.IS_REMOVE_APP, true);
}
} else if (Constants.WEBAPP.equals(app.getPlatform())) {
mobileAppProperties.put(Constants.IOSConstants.LABEL, app.getName());
mobileAppProperties.put(Constants.IOSConstants.IS_REMOVE_APP, true);
}
mobileApp.setProperties(mobileAppProperties);
applicationWrapper.setApplication(mobileApp);
Activity activity = null;
if (deviceIdentifiers.size() > 0) {
applicationWrapper.setDeviceIdentifiers(deviceIdentifiers);
if (Constants.INSTALL.equals(applicationOperationAction.getAction())) {
activity = applicationManagementAdminService.installApplication(applicationWrapper);
} else if (Constants.UPDATE.equals(applicationOperationAction.getAction())) {
activity = applicationManagementAdminService.installApplication(applicationWrapper);
} else {
activity = applicationManagementAdminService.uninstallApplication(applicationWrapper);
}
}
if (activity != null) {
return activity.getActivityId();
}
return null;
}
/**
* Get devices.
*
* @param applicationOperationDevice {@link ApplicationOperationAction} object
* @return list of {@link Device} objects
* @throws MobileApplicationException on errors while trying to get devices list
*/
@Override
public List<Device> getDevices(ApplicationOperationDevice applicationOperationDevice)
throws MobileApplicationException {
Map<String, String> queryParamsMap = new HashMap<>();
String platform = applicationOperationDevice.getPlatform();
String platformVersion = applicationOperationDevice.getPlatformVersion();
String userName = applicationOperationDevice.getCurrentUser().getUsername();
queryParamsMap.put(Constants.PLATFORM, platform);
queryParamsMap.put(Constants.PLATFORM_VERSION, platformVersion);
queryParamsMap.put(Constants.USER, userName);
String type = applicationOperationDevice.getType();
queryParamsMap.put(Constants.TYPE, type);
List<org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.Device> deviceList =
deviceManagementAdminService.getDevices(userName, null).getList();
List<Device> processedDevices = new ArrayList<>();
for (org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.Device device : deviceList) {
Device processedDevice = new Device();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(device.getDeviceIdentifier().toString());
deviceIdentifier.setType(device.getType().toString());
processedDevice.setDeviceIdentifier(deviceIdentifier);
processedDevice.setName(device.getName());
processedDevice.setModel(device.getName());
processedDevice.setType(device.getType());
String imgUrl;
if (Constants.ANDROID.equalsIgnoreCase((device.getType().toString()))) {
imgUrl = String.format(getActiveMDMProperties().get(Constants.PROPERTY_IMAGE_URL), Constants.NEXUS);
} else if (Constants.IOS.equalsIgnoreCase((device.getType().toString()))) {
imgUrl = String.format(getActiveMDMProperties().get(Constants.PROPERTY_IMAGE_URL), Constants.IPHONE);
} else {
imgUrl = String.format(getActiveMDMProperties().get(Constants.PROPERTY_IMAGE_URL), Constants.NONE);
}
processedDevice.setImage(imgUrl);
processedDevice.setPlatform(device.getType().toString());
processedDevices.add(processedDevice);
}
return processedDevices;
}
private HashMap<String, String> getActiveMDMProperties() {
MobileConfigurations configurations = MobileConfigurations.getInstance();
return configurations.getActiveMDMProperties();
}
private static DeviceIdentifier getDeviceIdentifierByDevice(
org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.Device device) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(device.getDeviceIdentifier());
deviceIdentifier.setType(device.getType());
return deviceIdentifier;
}
private boolean isValidJSON(String json) {
JSONParser parser = new JSONParser();
try {
parser.parse(json);
} catch (ParseException e) {
return false;
}
return true;
}
private void logError(String errorMessage, Throwable e) {
if (log.isDebugEnabled()) {
log.error(errorMessage, e);
} else {
log.error(errorMessage);
}
}
public static Client getSSLClient() {
boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.getProperty("org.wso2.ignoreHostnameVerification"));
if(isIgnoreHostnameVerification) {
return new Client.Default(getSimpleTrustedSSLSocketFactory(), new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}else {
return new Client.Default(getTrustedSSLSocketFactory(), null);
}
}
private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
return sc.getSocketFactory();
} catch (KeyManagementException | NoSuchAlgorithmException e) {
return null;
}
}
//FIXME - I know hard-cording values is a bad practice , this code is repeating in
// several class, so this hard-coding strings will be removed once this code block is moved into a central location
// this should be done after the 3.1.0 release.
private static SSLSocketFactory getTrustedSSLSocketFactory() {
try {
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
"Security.TrustStore.Password");
String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
"Security.TrustStore.Location");
KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,"JKS");
KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword);
return initSSLConnection(keyStore,keyStorePassword,trustStore);
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException
|CertificateException | IOException | UnrecoverableKeyException e) {
log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e);
return null;
}
}
private static SSLSocketFactory initSSLConnection(KeyStore keyStore,String keyStorePassword,KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException,
KeyStoreException, KeyManagementException {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(trustStore);
// Create and initialize SSLContext for HTTPS communication
SSLContext sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
SSLContext.setDefault(sslContext);
return sslContext.getSocketFactory();
}
private static KeyStore loadKeyStore(String keyStorePath, String ksPassword, String type)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
InputStream fileInputStream = null;
try {
char[] keypassChar = ksPassword.toCharArray();
KeyStore keyStore = KeyStore.getInstance(type);
fileInputStream = new FileInputStream(keyStorePath);
keyStore.load(fileInputStream, keypassChar);
return keyStore;
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
}
private static KeyStore loadTrustStore(String trustStorePath, String tsPassword)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
return loadKeyStore(trustStorePath,tsPassword,"JKS");
}
}

@ -1,108 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector;
public class Constants {
public static final String PROPERTY_SERVER_URL = "ServerURL";
public static final String PROPERTY_TOKEN_API_URL = "TokenApiURL";
public static final String PROPERTY_IMAGE_URL = "ImageURL";
public static final String PROPERTY_TOKEN_REFRESH_TIME_OFFSET = "TokenRefreshTimeOffset";
public static final String PROPERTY_USERNAME = "Username";
public static final String PROPERTY_PASSWORD = "Password";
public static final String USER = "user";
public static final String ROLE = "role";
public static final String USERS = USER + "s";
public static final String ROLES = ROLE + "s";
public static final String ANDROID = "android";
public static final String IOS = "ios";
public static final String WEBAPP = "webapp";
public static final String PLATFORM = "platform";
public static final String PLATFORM_VERSION = "platformVersion";
public static final String PROPERTIES = "properties";
public static final String TYPE = "type";
public static final String TYPES = TYPE + "s";
public static final String ID = "id";
public static final String NAME = "name";
public static final String USER_LIST = "userList";
public static final String DEVICE_IDENTIFIER = "deviceIdentifier";
public static final String DEVICE_IDENTIFIERS = DEVICE_IDENTIFIER + "s";
public static final String DEVICES = "devices";
public static final String APPLICATION = "application";
public static final String NEXUS = "nexus";
public static final String IPHONE = "iphone";
public static final String NONE = "none";
public static final String INSTALL = "install";
public static final String UPDATE = "update";
public static final String MOBILE_DEVICE = "mobileDevice";
public static final String ENTERPRISE = "enterprise";
public static final String ACTIVE = "active";
public static final String DEVICE = "device";
public class IOSConstants {
private IOSConstants() {
throw new AssertionError();
}
public static final String IS_REMOVE_APP = "isRemoveApp";
public static final String IS_PREVENT_BACKUP = "isPreventBackup";
public static final String I_TUNES_ID = "iTunesId";
public static final String LABEL = "label";
public static final String PUBLIC = "public";
public static final String OPCODE_INSTALL_ENTERPRISE_APPLICATION =
"INSTALL_ENTERPRISE_APPLICATION";
public static final String OPCODE_INSTALL_STORE_APPLICATION = "INSTALL_STORE_APPLICATION";
public static final String OPCODE_INSTALL_WEB_APPLICATION = "WEB_CLIP";
public static final String OPCODE_REMOVE_APPLICATION = "REMOVE_APPLICATION";
}
public class AndroidConstants {
private AndroidConstants() {
throw new AssertionError();
}
public static final String OPCODE_INSTALL_APPLICATION = "INSTALL_APPLICATION";
public static final String OPCODE_UPDATE_APPLICATION = "UPDATE_APPLICATION";
public static final String OPCODE_UNINSTALL_APPLICATION = "UNINSTALL_APPLICATION";
}
public class WebAppConstants {
public static final String WEBAPP = "webapp";
public static final String LABEL = "label";
public static final String IS_REMOVE_APP = "isRemoveApp";
public static final String NAME = "name";
}
public class RestConstants {
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String AUTHORIZATION = "Authorization";
public static final String BEARER = "Bearer ";
public static final String BASIC = "Basic ";
public static final String COLON = ":";
public static final String GRANT_TYPE = "grant_type";
public static final String CONTENT_TYPE = "Content-Type";
public static final String ACCESS_TOKEN = "accessToken";
public static final String ACCEPT = "Accept";
public static final String APPLICATION_JSON = "application/json";
public static final String APPLICATION_FORM_URL_ENCODED = "application/x-www-form-urlencoded";
}
}

@ -1,227 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client;
import feign.Client;
import feign.Feign;
import feign.FeignException;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Response;
import feign.auth.BasicAuthRequestInterceptor;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.appmgt.mdm.restconnector.Constants;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.AccessTokenInfo;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApiApplicationKey;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApiApplicationRegistrationService;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApiRegistrationProfile;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.TokenIssuerService;
import org.wso2.carbon.appmgt.mdm.restconnector.config.AuthorizationConfigurationManager;
import org.wso2.carbon.appmgt.mdm.restconnector.internal.AuthorizationDataHolder;
import org.wso2.carbon.base.ServerConfiguration;
import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
/**
* This is a request interceptor to add oauth token header.
*/
public class OAuthRequestInterceptor implements RequestInterceptor {
private AccessTokenInfo tokenInfo;
private String refreshTimeOffset;
private static final String API_APPLICATION_REGISTRATION_CONTEXT = "/api-application-registration";
private static final String DEVICE_MANAGEMENT_SERVICE_TAG[] = {"device_management"};
private static final String APPLICATION_NAME = "appm_restconnector_application";
private static final String PASSWORD_GRANT_TYPE = "password";
private static final String REFRESH_GRANT_TYPE = "refresh_token";
private ApiApplicationRegistrationService apiApplicationRegistrationService;
private TokenIssuerService tokenIssuerService;
private static Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
private ApiApplicationKey apiApplicationKey;
/**
* Creates an interceptor that authenticates all requests.
*/
public OAuthRequestInterceptor() {
refreshTimeOffset = AuthorizationConfigurationManager.getInstance().getTokenRefreshTimeOffset();
String username = AuthorizationConfigurationManager.getInstance().getUserName();
String password = AuthorizationConfigurationManager.getInstance().getPassword();
apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(ApiApplicationRegistrationService.class,
AuthorizationConfigurationManager.getInstance().getServerURL() +
API_APPLICATION_REGISTRATION_CONTEXT);
AuthorizationDataHolder.getInstance().setApiApplicationRegistrationService(apiApplicationRegistrationService);
}
/**
* Api create.
*
* @param template {@link RequestTemplate} object
*/
@Override
public void apply(RequestTemplate template) {
if (tokenInfo == null) {
if (apiApplicationKey == null) {
ApiRegistrationProfile apiRegistrationProfile = new ApiRegistrationProfile();
apiRegistrationProfile.setApplicationName(APPLICATION_NAME);
apiRegistrationProfile.setIsAllowedToAllDomains(false);
apiRegistrationProfile.setIsMappingAnExistingOAuthApp(false);
apiRegistrationProfile.setTags(DEVICE_MANAGEMENT_SERVICE_TAG);
apiApplicationKey = apiApplicationRegistrationService.register(apiRegistrationProfile);
}
String consumerKey = apiApplicationKey.getConsumerKey();
String consumerSecret = apiApplicationKey.getConsumerSecret();
String username = AuthorizationConfigurationManager.getInstance().getUserName();
String password = AuthorizationConfigurationManager.getInstance().getPassword();
if (tokenIssuerService == null) {
tokenIssuerService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
Logger.Level.FULL)
.requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(TokenIssuerService.class,
AuthorizationConfigurationManager.getInstance().getTokenApiURL());
}
tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password);
tokenInfo.setExpires_in(System.currentTimeMillis() + tokenInfo.getExpires_in());
} else {
synchronized (this) {
if (System.currentTimeMillis() + Long.parseLong(refreshTimeOffset) > tokenInfo.getExpires_in()) {
try {
tokenInfo = tokenIssuerService.getToken(REFRESH_GRANT_TYPE, tokenInfo.getRefresh_token());
tokenInfo.setExpires_in(System.currentTimeMillis() + tokenInfo.getExpires_in());
} catch (FeignException e) {
tokenInfo = null;
apply(template);
}
}
}
}
String headerValue = Constants.RestConstants.BEARER + tokenInfo.getAccess_token();
template.header(Constants.RestConstants.AUTHORIZATION, headerValue);
}
public static Client getSSLClient() {
boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.getProperty("org.wso2.ignoreHostnameVerification"));
if(isIgnoreHostnameVerification) {
return new Client.Default(getSimpleTrustedSSLSocketFactory(), new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}else {
return new Client.Default(getTrustedSSLSocketFactory(), null);
}
}
private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() {
try {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
return sc.getSocketFactory();
} catch (KeyManagementException | NoSuchAlgorithmException e) {
return null;
}
}
//FIXME - I know hard-cording values is a bad practice , this code is repeating in
// several class, so this hard-coding strings will be removed once this code block is moved into a central location
// this should be done after the 3.1.0 release.
private static SSLSocketFactory getTrustedSSLSocketFactory() {
try {
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
"Security.TrustStore.Password");
String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
"Security.TrustStore.Location");
KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,"JKS");
KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword);
return initSSLConnection(keyStore,keyStorePassword,trustStore);
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException
|CertificateException | IOException | UnrecoverableKeyException e) {
log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e);
return null;
}
}
private static SSLSocketFactory initSSLConnection(KeyStore keyStore,String keyStorePassword,KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException,
KeyStoreException, KeyManagementException {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(trustStore);
// Create and initialize SSLContext for HTTPS communication
SSLContext sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
SSLContext.setDefault(sslContext);
return sslContext.getSocketFactory();
}
private static KeyStore loadKeyStore(String keyStorePath, String ksPassword, String type)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
InputStream fileInputStream = null;
try {
char[] keypassChar = ksPassword.toCharArray();
KeyStore keyStore = KeyStore.getInstance(type);
fileInputStream = new FileInputStream(keyStorePath);
keyStore.load(fileInputStream, keypassChar);
return keyStore;
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
}
private static KeyStore loadTrustStore(String trustStorePath, String tsPassword)
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
return loadKeyStore(trustStorePath,tsPassword,"JKS");
}
}

@ -1,60 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
/**
* This hold access token info that returned from the api call.
*/
public class AccessTokenInfo {
public String token_type;
public long expires_in;
public String refresh_token;
public String access_token;
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public long getExpires_in() {
return expires_in;
}
public void setExpires_in(long expires_in) {
this.expires_in = expires_in;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
}

@ -1,63 +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.
*/
package org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto;
public class Activity {
public enum Type {
CONFIG, MESSAGE, INFO, COMMAND, PROFILE, POLICY
}
private String activityId;
private String code;
private Type type;
private String createdTimeStamp;
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getCreatedTimeStamp() {
return createdTimeStamp;
}
public void setCreatedTimeStamp(String createdTimeStamp) {
this.createdTimeStamp = createdTimeStamp;
}
}

@ -1,42 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
/**
* This holds api application consumer key and secret.
*/
public class ApiApplicationKey {
private String client_id;
private String client_secret;
public String getConsumerKey() {
return this.client_id;
}
public void setClient_id(String consumerKey) {
this.client_id = consumerKey;
}
public String getConsumerSecret() {
return this.client_secret;
}
public void setClient_secret(String consumerSecret) {
this.client_secret = consumerSecret;
}
}

@ -1,42 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* This is the application registration service that exposed for apimApplicationRegistration.
*/
@Path("/register")
public interface ApiApplicationRegistrationService {
/**
* This method is used to register api application.
*
* @param registrationProfile contains the necessary attributes that are needed in order to register an app
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
ApiApplicationKey register(ApiRegistrationProfile registrationProfile);
}

@ -1,79 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
/**
* This class represents the data that are required to register the oauth application.
*/
public class ApiRegistrationProfile {
public String applicationName;
public String tags[];
public boolean isAllowedToAllDomains;
public String consumerKey;
public String consumerSecret;
public boolean isMappingAnExistingOAuthApp;
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String[] getTags() {
return tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
public boolean isAllowedToAllDomains() {
return isAllowedToAllDomains;
}
public void setIsAllowedToAllDomains(boolean isAllowedToAllDomains) {
this.isAllowedToAllDomains = isAllowedToAllDomains;
}
public boolean isMappingAnExistingOAuthApp() {
return isMappingAnExistingOAuthApp;
}
public void setIsMappingAnExistingOAuthApp(boolean isMappingAnExistingOAuthApp) {
this.isMappingAnExistingOAuthApp = isMappingAnExistingOAuthApp;
}
public String getConsumerKey() {
return consumerKey;
}
public void setConsumerKey(String consumerKey) {
this.consumerKey = consumerKey;
}
public String getConsumerSecret() {
return consumerSecret;
}
public void setConsumerSecret(String consumerSecret) {
this.consumerSecret = consumerSecret;
}
}

@ -1,59 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/admin/applications")
/**
* This interface provided the definition of the application management service.
*/
public interface ApplicationManagementAdminService {
/**
* Install application.
*
* @param applicationWrapper {@link ApplicationWrapper} object
* @return {@link Activity} object
*/
@POST
@Path("/install-application")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
Activity installApplication(ApplicationWrapper applicationWrapper);
/**
* Uninstall application.
*
* @param applicationWrapper {@link ApplicationWrapper} object
* @return {@link Activity} object
*/
@POST
@Path("/uninstall-application")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
Activity uninstallApplication(ApplicationWrapper applicationWrapper);
}

@ -1,65 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import org.wso2.carbon.appmgt.mobile.beans.DeviceIdentifier;
import java.util.List;
/**
* This DTO class is used to send application details and devices details to installation/uninstallation service.
*/
public class ApplicationWrapper {
private List<String> userNameList;
private List<String> roleNameList;
private List<DeviceIdentifier> deviceIdentifiers;
private MobileApp application;
public List<String> getUserNameList() {
return userNameList;
}
public void setUserNameList(List<String> userNameList) {
this.userNameList = userNameList;
}
public List<DeviceIdentifier> getDeviceIdentifiers() {
return deviceIdentifiers;
}
public void setDeviceIdentifiers(
List<DeviceIdentifier> deviceIdentifiers) {
this.deviceIdentifiers = deviceIdentifiers;
}
public List<String> getRoleNameList() {
return roleNameList;
}
public void setRoleNameList(List<String> roleNameList) {
this.roleNameList = roleNameList;
}
public MobileApp getApplication() {
return application;
}
public void setApplication(MobileApp application) {
this.application = application;
}
}

@ -1,121 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import java.io.Serializable;
/**
* The DTO class of device.
*/
public class Device implements Serializable {
private static final long serialVersionUID = 1998101711L;
private int id;
private String name;
private String type;
private String description;
private String deviceIdentifier;
private EnrolmentInfo enrolmentInfo;
public Device() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(String deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public EnrolmentInfo getEnrolmentInfo() {
return enrolmentInfo;
}
public void setEnrolmentInfo(EnrolmentInfo enrolmentInfo) {
this.enrolmentInfo = enrolmentInfo;
}
public static class Property {
private String name;
private String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@Override
public String toString() {
return "device [" +
"name=" + name + ";" +
"type=" + type + ";" +
"description=" + description + ";" +
"identifier=" + deviceIdentifier + ";" +
"EnrolmentInfo[" +
"owner=" + enrolmentInfo.getOwner() + ";" +
"ownership=" + enrolmentInfo.getOwnership() + ";" +
"status=" + enrolmentInfo.getStatus() + ";" +
"]" +
"]";
}
}

@ -1,53 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import java.util.ArrayList;
import java.util.List;
public class DeviceList {
private List<Device> devices = new ArrayList<>();
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Device> getList() {
return devices;
}
public void setList(List<Device> devices) {
this.devices = devices;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" count: ").append(getCount()).append(",\n");
sb.append(" devices: [").append(devices).append("\n");
sb.append("]}\n");
return sb.toString();
}
}

@ -1,47 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/devices")
/**
* This interface provided the definition of the device management service.
*/
public interface DeviceManagementAdminService {
/**
* Get devices.
*
* @param user Username
* @param role Role of the user
* @return {@link DeviceList} object
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
DeviceList getDevices(@QueryParam("user") String user, @QueryParam("role") String role);
}

@ -1,118 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import java.io.Serializable;
/**
* The DTO class for enrollment information.
*/
public class EnrolmentInfo implements Serializable {
private static final long serialVersionUID = 1998101712L;
public enum Status {
CREATED, ACTIVE, INACTIVE, UNREACHABLE, UNCLAIMED, SUSPENDED, BLOCKED, REMOVED, DISENROLLMENT_REQUESTED
}
public enum OwnerShip {
BYOD, COPE
}
private int id;
private OwnerShip ownership;
private Status status;
private String owner;
private Long dateOfEnrolment;
private Long dateOfLastUpdate;
public EnrolmentInfo() {
}
public EnrolmentInfo(String owner, OwnerShip ownership, Status status) {
this.owner = owner;
this.ownership = ownership;
this.status = status;
}
public Long getDateOfEnrolment() {
return dateOfEnrolment;
}
public void setDateOfEnrolment(Long dateOfEnrolment) {
this.dateOfEnrolment = dateOfEnrolment;
}
public Long getDateOfLastUpdate() {
return dateOfLastUpdate;
}
public void setDateOfLastUpdate(Long dateOfLastUpdate) {
this.dateOfLastUpdate = dateOfLastUpdate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public OwnerShip getOwnership() {
return ownership;
}
public void setOwnership(OwnerShip ownership) {
this.ownership = ownership;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof EnrolmentInfo) {
EnrolmentInfo tempInfo = (EnrolmentInfo) obj;
if (this.owner != null && this.ownership != null) {
if (this.owner.equals(tempInfo.getOwner()) && this.ownership.equals(tempInfo.getOwnership())) {
return true;
}
}
}
return false;
}
@Override
public int hashCode() {
return owner.hashCode() ^ ownership.hashCode();
}
}

@ -1,126 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import java.util.Properties;
/**
* This class represents the generic mobile Application information which is used by AppM.
*/
public class MobileApp {
private String id;
private String name;
private MobileAppTypes type;
private String platform;
private String version;
private String identifier;
private String iconImage;
private String packageName;
private String appIdentifier;
private String location;
private Properties properties;
public MobileAppTypes getType() {
return type;
}
public void setType(MobileAppTypes type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getIconImage() {
return iconImage;
}
public void setIconImage(String iconImage) {
this.iconImage = iconImage;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getAppIdentifier() {
return appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}

@ -1,25 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
/**
* This enum contains the mobile app types.
*/
public enum MobileAppTypes {
ENTERPRISE, WEBAPP, PUBLIC
}

@ -1,56 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.authorization.client.dto;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* This hold the api definition that is used as a contract with netflix feign.
*/
@Path("/token")
public interface TokenIssuerService {
/**
* Get a token for password grant type.
* @param grant Token grant type
* @param username Username
* @param password Password
* @return {@link AccessTokenInfo} object
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
AccessTokenInfo getToken(@QueryParam("grant_type") String grant, @QueryParam("username") String username,
@QueryParam("password") String password);
/**
* Get a token for refresh grant type.
* @param grant Token grant type
* @param refreshToken Refresh token
* @return {@link AccessTokenInfo} object
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
AccessTokenInfo getToken(@QueryParam("grant_type") String grant, @QueryParam("refreshToken") String refreshToken);
}

@ -1,110 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.config;
import org.wso2.carbon.appmgt.mdm.restconnector.Constants;
import org.wso2.carbon.appmgt.mobile.utils.MobileConfigurations;
import java.util.HashMap;
/**
* The DTO class to AuthorizationConfigurationManager.
*/
public class AuthorizationConfigurationManager {
private String tokenApiURL;
private String imageURL;
private String serverURL;
private String userName;
private String password;
private String tokenRefreshTimeOffset;
private static AuthorizationConfigurationManager authorizationConfigurationManager = new
AuthorizationConfigurationManager();
private AuthorizationConfigurationManager() {
MobileConfigurations configurations = MobileConfigurations.getInstance();
HashMap<String, String> configProperties = configurations.getActiveMDMProperties();
setTokenApiURL(configProperties.get(Constants.PROPERTY_TOKEN_API_URL));
setImageURL(configProperties.get(Constants.PROPERTY_IMAGE_URL));
setServerURL(configProperties.get(Constants.PROPERTY_SERVER_URL));
setUserName(configProperties.get(Constants.PROPERTY_USERNAME));
setPassword(configProperties.get(Constants.PROPERTY_PASSWORD));
setTokenRefreshTimeOffset(configProperties.get(Constants.PROPERTY_TOKEN_REFRESH_TIME_OFFSET));
}
public static AuthorizationConfigurationManager getInstance() {
return authorizationConfigurationManager;
}
public String getTokenApiURL() {
return tokenApiURL;
}
public void setTokenApiURL(String tokenApiURL) {
this.tokenApiURL = tokenApiURL;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static AuthorizationConfigurationManager getAuthorizationConfigurationManager() {
return authorizationConfigurationManager;
}
public static void setAuthorizationConfigurationManager(
AuthorizationConfigurationManager authorizationConfigurationManager) {
AuthorizationConfigurationManager.authorizationConfigurationManager = authorizationConfigurationManager;
}
public String getTokenRefreshTimeOffset() {
return tokenRefreshTimeOffset;
}
public void setTokenRefreshTimeOffset(String tokenRefreshTimeOffset) {
this.tokenRefreshTimeOffset = tokenRefreshTimeOffset;
}
}

@ -1,43 +0,0 @@
/*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.internal;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApiApplicationRegistrationService;
public class AuthorizationDataHolder {
private static AuthorizationDataHolder thisInstance = new AuthorizationDataHolder();
private ApiApplicationRegistrationService apiApplicationRegistrationService;
private AuthorizationDataHolder() {
}
public static AuthorizationDataHolder getInstance() {
return thisInstance;
}
public ApiApplicationRegistrationService getApiApplicationRegistrationService() {
return apiApplicationRegistrationService;
}
public void setApiApplicationRegistrationService(
ApiApplicationRegistrationService apiApplicationRegistrationService) {
this.apiApplicationRegistrationService = apiApplicationRegistrationService;
}
}

@ -1,56 +0,0 @@
/*
*
* Copyright (c) 2017, 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.appmgt.mdm.restconnector.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.appmgt.mdm.restconnector.ApplicationOperationsImpl;
import org.wso2.carbon.appmgt.mobile.interfaces.ApplicationOperations;
/**
* @scr.component name="org.wso2.carbon.appmgt.mdm.restconnector" immediate="true"
*/
public class MDMComponent {
private static final Log log = LogFactory.getLog(MDMComponent.class);
private ServiceRegistration mdmServiceRegistration;
protected void activate(ComponentContext context) {
BundleContext bundleContext = context.getBundleContext();
mdmServiceRegistration = bundleContext.registerService(ApplicationOperations.class.getName(), new
ApplicationOperationsImpl(), null);
if (log.isDebugEnabled()) {
log.debug("WSO2MDM MDM Component activated.");
}
}
protected void deactivate(ComponentContext context) {
if (mdmServiceRegistration != null) {
mdmServiceRegistration.unregister();
mdmServiceRegistration = null;
}
if (log.isDebugEnabled()) {
log.debug("WSO2MDM MDM Component deactivated");
}
}
}

@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>extensions</artifactId>
<version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>appm-connector</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Base Plugin</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.appmgt.mdm.osgiconnector</module>
<module>org.wso2.carbon.appmgt.mdm.restconnector</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>1.7.2</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -80,6 +80,10 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
</dependencies>
<build>

@ -54,6 +54,14 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
</dependencies>
<build>
<plugins>

@ -69,6 +69,10 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>

@ -28,7 +28,7 @@
<artifactId>org.wso2.carbon.device.mgt.output.adapter.xmpp</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - Device Mgt Output MQTT Adaptor Module</name>
<name>WSO2 Carbon - Device Mgt Output XMPP Adaptor Module</name>
<description>org.wso2.carbon.device.mgt.output.adapter.xmpp provides the back-end functionality of xmpp adaptor
</description>
<url>http://wso2.org</url>

@ -327,6 +327,18 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</dependency>
</dependencies>
</project>

@ -22,8 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
//import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;

@ -33,7 +33,6 @@
<url>http://wso2.org</url>
<modules>
<module>appm-connector</module>
<module>cdmf-transport-adapters</module>
<module>mb-extensions</module>
<module>siddhi-extensions</module>

@ -63,6 +63,10 @@
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.input.adapter.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
</dependencies>
<build>

@ -54,6 +54,22 @@
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
</dependency>
<!--dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>

@ -22,8 +22,8 @@ import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
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;

@ -126,16 +126,32 @@
<artifactId>javax.cache.wso2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging-api</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

@ -22,8 +22,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.extension.siddhi.device.utils.DeviceUtils;
import org.wso2.siddhi.core.config.ExecutionPlanContext;

@ -22,7 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.extension.siddhi.device.utils.DeviceUtils;
import org.wso2.siddhi.core.config.ExecutionPlanContext;

@ -21,8 +21,8 @@ package org.wso2.extension.siddhi.device;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.extension.siddhi.device.utils.DeviceUtils;
import org.wso2.siddhi.core.config.ExecutionPlanContext;

@ -20,9 +20,8 @@ package org.wso2.extension.siddhi.device;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.extension.siddhi.device.utils.DeviceUtils;
import org.wso2.siddhi.core.config.ExecutionPlanContext;

@ -21,10 +21,8 @@ package org.wso2.extension.siddhi.device;
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.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.extension.siddhi.device.utils.DeviceUtils;
import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException;

@ -30,12 +30,13 @@ import feign.okhttp.OkHttpClient;
import feign.slf4j.Slf4jLogger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.extension.siddhi.device.client.configs.SiddhiExtensionConfigReader;
import org.wso2.extension.siddhi.device.client.dto.OAuthApplication;
import org.wso2.extension.siddhi.device.client.dto.RegistrationProfile;

@ -26,7 +26,7 @@ import org.testng.annotations.BeforeSuite;
import org.w3c.dom.Document;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory;

@ -24,8 +24,8 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceNotFoundException;
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.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
@ -111,7 +111,7 @@ public class ExtensionTestCase extends BaseDeviceManagementTest {
}
private RegistryService getRegistryService() throws RegistryException, UserStoreException,
DeviceManagementException {
DeviceManagementException {
RealmService realmService = new InMemoryRealmService();
RegistryDataHolder.getInstance().setRealmService(realmService);
DeviceManagementDataHolder.getInstance().setRealmService(realmService);

@ -34,7 +34,6 @@
*/
package org.wso2.extension.siddhi.device.test.util;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
@ -43,11 +42,13 @@ import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.StartupOperationConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.general.GeneralConfig;
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypePlatformDetails;
import java.util.ArrayList;
import java.util.List;
@ -137,4 +138,7 @@ public class TestDeviceManagementService implements DeviceManagementService {
public GeneralConfig getGeneralConfig() {
return null;
}
@Override
public DeviceTypePlatformDetails getDeviceTypePlatformDetails() { return null; }
}

@ -17,11 +17,11 @@ package org.wso2.extension.siddhi.device.test.util;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;

@ -11,6 +11,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
CREATE TABLE IF NOT EXISTS DM_GROUP (
ID INTEGER AUTO_INCREMENT NOT NULL,
GROUP_NAME VARCHAR(100) DEFAULT NULL,
STATUS VARCHAR(50) DEFAULT NULL,
DESCRIPTION TEXT DEFAULT NULL,
OWNER VARCHAR(255) DEFAULT NULL,
TENANT_ID INTEGER DEFAULT 0,

@ -359,5 +359,15 @@
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-androidenterprise</artifactId>
<version>v1-rev186-1.25.0</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.application.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,87 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "BasicUserInfo", description = "Basic user information and the roles of the user.")
public class BasicUserInfo {
@ApiModelProperty(name = "username", value = "The login name of the user.", required = true )
private String username;
@ApiModelProperty(name = "firstname", value = "The first name of the user.", required = true )
private String firstname;
@ApiModelProperty(name = "lastname", value = "The last name of the user.", required = true )
private String lastname;
@ApiModelProperty(name = "emailAddress", value = "The email address of the user.", required = true )
private String emailAddress;
@ApiModelProperty(name = "createdDate", value = "User creation date." )
private String createdDate;
@ApiModelProperty(name = "modifiedDate", value = "User modifiedDate date." )
private String modifiedDate;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
}

@ -0,0 +1,32 @@
package org.wso2.carbon.mdm.services.android.bean;
public class EnterpriseConfigs {
String enterpriseId;
String esa;
ErrorResponse errorResponse;
public ErrorResponse getErrorResponse() {
return errorResponse;
}
public void setErrorResponse(ErrorResponse errorResponse) {
this.errorResponse = errorResponse;
}
public String getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(String enterpriseId) {
this.enterpriseId = enterpriseId;
}
public String getEsa() {
return esa;
}
public void setEsa(String esa) {
this.esa = esa;
}
}

@ -0,0 +1,72 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean;
import java.util.List;
public class EnterpriseStoreCluster {
String pageId;
String clusterId;
String name;
List<EnterpriseStorePackages> products;
String orderInPage;
public String getClusterId() {
return clusterId;
}
public void setClusterId(String clusterId) {
this.clusterId = clusterId;
}
public String getPageId() {
return pageId;
}
public void setPageId(String pageId) {
this.pageId = pageId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<EnterpriseStorePackages> getProducts() {
return products;
}
public void setProducts(List<EnterpriseStorePackages> products) {
this.products = products;
}
public String getOrderInPage() {
return orderInPage;
}
public void setOrderInPage(String orderInPage) {
this.orderInPage = orderInPage;
}
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean;
public class EnterpriseStorePackages {
String packageId;
String iconUrl;
public String getPackageId() {
return packageId;
}
public void setPackageId(String packageId) {
this.packageId = packageId;
}
public String getIconUrl() {
return iconUrl;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
}

@ -0,0 +1,61 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean;
import java.util.List;
public class EnterpriseStorePage {
String locale;
String pageName;
String pageId;
List<String> links;
public String getPageId() {
return pageId;
}
public void setPageId(String pageId) {
this.pageId = pageId;
}
public List<String> getLinks() {
return links;
}
public void setLinks(List<String> links) {
this.links = links;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean;
import java.util.List;
public class EnterpriseStorePageLinks {
String pageId;
List<String> links;
public String getPageId() {
return pageId;
}
public void setPageId(String pageId) {
this.pageId = pageId;
}
public List<String> getLinks() {
return links;
}
public void setLinks(List<String> links) {
this.links = links;
}
}

@ -0,0 +1,96 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean;
public class EnterpriseTokenUrl {
String enterpriseId;
String parentHost;
boolean approveApps;
boolean searchEnabled;
boolean isPrivateAppsEnabled;
boolean isWebAppEnabled;
boolean isOrganizeAppPageVisible;
boolean isManagedConfigEnabled;
public String getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(String enterpriseId) {
this.enterpriseId = enterpriseId;
}
public String getParentHost() {
return parentHost;
}
public void setParentHost(String parentHost) {
this.parentHost = parentHost;
}
public boolean isApproveApps() {
return approveApps;
}
public void setApproveApps(boolean approveApps) {
this.approveApps = approveApps;
}
public boolean isSearchEnabled() {
return searchEnabled;
}
public void setSearchEnabled(boolean searchEnabled) {
this.searchEnabled = searchEnabled;
}
public boolean isPrivateAppsEnabled() {
return isPrivateAppsEnabled;
}
public void setPrivateAppsEnabled(boolean privateAppsEnabled) {
isPrivateAppsEnabled = privateAppsEnabled;
}
public boolean isWebAppEnabled() {
return isWebAppEnabled;
}
public void setWebAppEnabled(boolean webAppEnabled) {
isWebAppEnabled = webAppEnabled;
}
public boolean isOrganizeAppPageVisible() {
return isOrganizeAppPageVisible;
}
public void setOrganizeAppPageVisible(boolean organizeAppPageVisible) {
isOrganizeAppPageVisible = organizeAppPageVisible;
}
public boolean isManagedConfigEnabled() {
return isManagedConfigEnabled;
}
public void setManagedConfigEnabled(boolean managedConfigEnabled) {
isManagedConfigEnabled = managedConfigEnabled;
}
}

@ -0,0 +1,14 @@
package org.wso2.carbon.mdm.services.android.bean;
public class GoogleAppSyncResponse {
int totalApps;
public int getTotalApps() {
return totalApps;
}
public void setTotalApps(int totalApps) {
this.totalApps = totalApps;
}
}

@ -0,0 +1,102 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean.wrapper;
import com.google.api.services.androidenterprise.model.VariableSet;
import java.io.Serializable;
import java.util.List;
public class EnterpriseApp implements Serializable {
private static final long serialVersionUID = 45598101734L;
String productId;
String autoInstallMode;
int autoInstallPriority;
String chargingStateConstraint;
String deviceIdleStateConstraint;
String networkTypeConstraint;
String mcmId;
List<VariableSet> variableSet;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getAutoInstallMode() {
return autoInstallMode;
}
public void setAutoInstallMode(String autoInstallMode) {
this.autoInstallMode = autoInstallMode;
}
public int getAutoInstallPriority() {
return autoInstallPriority;
}
public void setAutoInstallPriority(int autoInstallPriority) {
this.autoInstallPriority = autoInstallPriority;
}
public String getChargingStateConstraint() {
return chargingStateConstraint;
}
public void setChargingStateConstraint(String chargingStateConstraint) {
this.chargingStateConstraint = chargingStateConstraint;
}
public String getDeviceIdleStateConstraint() {
return deviceIdleStateConstraint;
}
public void setDeviceIdleStateConstraint(String deviceIdleStateConstraint) {
this.deviceIdleStateConstraint = deviceIdleStateConstraint;
}
public String getNetworkTypeConstraint() {
return networkTypeConstraint;
}
public void setNetworkTypeConstraint(String networkTypeConstraint) {
this.networkTypeConstraint = networkTypeConstraint;
}
public String getMcmId() {
return mcmId;
}
public void setMcmId(String mcmId) {
this.mcmId = mcmId;
}
public List<VariableSet> getVariableSet() {
return variableSet;
}
public void setVariableSet(List<VariableSet> variableSet) {
this.variableSet = variableSet;
}
}

@ -0,0 +1,100 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean.wrapper;
import java.io.Serializable;
import java.util.List;
public class EnterpriseInstallPolicy implements Serializable {
private static final long serialVersionUID = 15598101712L;
String username;
String managementType;
String kind;
String androidId;
String autoUpdatePolicy;
String productAvailabilityPolicy;
String productSetBehavior;
List<EnterpriseApp> apps;
public String getProductSetBehavior() {
return productSetBehavior;
}
public void setProductSetBehavior(String productSetBehavior) {
this.productSetBehavior = productSetBehavior;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getManagementType() {
return managementType;
}
public void setManagementType(String managementType) {
this.managementType = managementType;
}
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getAndroidId() {
return androidId;
}
public void setAndroidId(String androidId) {
this.androidId = androidId;
}
public String getAutoUpdatePolicy() {
return autoUpdatePolicy;
}
public void setAutoUpdatePolicy(String autoUpdatePolicy) {
this.autoUpdatePolicy = autoUpdatePolicy;
}
public String getProductAvailabilityPolicy() {
return productAvailabilityPolicy;
}
public void setProductAvailabilityPolicy(String productAvailabilityPolicy) {
this.productAvailabilityPolicy = productAvailabilityPolicy;
}
public List<EnterpriseApp> getApps() {
return apps;
}
public void setApps(List<EnterpriseApp> apps) {
this.apps = apps;
}
}

@ -0,0 +1,50 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.bean.wrapper;
public class EnterpriseUser {
String token;
String emmDeviceIdentifier;
String androidPlayDeviceId;
public String getEmmDeviceIdentifier() {
return emmDeviceIdentifier;
}
public void setEmmDeviceIdentifier(String emmDeviceIdentifier) {
this.emmDeviceIdentifier = emmDeviceIdentifier;
}
public String getAndroidPlayDeviceId() {
return androidPlayDeviceId;
}
public void setAndroidPlayDeviceId(String androidPlayDeviceId) {
this.androidPlayDeviceId = androidPlayDeviceId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

@ -0,0 +1,14 @@
package org.wso2.carbon.mdm.services.android.bean.wrapper;
public class TokenWrapper {
String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

@ -0,0 +1,357 @@
/*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://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.mdm.services.android.common;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.androidenterprise.AndroidEnterprise;
import com.google.api.services.androidenterprise.AndroidEnterpriseScopes;
import com.google.api.services.androidenterprise.model.AdministratorWebToken;
import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpec;
import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecManagedConfigurations;
import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecPlaySearch;
import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecPrivateApps;
import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecStoreBuilder;
import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecWebApps;
import com.google.api.services.androidenterprise.model.AuthenticationToken;
import com.google.api.services.androidenterprise.model.Device;
import com.google.api.services.androidenterprise.model.Install;
import com.google.api.services.androidenterprise.model.LocalizedText;
import com.google.api.services.androidenterprise.model.ProductSet;
import com.google.api.services.androidenterprise.model.ProductsListResponse;
import com.google.api.services.androidenterprise.model.StoreCluster;
import com.google.api.services.androidenterprise.model.StoreLayout;
import com.google.api.services.androidenterprise.model.StoreLayoutClustersListResponse;
import com.google.api.services.androidenterprise.model.StoreLayoutPagesListResponse;
import com.google.api.services.androidenterprise.model.StorePage;
import com.google.api.services.androidenterprise.model.User;
import com.google.common.collect.ImmutableList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.mobile.android.impl.EnterpriseServiceException;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseStoreCluster;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseStorePackages;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseStorePage;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseTokenUrl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class GoogleAPIInvoker {
private static final Log log = LogFactory.getLog(GoogleAPIInvoker.class);
private String esa;
public GoogleAPIInvoker(String esa) {
this.esa = esa;
}
private GoogleAPIInvoker(){}
public String insertUser(String enterpriseId, String username) throws EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
User user = new User();
user.setAccountIdentifier(username);
user.setDisplayName(username);
user.setAccountType("userAccount");
user.setManagementType("emmManaged");
try {
User addedUser = androidEnterprise.users().insert(enterpriseId, user)
.execute();
return addedUser.getId();
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
}
public String getToken(String enterpriseId, String userId) throws EnterpriseServiceException{
AndroidEnterprise androidEnterprise = getEnterpriseClient();
try {
AuthenticationToken tokenResponse = androidEnterprise.users()
.generateAuthenticationToken(enterpriseId, userId).execute();
return tokenResponse.getToken();
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs getToken";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
}
public Device updateAppsForUser(String enterpriseId, String userId , Device device) throws
EnterpriseServiceException{
AndroidEnterprise androidEnterprise = getEnterpriseClient();
try {
Device deviceResponse = androidEnterprise.devices().update(enterpriseId,
userId, device.getAndroidId(), device)
.execute();
return deviceResponse;
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs installApps";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
}
public Install installApps(String enterpriseId, String userId , String deviceId, String productId) throws
EnterpriseServiceException{
AndroidEnterprise androidEnterprise = getEnterpriseClient();
try {
Install install = new Install();
install.setKind("androidenterprise#install");
install.setProductId(productId);
return androidEnterprise.installs().update(enterpriseId, userId, deviceId, productId, install).execute();
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs installApps";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
}
public void uninstallApps(String enterpriseId, String userId , String deviceId, String productId) throws
EnterpriseServiceException{
AndroidEnterprise androidEnterprise = getEnterpriseClient();
try {
androidEnterprise.installs().delete(enterpriseId, userId, deviceId, productId).execute();
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs installApps";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
}
public void approveAppsForUser(String enterpriseId, String userId , List<String> products, String approvalType)
throws EnterpriseServiceException{
AndroidEnterprise androidEnterprise = getEnterpriseClient();
try {
ProductSet productSet = new ProductSet();
productSet.setKind("androidenterprise#productSet");
productSet.setProductId(products);
productSet.setProductSetBehavior(approvalType);
androidEnterprise.users().setAvailableProductSet(enterpriseId, userId, productSet).execute();
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs approveAppsForUser";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
}
public String getAdministratorWebToken(EnterpriseTokenUrl enterpriseTokenUrl) throws EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
AdministratorWebTokenSpec tokenSpec = new AdministratorWebTokenSpec();
tokenSpec.setParent(enterpriseTokenUrl.getParentHost());
tokenSpec.setPlaySearch(new AdministratorWebTokenSpecPlaySearch()
.setApproveApps(enterpriseTokenUrl.isApproveApps())
.setEnabled(enterpriseTokenUrl.isSearchEnabled()));
tokenSpec.setPrivateApps(new AdministratorWebTokenSpecPrivateApps()
.setEnabled(enterpriseTokenUrl.isPrivateAppsEnabled()));
tokenSpec.setWebApps(new AdministratorWebTokenSpecWebApps().setEnabled(enterpriseTokenUrl.isWebAppEnabled()));
tokenSpec.setStoreBuilder(new AdministratorWebTokenSpecStoreBuilder()
.setEnabled(enterpriseTokenUrl.isOrganizeAppPageVisible()));
tokenSpec.setManagedConfigurations(new AdministratorWebTokenSpecManagedConfigurations()
.setEnabled(enterpriseTokenUrl.isManagedConfigEnabled()));
try {
AdministratorWebToken token = androidEnterprise.enterprises()
.createWebToken(enterpriseTokenUrl.getEnterpriseId(), tokenSpec).execute();
return token.getToken();
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs installApps";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
}
public ProductsListResponse listProduct(String enterpriseId, String token) throws EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
try {
if (token == null) {
return androidEnterprise.products().list(enterpriseId).setMaxResults(100l).setApproved(true).execute();
} else {
return androidEnterprise.products().list(enterpriseId).setMaxResults(100l).setToken(token)
.setApproved(true).execute();
}
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs installApps";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
}
public String insertPage(String enterpriseId, EnterpriseStorePage storePage) throws IOException,
EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
List<LocalizedText> names =
ImmutableList.of(new LocalizedText().setLocale(storePage.getLocale()).setText(storePage.getPageName()));
StorePage page = new StorePage();
page.setName(names);
return androidEnterprise.storelayoutpages().insert(enterpriseId, page).execute().getId();
}
public String updatePage(String enterpriseId, EnterpriseStorePage storePage) throws IOException,
EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
List<LocalizedText> names =
ImmutableList.of(new LocalizedText().setLocale(storePage.getLocale()).setText(storePage.getPageName()));
StorePage page = new StorePage();
page.setName(names);
page.setLink(storePage.getLinks());
return androidEnterprise.storelayoutpages().update(enterpriseId, storePage.getPageId(), page).execute().getId();
}
public void deletePage(String enterpriseId, String pageId) throws IOException,
EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
androidEnterprise.storelayoutpages().delete(enterpriseId, pageId).execute();
}
public StoreLayoutPagesListResponse listPages(String enterpriseId) throws IOException,
EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
return androidEnterprise.storelayoutpages().list(enterpriseId).execute();
}
public StoreLayout setStoreLayout(String enterpriseId, String homepageId)
throws EnterpriseServiceException, IOException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
StoreLayout storeLayout = new StoreLayout();
storeLayout.setStoreLayoutType("custom");
storeLayout.setHomepageId(homepageId);
return androidEnterprise
.enterprises()
.setStoreLayout(enterpriseId, storeLayout)
.execute();
}
public String insertCluster(String enterpriseId, EnterpriseStoreCluster storeCluster) throws IOException ,
EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
StoreCluster cluster = new StoreCluster();
List<LocalizedText> names =
ImmutableList.of(new LocalizedText().setLocale("en").setText(storeCluster.getName()));
cluster.setName(names);
List<String> productIds = new ArrayList<>();
for (EnterpriseStorePackages packages : storeCluster.getProducts()) {
productIds.add(packages.getPackageId());
}
cluster.setProductId(productIds);
cluster.setOrderInPage(storeCluster.getOrderInPage());
return androidEnterprise.storelayoutclusters()
.insert(enterpriseId, storeCluster.getPageId(), cluster)
.execute()
.getId();
}
public String updateCluster(String enterpriseId, EnterpriseStoreCluster storeCluster) throws IOException ,
EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
StoreCluster cluster = new StoreCluster();
List<LocalizedText> names =
ImmutableList.of(new LocalizedText().setLocale("en").setText(storeCluster.getName()));
cluster.setName(names);
List<String> productIds = new ArrayList<>();
for (EnterpriseStorePackages packages : storeCluster.getProducts()) {
productIds.add(packages.getPackageId());
}
cluster.setProductId(productIds);
cluster.setOrderInPage(storeCluster.getOrderInPage());
cluster.setId(storeCluster.getClusterId());
return androidEnterprise.storelayoutclusters()
.update(enterpriseId, storeCluster.getPageId(), storeCluster.getClusterId(), cluster)
.execute()
.getId();
}
public StoreLayoutClustersListResponse getClusters(String enterpriseId, String pageId)
throws IOException, EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
return androidEnterprise.storelayoutclusters().list(enterpriseId, pageId).execute();
}
public void deleteCluster(String enterpriseId, String pageId, String clusterId)
throws IOException, EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
androidEnterprise.storelayoutclusters().delete(enterpriseId, pageId, clusterId).execute();
}
// Update the pages to include quick links to other pages.
public void addLinks(String enterpriseId, String pageId, List<String> links)
throws IOException , EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
androidEnterprise.storelayoutpages()
.patch(enterpriseId, pageId, new StorePage().setLink(links)).execute();
}
public StoreLayout getStoreLayout(String enterpriseId)
throws IOException, EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
return androidEnterprise
.enterprises()
.getStoreLayout(enterpriseId)
.execute();
}
public void unenroll(String enterpriseId)
throws IOException, EnterpriseServiceException {
AndroidEnterprise androidEnterprise = getEnterpriseClient();
// androidEnterprise.enterprises().unenroll(enterpriseId).execute();
}
private AndroidEnterprise getEnterpriseClient() throws EnterpriseServiceException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
InputStream inputStream = new ByteArrayInputStream(esa.getBytes(StandardCharsets.UTF_8));
final Credential credential;
try {
credential = GoogleCredential.fromStream(inputStream, httpTransport, jsonFactory)
.createScoped(AndroidEnterpriseScopes.all());
} catch (IOException e) {
String msg = "Error occurred while accessing Google APIs";
log.error(msg, e);
throw new EnterpriseServiceException(msg, e);
}
HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
credential.initialize(request);
}
};
return new AndroidEnterprise.Builder(httpTransport, jsonFactory, httpRequestInitializer)
.build();
}
}

@ -156,6 +156,12 @@ import java.util.List;
key = "perm:android:reboot",
permissions = {"/device-mgt/devices/owning-device/operations/android/reboot"}
),
@Scope(
name = "Change LockTask mode",
description = "Change LoockTask mode of KIOSK devices",
key = "perm:android:change-LockTask",
permissions = {"/device-mgt/devices/owning-device/operations/android/change-LockTask"}
),
@Scope(
name = "Mute Device",
description = "Mute Android devices",
@ -1055,6 +1061,66 @@ public interface DeviceManagementAdminService {
required = true)
List<String> deviceIDs);
@POST
@Path("/change-LockTask")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Change LockTask mode of KIOSK Devices",
notes = "Enable or disable LockTask mode of KIOSK devices.",
response = Activity.class,
tags = "Android Device Management Administrative Service",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:change-LockTask")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 201,
message = "Created. \n Successfully scheduled the change LockTask operation.",
response = Activity.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "URL of the activity instance that refers to the scheduled operation."),
@ResponseHeader(
name = "Content-Type",
description = "Content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 303,
message = "See Other. \n The source can be retrieved from the URL specified in the location header.\n",
responseHeaders = {
@ResponseHeader(
name = "Content-Location",
description = "The Source URL of the document.")}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error."),
@ApiResponse(
code = 415,
message = "Unsupported media type. \n The format of the requested entity was not supported.\n"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while adding the new change LockTask operation.")
})
Response changeLockTask(
@ApiParam(
name = "deviceIDs",
value = "Provide the ID of the Android device. Multiple device IDs can be added using comma separated values. ",
required = true)
List<String> deviceIDs);
@POST
@Path("/mute")
@ApiOperation(

@ -209,6 +209,11 @@ public interface DeviceManagementService {
message = "Internal Server Error. \n Server error occurred while fetching the list of pending operations.")
})
Response getPendingOperations(
@ApiParam(
name = "disableGoogleApps",
value = "Specifically disable having Google apps installed.",
required = false)
@QueryParam("disableGoogleApps") boolean disableGoogleApps,
@ApiParam(
name = "id",
value = "The unique device identifier.",

@ -0,0 +1,817 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.services.impl;
import com.google.api.services.androidenterprise.model.AppRestrictionsSchema;
import com.google.api.services.androidenterprise.model.ProductsListResponse;
import com.google.api.services.androidenterprise.model.StoreCluster;
import com.google.api.services.androidenterprise.model.StoreLayout;
import com.google.api.services.androidenterprise.model.StoreLayoutClustersListResponse;
import com.google.api.services.androidenterprise.model.StoreLayoutPagesListResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationPolicyDTO;
import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
import org.wso2.carbon.device.mgt.mobile.android.impl.EnterpriseServiceException;
import org.wso2.carbon.device.mgt.mobile.android.impl.dto.AndroidEnterpriseManagedConfig;
import org.wso2.carbon.device.mgt.mobile.android.impl.dto.AndroidEnterpriseUser;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseConfigs;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseStoreCluster;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseStorePackages;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseStorePage;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseStorePageLinks;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseTokenUrl;
import org.wso2.carbon.mdm.services.android.bean.ErrorResponse;
import org.wso2.carbon.mdm.services.android.bean.GoogleAppSyncResponse;
import org.wso2.carbon.mdm.services.android.bean.wrapper.EnterpriseApp;
import org.wso2.carbon.mdm.services.android.bean.wrapper.EnterpriseInstallPolicy;
import org.wso2.carbon.mdm.services.android.bean.wrapper.EnterpriseUser;
import org.wso2.carbon.mdm.services.android.bean.wrapper.TokenWrapper;
import org.wso2.carbon.mdm.services.android.common.GoogleAPIInvoker;
import org.wso2.carbon.mdm.services.android.exception.BadRequestException;
import org.wso2.carbon.mdm.services.android.exception.NotFoundException;
import org.wso2.carbon.mdm.services.android.services.AndroidEnterpriseService;
import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils;
import org.wso2.carbon.mdm.services.android.util.AndroidConstants;
import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils;
import org.wso2.carbon.mdm.services.android.util.AndroidEnterpriseUtils;
import org.wso2.carbon.policy.mgt.common.FeatureManagementException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Path("/enterprise")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class AndroidEnterpriseServiceImpl implements AndroidEnterpriseService {
private static final Log log = LogFactory.getLog(AndroidEnterpriseServiceImpl.class);
@Override
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@POST
@Path("/user")
public Response addUser(EnterpriseUser enterpriseUser) {
if (enterpriseUser == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build())
.build();
} else if (enterpriseUser.getEmmDeviceIdentifier() == null || enterpriseUser.getEmmDeviceIdentifier().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("EMM ID is incorrect").build())
.build();
} else if (enterpriseUser.getAndroidPlayDeviceId() == null || enterpriseUser.getAndroidPlayDeviceId().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Google Play ID is incorrect").build())
.build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
String token;
boolean deviceIdExist = false;
try {
String googleUserId;
List<AndroidEnterpriseUser> androidEnterpriseUsers = AndroidAPIUtils.getAndroidPluginService()
.getEnterpriseUser(CarbonContext.getThreadLocalCarbonContext().getUsername());
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
if (androidEnterpriseUsers != null && androidEnterpriseUsers.size() > 0) {
googleUserId = androidEnterpriseUsers.get(0).getGoogleUserId();
// If this device is also present, only need to provide a token for this request.
for (AndroidEnterpriseUser enterprise : androidEnterpriseUsers) {
if (enterprise.getEmmDeviceId() != null
&& enterprise.getEmmDeviceId().equals(enterpriseUser.getAndroidPlayDeviceId())) {
deviceIdExist = true;
}
}
} else {
googleUserId = googleAPIInvoker.insertUser(enterpriseConfigs.getEnterpriseId(), CarbonContext
.getThreadLocalCarbonContext()
.getUsername());
}
// Fetching an auth token from Google EMM API
token = googleAPIInvoker.getToken(enterpriseConfigs.getEnterpriseId(), googleUserId);
if (!deviceIdExist) {
AndroidEnterpriseUser androidEnterpriseUser = new AndroidEnterpriseUser();
androidEnterpriseUser.setEmmUsername(CarbonContext.getThreadLocalCarbonContext().getUsername());
androidEnterpriseUser.setTenantId(CarbonContext.getThreadLocalCarbonContext().getTenantId());
androidEnterpriseUser.setAndroidPlayDeviceId(enterpriseUser.getAndroidPlayDeviceId());
androidEnterpriseUser.setEnterpriseId(enterpriseConfigs.getEnterpriseId());
androidEnterpriseUser.setEmmDeviceId(enterpriseUser.getEmmDeviceIdentifier());
androidEnterpriseUser.setGoogleUserId(googleUserId);
AndroidAPIUtils.getAndroidPluginService().addEnterpriseUser(androidEnterpriseUser);
}
if (token == null) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching token").build())
.build();
}
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving user").build()).build();
}
return Response.status(Response.Status.OK).entity(token).build();
}
@Override
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@POST
@Path("/available-app")
public Response updateUser(EnterpriseInstallPolicy device) {
boolean sentToDevice = false;
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
try {
List<AndroidEnterpriseUser> enterpriseUserInstances = AndroidAPIUtils.getAndroidPluginService()
.getEnterpriseUser(device.getUsername());
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
for (AndroidEnterpriseUser userDetail : enterpriseUserInstances) {
if (userDetail.getEnterpriseId() != null && !userDetail.getEnterpriseId().isEmpty() && userDetail
.getEmmUsername() != null && userDetail.getEmmUsername().equals(device.getUsername())
&& device.getAndroidId().equals(userDetail.getAndroidPlayDeviceId())) {
googleAPIInvoker.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(),
AndroidEnterpriseUtils.convertToDeviceInstance(device));
sentToDevice = true;
}
}
} catch (EnterpriseServiceException e) {
String errorMessage = "App install failed. No user found for name " + device.getUsername();
log.error(errorMessage);
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage(errorMessage).build());
}
if (sentToDevice) {
return Response.status(Response.Status.OK).build();
} else {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Could not install on the device of user "
+ device.getUsername()).build()).build();
}
}
@Override
@GET
@Path("/store-url")
public Response getStoreUrl(@QueryParam("approveApps") boolean approveApps,
@QueryParam("searchEnabled") boolean searchEnabled,
@QueryParam("isPrivateAppsEnabled") boolean isPrivateAppsEnabled,
@QueryParam("isWebAppEnabled") boolean isWebAppEnabled,
@QueryParam("isOrganizeAppPageVisible") boolean isOrganizeAppPageVisible,
@QueryParam("isManagedConfigEnabled") boolean isManagedConfigEnabled,
@QueryParam("host") String host) {
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
EnterpriseTokenUrl enterpriseTokenUrl = new EnterpriseTokenUrl();
if (enterpriseConfigs == null || enterpriseConfigs.getEnterpriseId() == null) {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Not configured for AFW").build()).build();
}
enterpriseTokenUrl.setEnterpriseId(enterpriseConfigs.getEnterpriseId());
enterpriseTokenUrl.setApproveApps(approveApps);
enterpriseTokenUrl.setSearchEnabled(searchEnabled);
enterpriseTokenUrl.setPrivateAppsEnabled(isPrivateAppsEnabled);
enterpriseTokenUrl.setWebAppEnabled(isWebAppEnabled);
enterpriseTokenUrl.setOrganizeAppPageVisible(isOrganizeAppPageVisible);
enterpriseTokenUrl.setParentHost(host);
enterpriseTokenUrl.setManagedConfigEnabled(isManagedConfigEnabled);
try {
String token = googleAPIInvoker.getAdministratorWebToken(enterpriseTokenUrl);
TokenWrapper tokenWrapper = new TokenWrapper();
tokenWrapper.setToken(token);
return Response.status(Response.Status.OK).entity(tokenWrapper).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when calling get web token").build())
.build();
}
}
@Override
@GET
@Path("/products/sync")
public Response syncApps() {
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
ProductsListResponse productsListResponse = googleAPIInvoker
.listProduct(enterpriseConfigs.getEnterpriseId(), null);
AndroidEnterpriseUtils.persistApp(productsListResponse);
int total = productsListResponse.getProduct().size()
+ recursiveSync(googleAPIInvoker, enterpriseConfigs.getEnterpriseId(), productsListResponse);
GoogleAppSyncResponse appSyncResponse = new GoogleAppSyncResponse();
appSyncResponse.setTotalApps(total);
return Response.status(Response.Status.OK).entity(appSyncResponse).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when calling sync").build())
.build();
} catch (ApplicationManagementException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when persisting app").build())
.build();
}
}
private int recursiveSync(GoogleAPIInvoker googleAPIInvoker, String enterpriseId, ProductsListResponse
productsListResponse) throws EnterpriseServiceException, ApplicationManagementException {
// Are there more pages
if (productsListResponse == null || productsListResponse.getTokenPagination() == null
|| productsListResponse.getTokenPagination().getNextPageToken() == null) {
return 0;
}
// Get next page
ProductsListResponse productsListResponseNext = googleAPIInvoker.listProduct(enterpriseId,
productsListResponse.getTokenPagination().getNextPageToken());
AndroidEnterpriseUtils.persistApp(productsListResponseNext);
if (productsListResponseNext != null && productsListResponseNext.getTokenPagination() != null &&
productsListResponseNext.getTokenPagination().getNextPageToken() != null) {
return recursiveSync(googleAPIInvoker, enterpriseId, productsListResponseNext)
+ productsListResponseNext.getProduct().size();
} else {
return productsListResponseNext.getProduct().size();
}
}
@POST
@Path("/store-layout/page")
@Override
public Response addPage(EnterpriseStorePage page) {
if (page == null || page.getPageName() == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build())
.build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
String id = googleAPIInvoker.insertPage(enterpriseConfigs.getEnterpriseId(), page);
page.setPageId(id);
return Response.status(Response.Status.OK).entity(page).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when inserting page "
+ page.getPageName()).build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when inserting page "
+ page.getPageName() + " , due to an error with ESA").build() ).build();
}
}
@PUT
@Path("/store-layout/page")
@Override
public Response updatePage(EnterpriseStorePage page) {
if (page == null || page.getPageName() == null || page.getPageId() == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build())
.build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
String id = googleAPIInvoker.updatePage(enterpriseConfigs.getEnterpriseId(), page);
page.setPageId(id);
return Response.status(Response.Status.OK).entity(page).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating page "
+ page.getPageName()).build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating page "
+ page.getPageName() + " , due to an error with ESA").build()).build();
}
}
@DELETE
@Path("/store-layout/page/{id}")
@Consumes(MediaType.WILDCARD)
@Override
public Response deletePage(@PathParam("id") String id) {
if (id == null || id.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Page Id cannot be empty").build())
.build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
googleAPIInvoker.deletePage(enterpriseConfigs.getEnterpriseId(), id);
return Response.status(Response.Status.OK).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when deleting page "
+ id).build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating page "
+ id + " , Due to an error with ESA").build()).build();
}
}
@GET
@Path("/store-layout/page")
@Override
public Response getPages() {
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
StoreLayoutPagesListResponse pages = googleAPIInvoker.listPages(enterpriseConfigs.getEnterpriseId());
return Response.status(Response.Status.OK).entity(pages).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching all pages").build())
.build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching page "
+ " , Due to an error with ESA").build()).build();
}
}
@PUT
@Path("/store-layout/home-page/{id}")
@Override
public Response setHome(@PathParam("id") String id) {
if (id == null || id.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Id cannot be empty").build())
.build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
StoreLayout layout = googleAPIInvoker.setStoreLayout(enterpriseConfigs.getEnterpriseId(), id);
return Response.status(Response.Status.OK).entity(layout).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when inserting home page "
+ id).build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when inserting home page "
+ id + " , due to an error with ESA").build() ).build();
}
}
@GET
@Path("/store-layout/home-page")
@Override
public Response getHome() {
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
StoreLayout layout = googleAPIInvoker.getStoreLayout(enterpriseConfigs.getEnterpriseId());
return Response.status(Response.Status.OK).entity(layout).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching home page").build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching home page.").build() )
.build();
}
}
@POST
@Path("/store-layout/cluster")
@Override
public Response addCluster(EnterpriseStoreCluster storeCluster) {
if (storeCluster == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build())
.build();
} else if (storeCluster.getName() == null || storeCluster.getName().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster name cannot be empty").build()).build();
} else if (storeCluster.getProducts() == null || storeCluster.getProducts().size() < 0) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Products cannot be empty").build()).build();
} else if (storeCluster.getOrderInPage() == null || storeCluster.getOrderInPage().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster order cannot be empty").build()).build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
String id = googleAPIInvoker.insertCluster(enterpriseConfigs.getEnterpriseId(), storeCluster);
storeCluster.setClusterId(id);
return Response.status(Response.Status.OK).entity(storeCluster).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating cluster "
+ storeCluster.getName()).build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating cluster "
+ storeCluster.getName() + " , due to an error with ESA").build()).build();
}
}
@PUT
@Path("/store-layout/cluster")
@Override
public Response updatePage(EnterpriseStoreCluster storeCluster) {
if (storeCluster == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build())
.build();
} else if (storeCluster.getName() == null || storeCluster.getName().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster name cannot be empty").build()).build();
} else if (storeCluster.getProducts() == null || storeCluster.getProducts().size() < 0) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Products cannot be empty").build()).build();
} else if (storeCluster.getOrderInPage() == null || storeCluster.getOrderInPage().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster order cannot be empty").build()).build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
String id = googleAPIInvoker.updateCluster(enterpriseConfigs.getEnterpriseId(), storeCluster);
storeCluster.setClusterId(id);
return Response.status(Response.Status.OK).entity(storeCluster).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating cluster "
+ storeCluster.getName()).build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating cluster "
+ storeCluster.getName() + " , due to an error with ESA").build()).build();
}
}
@DELETE
@Path("/store-layout/cluster/{clusterId}/page/{pageId}")
@Consumes(MediaType.WILDCARD)
@Override
public Response deleteCluster( @PathParam("clusterId") String clusterId, @PathParam("pageId") String pageId) {
if (clusterId == null || clusterId.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster id cannot be empty").build()).build();
} else if (pageId == null || pageId.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Page id cannot be empty").build()).build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
googleAPIInvoker.deleteCluster(enterpriseConfigs.getEnterpriseId(), pageId, clusterId);
return Response.status(Response.Status.OK).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when deleting cluster "
+ clusterId).build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when deleting cluster "
+ clusterId + " , due to an error with ESA").build()).build();
}
}
@GET
@Path("/store-layout/page/{pageId}/clusters")
@Override
public Response getClustersInPage(@PathParam("pageId") String pageId) {
if (pageId == null || pageId.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Page id cannot be empty").build()).build();
}
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
StoreLayoutClustersListResponse response = googleAPIInvoker.getClusters(enterpriseConfigs.getEnterpriseId(), pageId);
if (response == null || response.getCluster() == null) {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Page id cannot be found").build()).build();
}
List<EnterpriseStoreCluster> clusters = new ArrayList<>();
for (StoreCluster cluster : response.getCluster()) {
EnterpriseStoreCluster storeCluster = new EnterpriseStoreCluster();
storeCluster.setClusterId(cluster.getId());
storeCluster.setName(cluster.getName().get(0).getText());
storeCluster.setOrderInPage(cluster.getOrderInPage());
List<String> productIds = new ArrayList<>();
for (String productId : cluster.getProductId()) {
String trimmedPackage = productId.replaceFirst("app:", "");
productIds.add(trimmedPackage);
}
ApplicationManager appManager = AndroidEnterpriseUtils.getAppManagerServer();
List<ApplicationReleaseDTO> packageDetails = appManager.getReleaseByPackageNames(productIds);
List<EnterpriseStorePackages> enterpriseStorePackages = new ArrayList<>();
for (String productId : cluster.getProductId()) {
String trimmedPackage = productId.replaceFirst("app:", "");
EnterpriseStorePackages storePackages = new EnterpriseStorePackages();
storePackages.setPackageId(productId);
for (ApplicationReleaseDTO releaseDTO : packageDetails) {
if (releaseDTO.getPackageName().equalsIgnoreCase(trimmedPackage)) {
storePackages.setIconUrl(releaseDTO.getIconName());
break;
}
}
enterpriseStorePackages.add(storePackages);
}
storeCluster.setProducts(enterpriseStorePackages);
clusters.add(storeCluster);
}
return Response.status(Response.Status.OK).entity(clusters).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching clusters in pageId "
+ pageId).build()).build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching clusters in pageId "
+ pageId + " , due to an error with ESA").build()).build();
} catch (ApplicationManagementException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching all details in PageId "
+ pageId).build()).build();
}
}
@PUT
@Path("/store-layout/page-link")
@Override
public Response updateLinks(EnterpriseStorePageLinks link) {
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
googleAPIInvoker.addLinks(enterpriseConfigs.getEnterpriseId(),
link.getPageId(), link.getLinks());
return Response.status(Response.Status.OK).build();
} catch (IOException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching all pages").build())
.build();
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching page "
+ " , Due to an error with ESA").build()).build();
}
}
@Override
@Produces(MediaType.APPLICATION_JSON)
@GET
@Path("/managed-configs/package/{packageName}")
public Response getConfig(@PathParam("packageName") String packageName) {
if (packageName== null || packageName.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Package name is incorrect").build()).build();
}
AndroidEnterpriseManagedConfig managedConfig;
try {
managedConfig = AndroidAPIUtils.getAndroidPluginService().getConfigByPackageName(packageName);
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs").build()).build();
}
return Response.status(Response.Status.OK).entity(managedConfig).build();
}
@Override
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@POST
@Path("/managed-configs")
public Response addManagedConfigs(AndroidEnterpriseManagedConfig managedConfig) {
if (managedConfig == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build())
.build();
} else if (managedConfig.getPackageName() == null || managedConfig.getPackageName().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Package name is incorrect").build()).build();
} else if (managedConfig.getProfileName() == null || managedConfig.getProfileName().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Profile name is incorrect").build()).build();
}
try {
AndroidAPIUtils.getAndroidPluginService().addConfig(managedConfig);
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs for "
+ managedConfig.getPackageName()).build()).build();
}
return Response.status(Response.Status.CREATED).build();
}
@Override
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@PUT
@Path("/managed-configs")
public Response updateManagedConfigs(AndroidEnterpriseManagedConfig managedConfig) {
if (managedConfig == null) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build())
.build();
} else if (managedConfig.getProfileName() == null || managedConfig.getProfileName().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Profile name is incorrect").build()).build();
}
try {
AndroidAPIUtils.getAndroidPluginService().updateMobileDevice(managedConfig);
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs").build()).build();
}
return Response.status(Response.Status.CREATED).build();
}
@Override
@DELETE
@Path("/managed-configs/mcm/{mcmId}")
@Consumes(MediaType.WILDCARD)
public Response deleteManagedConfigs(@PathParam("mcmId") String mcmId) {
if (mcmId == null || mcmId.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("MCM Id is incorrect").build()).build();
}
try {
AndroidAPIUtils.getAndroidPluginService().deleteMobileDevice(mcmId);
} catch (EnterpriseServiceException e) {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs").build()).build();
}
return Response.status(Response.Status.OK).build();
}
@Override
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@POST
@Path("/change-app")
public Response updateUser(ApplicationPolicyDTO applicationPolicyDTO) {
boolean sentToDevice = false;
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
for (DeviceIdentifier deviceIdentifier : applicationPolicyDTO.getDeviceIdentifierList()) {
try {
AndroidEnterpriseUser userDetail = AndroidAPIUtils.getAndroidPluginService()
.getEnterpriseUserByDevice(deviceIdentifier.getId());
if (userDetail != null && userDetail.getEnterpriseId() != null && !userDetail.getEnterpriseId()
.isEmpty() && userDetail.getEmmUsername() != null) {
if (applicationPolicyDTO.getAction().equals(AndroidConstants.ApplicationInstall.INSTALL)) {
if (applicationPolicyDTO.getPolicy() == null) {
ProfileFeature feature = AndroidDeviceUtils.getEnrollmentFeature(deviceIdentifier);
EnterpriseInstallPolicy enterpriseInstallPolicy = AndroidEnterpriseUtils
.getDeviceAppPolicy(null, feature, userDetail);
List<String> apps = new ArrayList<>();
boolean isAppWhitelisted = false;
for (EnterpriseApp enterpriseApp : enterpriseInstallPolicy.getApps()) {
apps.add(enterpriseApp.getProductId());
String packageName = enterpriseApp.getProductId().replace("app:", "");
if (applicationPolicyDTO.getApplicationDTO().getPackageName().equals(packageName)) {
isAppWhitelisted = true;
}
}
if (enterpriseInstallPolicy.getProductSetBehavior().equals(AndroidConstants
.ApplicationInstall.BEHAVIOUR_WHITELISTED_APPS_ONLY)) {
// This app can only be installed if the app is approved by whitelist to user.
if (!isAppWhitelisted) {
String errorMessage = "App: " + applicationPolicyDTO.getApplicationDTO()
.getPackageName() + " for device " + deviceIdentifier.getId();
log.error(errorMessage);
throw new BadRequestException(
new ErrorResponse.ErrorResponseBuilder().setCode(Response.Status.BAD_REQUEST
.getStatusCode()).setMessage(errorMessage).build());
}
}
googleAPIInvoker.installApps(enterpriseConfigs.getEnterpriseId(), userDetail
.getGoogleUserId(), userDetail.getAndroidPlayDeviceId(), "app:" +
applicationPolicyDTO.getApplicationDTO().getPackageName());
sentToDevice = true;
}
} else if (applicationPolicyDTO.getAction().equals(AndroidConstants.ApplicationInstall.UNINSTALL)) {
googleAPIInvoker.uninstallApps(enterpriseConfigs.getEnterpriseId(), userDetail
.getGoogleUserId(), userDetail.getAndroidPlayDeviceId(), "app:" +
applicationPolicyDTO.getApplicationDTO().getPackageName());
sentToDevice = true;
}
}
} catch (EnterpriseServiceException e) {
String errorMessage = "App install failed for device " + deviceIdentifier.getId();
log.error(errorMessage);
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(Response.Status.NOT_FOUND
.getStatusCode()).setMessage(errorMessage).build());
} catch (FeatureManagementException e) {
String errorMessage = "Could not fetch effective policy for device " + deviceIdentifier.getId();
log.error(errorMessage);
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(Response.Status.INTERNAL_SERVER_ERROR
.getStatusCode()).setMessage(errorMessage).build());
}
}
if (sentToDevice) {
return Response.status(Response.Status.OK).build();
} else {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Could not install on the device of user "
).build()).build();
}
}
@PUT
@Path("/{id}/unenroll")
@Override
public Response unenroll() {
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs();
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
try {
googleAPIInvoker.unenroll(enterpriseConfigs.getEnterpriseId());
} catch (IOException e) {
String errorMessage = "Could not unenroll the enterprise " + enterpriseConfigs.getEnterpriseId();
log.error(errorMessage);
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(Response.Status.INTERNAL_SERVER_ERROR
.getStatusCode()).setMessage(errorMessage).build());
} catch (EnterpriseServiceException e) {
String errorMessage = "Could not get client to call Google to unenroll enterprise " + enterpriseConfigs.getEnterpriseId();
log.error(errorMessage);
throw new NotFoundException(
new ErrorResponse.ErrorResponseBuilder().setCode(Response.Status.INTERNAL_SERVER_ERROR
.getStatusCode()).setMessage(errorMessage).build());
}
return Response.status(Response.Status.OK).build();
}
}

@ -37,8 +37,8 @@ package org.wso2.carbon.mdm.services.android.services.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
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;
@ -500,6 +500,33 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
}
}
@POST
@Path("/change-LockTask")
@Override
public Response changeLockTask(List<String> deviceIDs) {
if (log.isDebugEnabled()) {
log.debug("Invoking Android change LockTask mode operation");
}
try {
CommandOperation operation = new CommandOperation();
operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_TASK_MODE);
operation.setType(Operation.Type.COMMAND);
Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation);
return Response.status(Response.Status.CREATED).entity(activity).build();
} catch (InvalidDeviceException e) {
String errorMessage = "Invalid Device Identifiers found.";
log.error(errorMessage, e);
throw new BadRequestException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build());
} catch (OperationManagementException e) {
String errorMessage = "Issue in retrieving operation management service instance";
log.error(errorMessage, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build());
}
}
@POST
@Path("/mute")
@Override

@ -34,16 +34,17 @@
*/
package org.wso2.carbon.mdm.services.android.services.impl;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.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.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
@ -136,7 +137,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@PUT
@Path("/{id}/pending-operations")
@Override
public Response getPendingOperations(@PathParam("id") String id,
public Response getPendingOperations(@QueryParam("disableGoogleApps") boolean disableGoogleApps,
@PathParam("id") String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince,
List<? extends Operation> resultOperations) {
if (id == null || id.isEmpty()) {
@ -186,7 +188,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
List<? extends Operation> pendingOperations;
try {
pendingOperations = AndroidDeviceUtils.getPendingOperations(deviceIdentifier);
pendingOperations = AndroidDeviceUtils.getPendingOperations(deviceIdentifier, !disableGoogleApps);
} catch (OperationManagementException e) {
String msg = "Issue in retrieving operation management service instance";
log.error(msg, e);
@ -291,7 +293,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
for (ProfileFeature feature : effectiveProfileFeatures) {
if (AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE
.equals(feature.getFeatureCode())) {
AndroidDeviceUtils.installEnrollmentApplications(feature, deviceIdentifier.getId());
AndroidDeviceUtils.installEnrollmentApplications(feature, deviceIdentifier);
break;
}
}
@ -485,7 +487,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
throws DeviceManagementException {
DeviceLocation location = null;
String latitude = "", longitude = "";
String latitude = "", longitude = "", altitude = "", speed = "", bearing = "", distance = "";
if (properties == null) return null;
@ -494,17 +496,34 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
if (propertyName == null) continue;
if (propertyName.equals("LATITUDE")) {
latitude = property.getValue();
if (!longitude.isEmpty()) break;
} else if (propertyName.equals("LONGITUDE")) {
}
if (propertyName.equals("LONGITUDE")) {
longitude = property.getValue();
if (!latitude.isEmpty()) break;
}
if (propertyName.equals("ALTITUDE")) {
altitude = property.getValue();
}
if (propertyName.equals("SPEED")) {
speed = property.getValue();
}
if (propertyName.equals("BEARING")) {
bearing = property.getValue();
}
if (propertyName.equals("DISTANCE")) {
distance = property.getValue();
}
}
if (!latitude.isEmpty() && !longitude.isEmpty()) {
if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude) &&
StringUtils.isNotBlank(altitude) && StringUtils.isNotBlank(speed) &&
StringUtils.isNotBlank(bearing) && StringUtils.isNotBlank(distance)) {
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.setDeviceIdentifier(deviceIdentifier);
Device savedDevice = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false);
location.setDeviceId(savedDevice.getId());

@ -39,11 +39,11 @@ import org.wso2.carbon.base.ServerConfiguration;
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.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
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.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;

@ -26,8 +26,8 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.mdm.services.android.bean.DeviceState;
import org.wso2.carbon.mdm.services.android.bean.ErrorResponse;
@ -59,6 +59,10 @@ public class EventReceiverServiceImpl implements EventReceiverService {
private static final String LONGITUDE = "longitude";
private static final String LATITUDE = "latitude";
private static final String ALTITUDE = "altitude";
private static final String SPEED = "speed";
private static final String DISTANCE = "distance";
private static final String BEARING = "bearing";
private static final String TIME_STAMP = "timeStamp";
private static final String LOCATION_EVENT_TYPE = "location";
@ -100,7 +104,11 @@ public class EventReceiverServiceImpl implements EventReceiverService {
Object[] payload = {
jsonObject.get(TIME_STAMP).getAsLong(),
jsonObject.get(LATITUDE).getAsDouble(),
jsonObject.get(LONGITUDE).getAsDouble()
jsonObject.get(LONGITUDE).getAsDouble(),
jsonObject.get(ALTITUDE).getAsDouble(),
jsonObject.get(SPEED).getAsFloat(),
jsonObject.get(BEARING).getAsFloat(),
jsonObject.get(DISTANCE).getAsDouble()
};
try {
if (AndroidAPIUtils.getEventPublisherService().publishEvent(

@ -25,8 +25,8 @@ 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.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
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.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
@ -34,6 +34,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementExcept
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.AndroidPluginService;
import org.wso2.carbon.mdm.services.android.bean.ErrorResponse;
import org.wso2.carbon.mdm.services.android.exception.BadRequestException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
@ -54,6 +55,18 @@ public class AndroidAPIUtils {
throw new IllegalStateException("Utility class");
}
public static AndroidPluginService getAndroidPluginService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AndroidPluginService androidPluginService =
(AndroidPluginService) ctx.getOSGiService(AndroidPluginService.class, null);
if (androidPluginService == null) {
String msg = "Android plugin service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return androidPluginService;
}
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();

@ -62,6 +62,14 @@ public final class AndroidConstants {
public static final String APPLICATION_JSON = "application/json";
public static final String SCOPE = "scope";
public static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress";
public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname";
public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname";
public static final String USER_CLAIM_EMAIL_ADDRESS_PLACEHOLDER = "$email";
public static final String USER_CLAIM_FIRST_NAME_PLACEHOLDER = "$firstName";
public static final String USER_CLAIM_LAST_NAME_PLACEHOLDER = "$lastName";
public final class DeviceProperties {
private DeviceProperties() {
throw new AssertionError();
@ -129,8 +137,10 @@ public final class AndroidConstants {
public static final String ENCRYPT_STORAGE = "ENCRYPT_STORAGE";
public static final String DEVICE_RING = "DEVICE_RING";
public static final String DEVICE_REBOOT = "REBOOT";
public static final String CHANGE_LOCK_TASK_MODE = "CHANGE_LOCK_TASK_MODE";
public static final String UPGRADE_FIRMWARE = "UPGRADE_FIRMWARE";
public static final String NOTIFICATION = "NOTIFICATION";
public static final String POLICY_BUNDLE = "POLICY_BUNDLE";
public static final String WEBCLIP = "WEBCLIP";
public static final String DISENROLL = "DISENROLL";
public static final String MONITOR = "MONITOR";
@ -187,7 +197,9 @@ public final class AndroidConstants {
public static final String DEFAULT_TOKEN_TYPE = "PRODUCTION";
public static final String DEFAULT_VALIDITY_PERIOD = "3600";
public static final String SUBSCRIPTION_SCOPE = "appm:subscribe";
public static final String ENROLLMENT_APP_INSTALL_ID = "appId";
public static final String ENROLLMENT_APP_INSTALL_UUID = "uuid";
public static final String ENROLLMENT_APP_INSTALL_APP_ID = "appId";
public static final String GOOGLE_POLICY_PAYLOAD = "installGooglePolicyPayload";
public static final String ENROLLMENT_APP_INSTALL_CODE = "enrollmentAppInstall";
public static final String ENCODING = "UTF-8";
public static final String AT = "@";
@ -195,9 +207,12 @@ public final class AndroidConstants {
public static final String IOT_CORE_HOST = "iot.core.host";
public static final String IOT_CORE_PORT = "iot.core.https.port";
public static final String ENROLLMENT_APP_INSTALL_PROTOCOL = "https://";
public static final String ENROLLMENT_APP_INSTALL_CONTEXT = "/api/appm/store/v1.1/apps/mobile/schedule-install";
public static final String ENROLLMENT_APP_INSTALL_URL = "/api/application-mgt-store/v1.0/subscription/{uuid}/devices/install";
public static final String AUTHORIZATION = "Authorization";
public static final String AUTHORIZATION_HEADER_VALUE = "Bearer ";
public static final String BEHAVIOUR_WHITELISTED_APPS_ONLY = "whitelist";
public static final String INSTALL = "INSTALL";
public static final String UNINSTALL = "UNINSTALL";
}
public final class ErrorMessages {

@ -57,16 +57,21 @@ 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.SubAction;
import org.wso2.carbon.device.application.mgt.common.SubscriptionType;
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.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.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;
@ -75,19 +80,29 @@ 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.operation.mgt.ProfileOperation;
import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils;
import org.wso2.carbon.device.mgt.mobile.android.impl.EnterpriseServiceException;
import org.wso2.carbon.device.mgt.mobile.android.impl.dto.AndroidEnterpriseUser;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.mdm.services.android.bean.DeviceState;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseConfigs;
import org.wso2.carbon.mdm.services.android.bean.ErrorListItem;
import org.wso2.carbon.mdm.services.android.bean.ErrorResponse;
import org.wso2.carbon.mdm.services.android.bean.wrapper.EnterpriseApp;
import org.wso2.carbon.mdm.services.android.bean.wrapper.EnterpriseInstallPolicy;
import org.wso2.carbon.mdm.services.android.common.GoogleAPIInvoker;
import org.wso2.carbon.mdm.services.android.exception.BadRequestException;
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 javax.validation.ConstraintViolation;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -236,6 +251,19 @@ public class AndroidDeviceUtils {
} 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
@ -255,13 +283,109 @@ public class AndroidDeviceUtils {
}
public static List<? extends Operation> getPendingOperations
(DeviceIdentifier deviceIdentifier) throws OperationManagementException {
(DeviceIdentifier deviceIdentifier, boolean handleGoogleAps) throws OperationManagementException {
List<? extends Operation> operations;
operations = AndroidAPIUtils.getDeviceManagementService().getPendingOperations(deviceIdentifier);
if (operations != null && handleGoogleAps) {
handleEnrollmentGoogleApps(operations, deviceIdentifier);
}
return operations;
}
private static void handleEnrollmentGoogleApps(List<? extends Operation> operations, DeviceIdentifier
deviceIdentifier) {
boolean containsGoogleAppPolicy = false;
for (int x = 0; x < operations.size() && !containsGoogleAppPolicy; x++) {
Operation operation = operations.get(x);
// Check if the operation has a policy bundle inside.
if (operation.getCode().equals(AndroidConstants.OperationCodes.POLICY_BUNDLE)) {
ArrayList operationPayLoad = (ArrayList) operation.getPayLoad();
// If there is a policy bundle, read its payload
for (int i = 0; i < operationPayLoad.size() && !containsGoogleAppPolicy; i++) {
Object policy = operationPayLoad.get(i);
ProfileOperation profileOperation = (ProfileOperation) policy;
String code = profileOperation.getCode();
// Find if there is an ENROLLMENT_APP_INSTALL payload
if (code.equals(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE)) {
String payload = profileOperation.getPayLoad().toString();
JsonElement appListElement = new JsonParser().parse(payload).getAsJsonObject()
.get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE);
JsonArray appListArray = appListElement.getAsJsonArray();
// Find if there are Apps with Work profile configurations
for (JsonElement appElement : appListArray) {
JsonElement googlePolicyPayload = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD);
if (googlePolicyPayload != null) {
String uuid = appElement.getAsJsonObject().get("uuid").toString();
containsGoogleAppPolicy = true;// breaking out of outer for loop
try {
uuid = uuid.replace("\"", "");
sendPayloadToGoogle(uuid, payload, deviceIdentifier);
} catch (org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException e) {
String errorMessage = "App install failed for device " + deviceIdentifier.getId();
log.error(errorMessage, e);
}
break;
}
}
}
}
}
}
}
/**
* Sends the app install policy to Google
* @param payload policy profile
* @param deviceIdentifier device to apply policy
*/
private static void sendPayloadToGoogle(String uuid, String payload, DeviceIdentifier deviceIdentifier)
throws org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException {
try {
EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigsFromGoogle();
if (enterpriseConfigs != null && enterpriseConfigs.getErrorResponse() == null) {
GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa());
AndroidEnterpriseUser userDetail = AndroidAPIUtils.getAndroidPluginService()
.getEnterpriseUserByDevice(deviceIdentifier.getId());
if (userDetail != null && userDetail.getEnterpriseId() != null && !userDetail.getEnterpriseId()
.isEmpty() && userDetail.getEmmUsername() != null) {
if (payload != null) {
// ProfileFeature feature = AndroidDeviceUtils.getEnrollmentPolicy(deviceIdentifier);
EnterpriseInstallPolicy enterpriseInstallPolicy = AndroidEnterpriseUtils
.getDeviceAppPolicy(payload, null, userDetail);
List<String> apps = new ArrayList<>();
for (EnterpriseApp enterpriseApp : enterpriseInstallPolicy.getApps()) {
apps.add(enterpriseApp.getProductId());
}
googleAPIInvoker.approveAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail
.getGoogleUserId(), apps, enterpriseInstallPolicy.getProductSetBehavior());
googleAPIInvoker.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(),
AndroidEnterpriseUtils.convertToDeviceInstance(enterpriseInstallPolicy));
AndroidEnterpriseUtils.getAppSubscriptionService()
.performEntAppSubscription(uuid,
Arrays.asList(CarbonContext.getThreadLocalCarbonContext().getUsername()),
SubscriptionType.USER.toString(), SubAction.INSTALL.toString(), false);
}
}
}
} catch (EnterpriseServiceException e) {
String errorMessage = "App install failed for device " + deviceIdentifier.getId();
log.error(errorMessage);
}
}
private static void updateApplicationList(Operation operation, DeviceIdentifier deviceIdentifier)
throws ApplicationManagementException {
// Parsing json string to get applications list.
@ -308,6 +432,16 @@ public class AndroidDeviceUtils {
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();
@ -536,11 +670,9 @@ public class AndroidDeviceUtils {
return errorResponse;
}
public static void installEnrollmentApplications(ProfileFeature feature, String deviceId)
public static void installEnrollmentApplications(ProfileFeature feature, DeviceIdentifier deviceIdentifier)
throws PolicyManagementException {
String appId = "";
String payload;
StringRequestEntity requestEntity;
String uuid = "";
HttpClient httpClient;
PostMethod request;
try {
@ -553,36 +685,44 @@ public class AndroidDeviceUtils {
System.getProperty(AndroidConstants.ApplicationInstall.IOT_CORE_HOST) +
AndroidConstants.ApplicationInstall.COLON +
System.getProperty(AndroidConstants.ApplicationInstall.IOT_CORE_PORT) +
AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CONTEXT;
AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_URL;
JsonElement appListElement = new JsonParser().parse(feature.getContent().toString()).getAsJsonObject()
.get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE);
String payload = "[{\"id\":\"" + deviceIdentifier.getId() + "\", \"type\":\""
+ deviceIdentifier.getType() + "\"}]";
StringRequestEntity requestEntity = new StringRequestEntity(payload, MediaType.APPLICATION_JSON
, AndroidConstants.ApplicationInstall.ENCODING);
JsonArray appListArray = appListElement.getAsJsonArray();
for (JsonElement appElement : appListArray) {
appId = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_ID).getAsString();
payload = "{\"appId\": \"" + appId + "\", \"scheduleTime\":\"2013-12-25T15:25:30-05:00\"," +
"\"deviceIds\": [\"{\\\"id\\\":\\\"" + deviceId + "\\\", \\\"type\\\":\\\"android\\\"}\"]}";
requestEntity = new StringRequestEntity(payload, MediaType.APPLICATION_JSON,
AndroidConstants.ApplicationInstall.ENCODING);
uuid = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_UUID).getAsString();
requestUrl = requestUrl.replace("{uuid}", uuid);
httpClient = new HttpClient();
request = new PostMethod(requestUrl);
request.addRequestHeader(AndroidConstants.ApplicationInstall.AUTHORIZATION,
AndroidConstants.ApplicationInstall.AUTHORIZATION_HEADER_VALUE + tokenInfo.getAccessToken());
request.addRequestHeader(AndroidConstants.ApplicationInstall.AUTHORIZATION
, AndroidConstants.ApplicationInstall.AUTHORIZATION_HEADER_VALUE + tokenInfo.getAccessToken());
request.setRequestEntity(requestEntity);
httpClient.executeMethod(request);
}
} catch (UserStoreException e) {
throw new PolicyManagementException("Error while accessing user store for user with iOS device id: " +
deviceId, 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) {
throw new PolicyManagementException("Error while retrieving access token for Android device id: " +
deviceId, 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) {
throw new PolicyManagementException("Error while calling the app store to install enrollment app with " +
"id: " + appId + " on device with id: " + deviceId, 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) {
throw new PolicyManagementException("Error while installing the enrollment app with id: " + appId +
" on device with id: " + deviceId, 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);
}
}
@ -595,7 +735,7 @@ public class AndroidDeviceUtils {
public static void updateDisEnrollOperationStatus(DeviceIdentifier deviceIdentifier)
throws DeviceManagementException {
try {
List<? extends Operation> pendingOperations = getPendingOperations(deviceIdentifier);
List<? extends Operation> pendingOperations = getPendingOperations(deviceIdentifier, false);
if (pendingOperations != null && !pendingOperations.isEmpty()) {
for (Operation operation : pendingOperations) {
operation.setStatus(Operation.Status.ERROR);
@ -609,4 +749,53 @@ public class AndroidDeviceUtils {
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;
}
}

@ -0,0 +1,474 @@
/*
* Copyright (c) 2019, 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.mdm.services.android.util;
import com.google.api.services.androidenterprise.model.AppVersion;
import com.google.api.services.androidenterprise.model.AutoInstallConstraint;
import com.google.api.services.androidenterprise.model.AutoInstallPolicy;
import com.google.api.services.androidenterprise.model.ConfigurationVariables;
import com.google.api.services.androidenterprise.model.Device;
import com.google.api.services.androidenterprise.model.ManagedConfiguration;
import com.google.api.services.androidenterprise.model.Policy;
import com.google.api.services.androidenterprise.model.Product;
import com.google.api.services.androidenterprise.model.ProductPolicy;
import com.google.api.services.androidenterprise.model.ProductsListResponse;
import com.google.api.services.androidenterprise.model.VariableSet;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
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.ApplicationArtifact;
import org.wso2.carbon.device.application.mgt.common.LifecycleChanger;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
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.PublicAppReleaseWrapper;
import org.wso2.carbon.device.application.mgt.common.wrapper.PublicAppWrapper;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature;
import org.wso2.carbon.device.mgt.mobile.android.impl.EnterpriseServiceException;
import org.wso2.carbon.device.mgt.mobile.android.impl.dto.AndroidEnterpriseManagedConfig;
import org.wso2.carbon.device.mgt.mobile.android.impl.dto.AndroidEnterpriseUser;
import org.wso2.carbon.mdm.services.android.bean.BasicUserInfo;
import org.wso2.carbon.mdm.services.android.bean.EnterpriseConfigs;
import org.wso2.carbon.mdm.services.android.bean.ErrorResponse;
import org.wso2.carbon.mdm.services.android.bean.wrapper.EnterpriseApp;
import org.wso2.carbon.mdm.services.android.bean.wrapper.EnterpriseInstallPolicy;
import org.wso2.carbon.mdm.services.android.exception.NotFoundException;
import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AndroidEnterpriseUtils {
private static Log log = LogFactory.getLog(AndroidEnterpriseUtils.class);
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();
device.setManagementType(enterpriseInstallPolicy.getManagementType());
device.setKind(enterpriseInstallPolicy.getKind());
device.setAndroidId(enterpriseInstallPolicy.getAndroidId());
Policy policy = new Policy();
List<ProductPolicy> policyList = new ArrayList<>();
for (EnterpriseApp app : enterpriseInstallPolicy.getApps()) {
ProductPolicy productPolicy = new ProductPolicy();
AutoInstallPolicy autoInstallPolicy = new AutoInstallPolicy();
autoInstallPolicy.setAutoInstallMode(app.getAutoInstallMode());
autoInstallPolicy.setAutoInstallPriority(app.getAutoInstallPriority());
List<AutoInstallConstraint> autoInstallConstraintList = new ArrayList<>();
AutoInstallConstraint autoInstallConstraint = new AutoInstallConstraint();
autoInstallConstraint.setChargingStateConstraint(app.getChargingStateConstraint());
autoInstallConstraint.setDeviceIdleStateConstraint(app.getDeviceIdleStateConstraint());
autoInstallConstraint.setNetworkTypeConstraint(app.getNetworkTypeConstraint());
autoInstallConstraintList.add(autoInstallConstraint);
autoInstallPolicy.setAutoInstallConstraint(autoInstallConstraintList);
productPolicy.setAutoInstallPolicy(autoInstallPolicy);
productPolicy.setProductId(app.getProductId());
// TODO: Cache this against package name
AndroidEnterpriseManagedConfig configs = AndroidAPIUtils.getAndroidPluginService()
.getConfigByPackageName(app.getProductId().replaceFirst("app:", ""));
if (configs != null && configs.getMcmId() != null) {
ManagedConfiguration managedConfiguration = new ManagedConfiguration();
ConfigurationVariables configurationVariables = new ConfigurationVariables();
configurationVariables.setKind("androidenterprise#configurationVariables");
configurationVariables.setMcmId(configs.getMcmId());
List<VariableSet> variableSets = new ArrayList<>();
BasicUserInfo userInfo = getBasicUserInfo(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername());
for (String key : templates) {
VariableSet variableSet = new VariableSet();
variableSet.setKind("androidenterprise#variableSet");
variableSet.setPlaceholder(key);
String value = getPlaceholderValue(userInfo, key);
if (value == null) {
continue;
}
variableSet.setUserValue(value);
variableSets.add(variableSet);
}
if (variableSets != null && variableSets.size() > 0) {
configurationVariables.setVariableSet(variableSets);
}
managedConfiguration.setConfigurationVariables(configurationVariables);
productPolicy.setManagedConfiguration(managedConfiguration);
}
policyList.add(productPolicy);
}
policy.setProductPolicy(policyList);
policy.setAutoUpdatePolicy(enterpriseInstallPolicy.getAutoUpdatePolicy());
policy.setProductAvailabilityPolicy(enterpriseInstallPolicy.getProductAvailabilityPolicy());
device.setPolicy(policy);
return device;
}
private static String getPlaceholderValue(BasicUserInfo userInfo, String key) {
if (userInfo != null) {
switch (key) {
case AndroidConstants.USER_CLAIM_EMAIL_ADDRESS_PLACEHOLDER:
return userInfo.getEmailAddress();
case AndroidConstants.USER_CLAIM_FIRST_NAME_PLACEHOLDER:
return userInfo.getFirstname();
case AndroidConstants.USER_CLAIM_LAST_NAME_PLACEHOLDER:
return userInfo.getLastname();
}
}
return null;
}
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);
}
int tenantId = ctx.getTenantId();
try {
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
} catch (UserStoreException e) {
String msg = "Could not create user store manager.";
log.error(msg);
throw new EnterpriseServiceException(msg, e);
}
return userStoreManager;
}
private static BasicUserInfo getBasicUserInfo(String username) throws EnterpriseServiceException {
UserStoreManager userStoreManager = getUserStoreManager();
try {
if (!userStoreManager.isExistingUser(username)) {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist.");
}
return null;
}
} catch (UserStoreException e) {
String msg = "Could not get user details of user " + username;
log.error(msg);
throw new EnterpriseServiceException(msg, e);
}
BasicUserInfo userInfo = new BasicUserInfo();
userInfo.setUsername(username);
try {
userInfo.setEmailAddress(userStoreManager.getUserClaimValue(username, AndroidConstants.USER_CLAIM_EMAIL_ADDRESS, null));
userInfo.setFirstname(userStoreManager.getUserClaimValue(username, AndroidConstants.USER_CLAIM_FIRST_NAME, null));
userInfo.setFirstname(userStoreManager.getUserClaimValue(username, AndroidConstants.USER_CLAIM_LAST_NAME, null));
} catch (UserStoreException e) {
String msg = "Could not get claims of user " + username;
log.error(msg);
throw new EnterpriseServiceException(msg, e);
}
return userInfo;
}
public static EnterpriseConfigs getEnterpriseConfigs() {
EnterpriseConfigs enterpriseConfigs = getEnterpriseConfigsFromGoogle();
if (enterpriseConfigs.getErrorResponse() != null) {
if (enterpriseConfigs.getErrorResponse().getCode() == 500l) {
throw new UnexpectedServerErrorException(enterpriseConfigs.getErrorResponse());
} else if (enterpriseConfigs.getErrorResponse().getCode() == 500l) {
throw new NotFoundException(enterpriseConfigs.getErrorResponse());
}
}
return enterpriseConfigs;
}
public static EnterpriseConfigs getEnterpriseConfigsFromGoogle() {
PlatformConfiguration configuration = null;
EnterpriseConfigs enterpriseConfigs = new EnterpriseConfigs();
try {
configuration = AndroidAPIUtils.getDeviceManagementService().
getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
} catch (DeviceManagementException e) {
String errorMessage = "Error while fetching tenant configurations for tenant " +
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
log.error(errorMessage);
// Error is being used in enterprise APIs as well as from getpending operations which should not fail as
// these errors can cause due to issues misconfigurations in policy/esa configs which can cause to break all
// operations, if the error is thrown to cfx error handler
enterpriseConfigs.setErrorResponse(new ErrorResponse.ErrorResponseBuilder().setCode(500l)
.setMessage(errorMessage).build());
}
String enterpriseId = AndroidDeviceUtils.getAndroidConfig(configuration,"enterpriseId");
String esa = AndroidDeviceUtils.getAndroidConfig(configuration,"esa");
if (enterpriseId == null || enterpriseId.isEmpty() || esa == null || esa.isEmpty()) {
String errorMessage = "Tenant is not configured to handle Android for work. Please contact Entgra.";
log.warn(errorMessage);
enterpriseConfigs.setErrorResponse(new ErrorResponse.ErrorResponseBuilder().setCode(404l)
.setMessage(errorMessage).build());
}
enterpriseConfigs.setEnterpriseId(enterpriseId);
enterpriseConfigs.setEsa(esa);
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();
List<Category> categories = applicationManager.getRegisteredCategories();
if (productListResponse != null && productListResponse.getProduct() != null
&& productListResponse.getProduct().size() > 0) {
for (Product product : productListResponse.getProduct()) {
if (product.getAppVersion() == null) { // This is to handled removed apps from playstore
continue;
}
// Generate App wrapper
PublicAppWrapper publicAppWrapper = new PublicAppWrapper();
PublicAppReleaseWrapper appReleaseWrapper = new PublicAppReleaseWrapper();
publicAppWrapper.setName(product.getTitle());
publicAppWrapper.setDescription(product.getDescription());
publicAppWrapper.setCategories(Arrays.asList(new String[]{"GooglePlaySyncedApp"}));//Default category
for (Category category : categories) {
if (product.getCategory() == null) {
publicAppWrapper.setCategories(Arrays.asList(new String[]{"GooglePlaySyncedApp"}));
break;
} else if (product.getCategory().equalsIgnoreCase(category.getCategoryName())) {
publicAppWrapper.setCategories(Arrays.asList(new String[]{category.getCategoryName(), "GooglePlaySyncedApp"}));
break;
}
}
if (product.getProductPricing().equalsIgnoreCase("free")) {
publicAppWrapper.setSubMethod("FREE");
} else {
publicAppWrapper.setSubMethod("PAID");
}
// TODO: purchase an app from Playstore and see how to capture the real value for price field.
publicAppWrapper.setPaymentCurrency("$");
appReleaseWrapper.setPrice(1.0);
publicAppWrapper.setDeviceType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID);
appReleaseWrapper.setDescription(product.getRecentChanges());
appReleaseWrapper.setReleaseType("ga");
appReleaseWrapper.setVersion(getAppString(product.getAppVersion()));
appReleaseWrapper.setPackageName(product.getProductId().replaceFirst("app:", ""));
appReleaseWrapper.setSupportedOsVersions(String.valueOf(product.getMinAndroidSdkVersion()) + "-ALL");
publicAppWrapper.setPublicAppReleaseWrappers(Arrays.asList(new PublicAppReleaseWrapper[]{appReleaseWrapper}));
// Generate artifacts
ApplicationArtifact applicationArtifact = new ApplicationArtifact();
String iconName = product.getIconUrl().split(".com/")[1];
applicationArtifact.setIconName(iconName);
InputStream iconInputStream = getInputStream(iconName, product.getIconUrl());
applicationArtifact.setIconStream(iconInputStream);
Map<String, InputStream> screenshotMap = new HashMap<>();
int numberOfScreenShots = 3;// This is to handle some apps in playstore without 3 screenshots.
if (product.getScreenshotUrls() != null) {
if (product.getScreenshotUrls().size() < 3) {
numberOfScreenShots = product.getScreenshotUrls().size();
}
for (int y = 1; y < 4; y++) {
int screenshotNumber = y - 1;
if (y > numberOfScreenShots) {
screenshotNumber = 0;
}
String screenshot = product.getScreenshotUrls().get(screenshotNumber);
String screenshotName = screenshot.split(".com/")[1];
InputStream screenshotInputStream = getInputStream(screenshotName, screenshot);
screenshotMap.put(screenshotName, screenshotInputStream);
}
} else { // Private apps doesn't seem to send screenshots. Handling it.
for (int a = 0; a < 3; a++) {
String screenshot = product.getIconUrl();
String screenshotName = screenshot.split(".com/")[1];
InputStream screenshotInputStream = getInputStream(screenshotName, screenshot);
screenshotMap.put(screenshotName, screenshotInputStream);
}
}
applicationArtifact.setScreenshots(screenshotMap);
Application application = applicationManager.createPublicApp(publicAppWrapper, applicationArtifact);
if (application != null && (application.getApplicationReleases().get(0).getCurrentStatus() == null
|| application.getApplicationReleases().get(0).getCurrentStatus().equals("CREATED"))) {
String uuid = application.getApplicationReleases().get(0).getUuid();
LifecycleChanger lifecycleChanger = new LifecycleChanger();
lifecycleChanger.setAction("IN-REVIEW");
applicationManager.changeLifecycleState(uuid, lifecycleChanger);
lifecycleChanger.setAction("APPROVED");
applicationManager.changeLifecycleState(uuid, lifecycleChanger);
lifecycleChanger.setAction("PUBLISHED");
applicationManager.changeLifecycleState(uuid, lifecycleChanger);
}
}
}
}
private static InputStream getInputStream(String filename, String url) throws ApplicationManagementException {
URL website;
try {
website = new URL(url);
} catch (MalformedURLException e) {
String msg = "Error occurred while converting the url " + url;
log.error(msg);
throw new ApplicationManagementException(msg, e);
}
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(website.openStream());
fos = new FileOutputStream(System.getProperty("java.io.tmpdir")
+ File.separator + filename);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}catch (IOException e) {
String msg = "Error occurred while opening stream for url " + url;
log.error(msg);
throw new ApplicationManagementException(msg, e);
} finally {
try {
fos.close();
rbc.close();
} catch (IOException e) {}
}
File file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename);
InputStream targetStream;
try {
targetStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
String msg = "Error occurred while reading the tmp file " + System.getProperty("java.io.tmpdir")
+ File.separator + filename;
log.error(msg);
throw new ApplicationManagementException(msg, e);
}
file.deleteOnExit();
return targetStream;
}
private static String getAppString(List<AppVersion> appVersions) {
int highestVersionCode = 0;
String highestVersionString = null;
for (AppVersion appVersion : appVersions) {
if (appVersion.getIsProduction() && appVersion.getVersionCode() > highestVersionCode) {
highestVersionCode = appVersion.getVersionCode();
highestVersionString = appVersion.getVersionString();
}
}
return highestVersionString;
}
public static EnterpriseInstallPolicy getDeviceAppPolicy(String appPolicy,
ProfileFeature feature,
AndroidEnterpriseUser userDetail) {
EnterpriseInstallPolicy enterpriseInstallPolicy = new EnterpriseInstallPolicy();
List<EnterpriseApp> apps = new ArrayList<>();
JsonElement appListElement;
if (appPolicy == null) {
appListElement = new JsonParser().parse(feature.getContent().toString()).getAsJsonObject()
.get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE);
} else {
appListElement = new JsonParser().parse(appPolicy).getAsJsonObject()
.get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE);
}
JsonArray appListArray = appListElement.getAsJsonArray();
JsonObject googlePolicyPayload = appListArray.get(0).getAsJsonObject();
// get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD).getAsString()).getAsJsonObject();
enterpriseInstallPolicy.setAutoUpdatePolicy(googlePolicyPayload.get("autoUpdatePolicy").getAsString());
enterpriseInstallPolicy.setProductSetBehavior(googlePolicyPayload.get("productSetBehavior").getAsString());
// enterpriseInstallPolicy.setProductAvailabilityPolicy(googlePolicyPayload.get("productAvailabilityPolicy").getAsString());
enterpriseInstallPolicy.setManagementType("managedProfile");
enterpriseInstallPolicy.setKind("androidenterprise#device");
enterpriseInstallPolicy.setAndroidId(userDetail.getAndroidPlayDeviceId());
enterpriseInstallPolicy.setUsername(userDetail.getEmmUsername());
for (JsonElement appElement : appListArray) {
JsonElement policy = appElement.getAsJsonObject().
get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD);
if (policy != null) {
JsonObject googlePolicyForApp = new JsonParser().parse(policy.getAsString()).getAsJsonObject();
EnterpriseApp enterpriseApp = new EnterpriseApp();
enterpriseApp.setProductId("app:" + googlePolicyForApp.get("packageName").getAsString());
enterpriseApp.setAutoInstallMode(googlePolicyForApp.get("autoInstallMode").getAsString());
enterpriseApp.setAutoInstallPriority(googlePolicyForApp.get("autoInstallPriority").getAsInt());
enterpriseApp.setChargingStateConstraint(googlePolicyForApp.get("chargingStateConstraint").getAsString());
enterpriseApp.setDeviceIdleStateConstraint(googlePolicyForApp.get("deviceIdleStateConstraint").getAsString());
enterpriseApp.setNetworkTypeConstraint(googlePolicyForApp.get("networkTypeConstraint").getAsString());
apps.add(enterpriseApp);
}
}
enterpriseInstallPolicy.setApps(apps);
return enterpriseInstallPolicy;
}
}

@ -249,6 +249,13 @@
<method>POST</method>
</Permission>
<Permission>
<name>Change LockTask mode</name>
<path>/device-mgt/admin/device/android/operation/change-LockTask</path>
<url>/admin/devices/change-LockTask</url>
<method>POST</method>
</Permission>
<Permission>
<name>Ring device</name>
<path>/device-mgt/admin/device/android/operation/ring</path>

@ -26,6 +26,7 @@
<ref bean="deviceManagementService"/>
<ref bean="deviceManagementAdminService"/>
<ref bean="eventReceiverService"/>
<ref bean="androidEnterprise"/>
<ref bean="deviceTypeConfigurationService"/>
<ref bean="swaggerResource"/>
</jaxrs:serviceBeans>
@ -63,6 +64,7 @@
<bean id="deviceManagementAdminService" class="org.wso2.carbon.mdm.services.android.services.impl.DeviceManagementAdminServiceImpl"/>
<bean id="eventReceiverService" class="org.wso2.carbon.mdm.services.android.services.impl.EventReceiverServiceImpl"/>
<bean id="deviceTypeConfigurationService" class="org.wso2.carbon.mdm.services.android.services.impl.DeviceTypeConfigurationServiceImpl"/>
<bean id="androidEnterprise" class="org.wso2.carbon.mdm.services.android.services.impl.AndroidEnterpriseServiceImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.mdm.services.android.common.GsonMessageBodyHandler"/>
<bean id="errorHandler" class="org.wso2.carbon.mdm.services.android.common.ErrorHandler"/>
<cxf:bus>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save