merging susinda's commit 'mobile-qsg code added'

application-manager-new
susinda 8 years ago
parent 59b86f9d50
commit 0779e358ed

@ -35,6 +35,7 @@
<modules>
<module>tools</module>
<module>iotserver-ui</module>
<module>scripts</module>
<module>features</module>
<module>p2-profile-gen</module>
<module>distribution</module>

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<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.iot</groupId>
<artifactId>wso2iot-core-scripts</artifactId>
<version>3.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.iot</groupId>
<artifactId>mobile-qsg</artifactId>
<version>3.1.0-SNAPSHOT</version>
<name>WSO2 IoTs QSG Script</name>
<description>This includes the tools for IoTs Quick Start Guide</description>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<finalName>${project.artifactId}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>org.wso2.mdm.qsg.QSGExecutor</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,189 @@
/*
* 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.mdm.qsg;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.mdm.qsg.dto.EMMQSGConfig;
import org.wso2.mdm.qsg.dto.HTTPResponse;
import org.wso2.mdm.qsg.dto.MobileApplication;
import org.wso2.mdm.qsg.utils.Constants;
import org.wso2.mdm.qsg.utils.HTTPInvoker;
import org.wso2.mdm.qsg.utils.QSGUtils;
import java.io.File;
import java.util.HashMap;
/**
* This class holds the app-mgt related operations.
*/
public class AppOperations {
public static MobileApplication uploadApplication(String platform, String appName, String appContentType) {
String appUploadEndpoint =
EMMQSGConfig.getInstance().getEmmHost() + "/api/appm/publisher/v1.1/apps/mobile/binaries";
String filePath = "apps" + File.separator + platform + File.separator + appName;
HTTPResponse
httpResponse = HTTPInvoker.uploadFile(appUploadEndpoint, filePath, appContentType);
if (Constants.HTTPStatus.OK == httpResponse.getResponseCode()) {
JSONObject appMeta = null;
MobileApplication application = new MobileApplication();
try {
appMeta = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
application.setPackageId((String) appMeta.get("package"));
application.setAppId(QSGUtils.getResourceId((String) appMeta.get("path")));
application.setVersion((String) appMeta.get("version"));
application.setPlatform(platform);
} catch (ParseException e) {
e.printStackTrace();
}
return application;
}
return null;
}
public static MobileApplication getPublicApplication(String packageId, String version, String platform) {
MobileApplication application = new MobileApplication();
application.setVersion(version);
application.setPackageId(packageId);
application.setPlatform(platform);
return application;
}
private static String uploadAsset(String path) {
String resUploadEndpoint =
EMMQSGConfig.getInstance().getEmmHost() + "/api/appm/publisher/v1.1/apps/static-contents?appType=mobileapp";
HTTPResponse httpResponse = HTTPInvoker.uploadFile(resUploadEndpoint, path, "image/jpeg");
if (Constants.HTTPStatus.OK == httpResponse.getResponseCode()) {
JSONObject resp = null;
try {
resp = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
return (String) resp.get("id");
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
public static MobileApplication uploadAssets(String platform, MobileApplication application) {
String assetDir = "apps" + File.separator + platform + File.separator + "images";
//Upload the icon file
String imgFile = assetDir + File.separator + "icon.jpg";
String uploadPath = uploadAsset(imgFile);
if (uploadPath != null && !uploadPath.isEmpty()) {
application.setIcon(uploadPath);
} else {
System.out.println("Unable to upload the app icon file.");
return null;
}
//Upload the banner file
imgFile = assetDir + File.separator + "banner.jpg";
uploadPath = uploadAsset(imgFile);
if (uploadPath != null && !uploadPath.isEmpty()) {
application.setBanner(uploadPath);
} else {
System.out.println("Unable to upload the app banner file.");
return null;
}
//Upload the screenshot1 file
imgFile = assetDir + File.separator + "screen1.jpg";
uploadPath = uploadAsset(imgFile);
if (uploadPath != null && !uploadPath.isEmpty()) {
application.setScreenshot1(uploadPath);
} else {
System.out.println("Unable to upload the app screenshot1 file.");
return null;
}
//Upload the screenshot2 file
imgFile = assetDir + File.separator + "screen2.jpg";
uploadPath = uploadAsset(imgFile);
if (uploadPath != null && !uploadPath.isEmpty()) {
application.setScreenshot2(uploadPath);
} else {
System.out.println("Unable to upload the app screenshot2 file.");
return null;
}
//Upload the screenshot3 file
imgFile = assetDir + File.separator + "screen3.jpg";
uploadPath = uploadAsset(imgFile);
if (uploadPath != null && !uploadPath.isEmpty()) {
application.setScreenshot3(uploadPath);
} else {
System.out.println("Unable to upload the app screenshot3 file.");
return null;
}
return application;
}
public static boolean addApplication(String name, MobileApplication mblApp, boolean isEnterpriseApp) {
HashMap<String, String> headers = new HashMap<String, String>();
String appEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/appm/publisher/v1.1/apps/mobileapp";
//Set the application payload
JSONObject application = new JSONObject();
application.put("name", name);
application.put("description", "Sample application");
application.put("type", "enterprise");
//Set appMeta data
JSONObject appMeta = new JSONObject();
appMeta.put("package", mblApp.getPackageId());
appMeta.put("version", mblApp.getVersion());
if (isEnterpriseApp) {
application.put("marketType", "enterprise");
appMeta.put("path", mblApp.getAppId());
} else {
application.put("marketType", "public");
}
application.put("provider", "admin");
application.put("displayName", name);
application.put("category", "Business");
application.put("icon", mblApp.getIcon());
application.put("version", mblApp.getVersion());
application.put("banner", mblApp.getBanner());
application.put("platform", mblApp.getPlatform());
application.put("appType", mblApp.getPlatform());
//application.put("appUrL", mblApp.getAppId());
application.put("mediaType", "application/vnd.wso2-mobileapp+xml");
//Set screenshots
JSONArray screenshots = new JSONArray();
screenshots.add(mblApp.getScreenshot1());
screenshots.add(mblApp.getScreenshot2());
screenshots.add(mblApp.getScreenshot3());
application.put("appmeta", appMeta);
application.put("screenshots", screenshots);
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse
httpResponse =
HTTPInvoker.sendHTTPPostWithOAuthSecurity(appEndpoint, application.toJSONString(), headers);
if (Constants.HTTPStatus.OK == httpResponse.getResponseCode()) {
return true;
}
return false;
}
}

@ -0,0 +1,77 @@
/*
* 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.mdm.qsg;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.wso2.mdm.qsg.dto.EMMQSGConfig;
import org.wso2.mdm.qsg.dto.HTTPResponse;
import org.wso2.mdm.qsg.utils.Constants;
import org.wso2.mdm.qsg.utils.HTTPInvoker;
import java.util.HashMap;
/**
* This class holds the methods to create policies.
*/
public class PolicyOperations {
public static boolean createPasscodePolicy(String policyName, String deviceType) {
HashMap<String, String> headers = new HashMap<String, String>();
String policyEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/policies";
//Set the policy payload
JSONObject policyData = new JSONObject();
policyData.put("policyName", policyName);
policyData.put("description", "Passcode Policy");
policyData.put("compliance", "enforce");
policyData.put("ownershipType", "ANY");
policyData.put("active", false);
JSONObject profile = new JSONObject();
profile.put("profileName", "passcode");
profile.put("deviceType", deviceType);
JSONArray featureList = new JSONArray();
JSONObject feature = new JSONObject();
feature.put("featureCode", "PASSCODE_POLICY");
feature.put("deviceType", deviceType);
JSONObject featureContent = new JSONObject();
featureContent.put("allowSimple", false);
featureContent.put("requireAlphanumeric", true);
featureContent.put("minLength", "5");
featureContent.put("minComplexChars", "2");
featureContent.put("maxPINAgeInDays", 7);
featureContent.put("pinHistory", 7);
featureContent.put("maxFailedAttempts", null);
feature.put("content", featureContent);
featureList.add(feature);
profile.put("profileFeaturesList", featureList);
JSONArray roles = new JSONArray();
roles.add(Constants.EMM_USER_ROLE);
policyData.put("profile", profile);
policyData.put("roles", roles);
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse
httpResponse = HTTPInvoker
.sendHTTPPostWithOAuthSecurity(policyEndpoint, policyData.toJSONString(), headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
return true;
}
return false;
}
}

@ -0,0 +1,137 @@
/*
* 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.mdm.qsg;
import org.wso2.mdm.qsg.dto.MobileApplication;
import org.wso2.mdm.qsg.utils.Constants;
import org.wso2.mdm.qsg.utils.HTTPInvoker;
import org.wso2.mdm.qsg.utils.QSGUtils;
import java.util.*;
/**
* Main class of EMM-QSG module. This class will populate each sample scenario.
*/
public class QSGExecutor {
public static void main(String[] args) {
boolean status = false;
Scanner scanner = new Scanner(System.in);
// prompt for the user's name
System.out.print("Enter your email address and press enter : ");
String email = scanner.next();
if (!QSGUtils.isValidEmailAddress(email)) {
do {
System.out.print("Please enter a valid email address and press enter : ");
email = scanner.next();
} while (!QSGUtils.isValidEmailAddress(email));
}
//Setup the OAuth token
String token = QSGUtils.getOAuthToken();
if (token == null) {
System.out.println("Unable to get the OAuth token. Please check the config.properties file.");
System.exit(0);
}
HTTPInvoker.oAuthToken = token;
//Creates the admin user
status = UserOperations.createUser("tom", "tom@mobx.com", true);
if (!status) {
System.out.println("Unable to create the admin user. Please check the config.properties file.");
System.exit(0);
}
status = UserOperations.changePassword("tom", "tomemm");
if (!status) {
System.out.println("Unable to change the password of the admin user. Terminating the EMM QSG now.");
System.exit(0);
}
//Creates the emm user
status = UserOperations.createUser("kim", email, false);
if (!status) {
System.out.println("Unable to create the emm user Kim. Terminating the EMM QSG now.");
System.exit(0);
}
status = UserOperations.changePassword("kim", "kimemm");
if (!status) {
System.out.println("Unable to change the password of the emm user. Terminating the EMM QSG now.");
System.exit(0);
}
//Creates the emm-user role
status = UserOperations.createRole(Constants.EMM_USER_ROLE, new String[] { "kim" });
if (!status) {
System.out.println("Unable to create the emm user role. Terminating the EMM QSG now.");
System.exit(0);
}
//Add the android policy
status = PolicyOperations.createPasscodePolicy("android-passcode-policy1", Constants.DeviceType.ANDROID);
if (!status) {
System.out.println("Unable to create the android passcode policy. Terminating the EMM QSG now.");
System.exit(0);
}
//Add the windows policy
status = PolicyOperations.createPasscodePolicy("windows-passcode-policy1", Constants.DeviceType.WINDOWS);
if (!status) {
System.out.println("Unable to create the windows passcode policy. Terminating the EMM QSG now.");
System.exit(0);
}
//Add the iOS policy
status = PolicyOperations.createPasscodePolicy("ios-passcode-policy1", Constants.DeviceType.IOS);
if (!status) {
System.out.println("Unable to create the ios passcode policy. Terminating the EMM QSG now.");
System.exit(0);
}
//Upload the android application
MobileApplication application = AppOperations.uploadApplication(Constants.DeviceType.ANDROID, "catalog.apk",
"application/vnd.android.package-archive");
if (application == null) {
System.out.println("Unable to upload the sample android application. Terminating the EMM QSG now.");
System.exit(0);
}
//Upload the assets
application = AppOperations.uploadAssets(Constants.DeviceType.ANDROID, application);
if (application == null) {
System.out.println(
"Unable to upload the assets for sample android application. Terminating the EMM QSG now.");
System.exit(0);
}
//Create application entry in publisher
status = AppOperations.addApplication("Catalog", application, true);
if (!status) {
System.out.println("Unable to create the mobile application. Terminating the EMM QSG now.");
System.exit(0);
}
//Upload the ios application
MobileApplication iOSApplication = AppOperations.uploadApplication(Constants.DeviceType.IOS, "PNDemo.ipa",
"application/octet-stream");
iOSApplication.setVersion("1.0.0");
//Upload the assets
iOSApplication = AppOperations.uploadAssets(Constants.DeviceType.IOS, iOSApplication);
if (iOSApplication == null) {
System.out.println(
"Unable to upload the assets for sample iOS application. Terminating the EMM QSG now.");
System.exit(0);
}
//Create application entry in publisher
status = AppOperations.addApplication("WSO2Con", iOSApplication, true);
if (!status) {
System.out.println("Unable to create the mobile application. Terminating the EMM QSG now.");
System.exit(0);
}
}
}

@ -0,0 +1,185 @@
/*
* 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.mdm.qsg;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.wso2.mdm.qsg.dto.EMMQSGConfig;
import org.wso2.mdm.qsg.dto.HTTPResponse;
import org.wso2.mdm.qsg.utils.Constants;
import org.wso2.mdm.qsg.utils.HTTPInvoker;
import java.util.HashMap;
/**
* This class holds the user-mgt related operations like user-create, role-create and change-password.
*/
public class UserOperations {
public static boolean createUser(String username, String email, boolean isAdmin) {
HashMap<String, String> headers = new HashMap<String, String>();
String userEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/users";
//Set the user payload
JSONObject userData = new JSONObject();
userData.put("username", username);
userData.put("emailAddress", email);
JSONArray roles = new JSONArray();
if (isAdmin) {
roles.add("admin");
userData.put("firstname", "Tom");
userData.put("lastname", "Admin");
} else {
userData.put("password", "kimemmtrial");
userData.put("firstname", "Kim");
userData.put("lastname", "User");
}
userData.put("roles", roles);
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse httpResponse = HTTPInvoker
.sendHTTPPostWithOAuthSecurity(userEndpoint, userData.toJSONString(), headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
return true;
}
return false;
}
public static boolean changePassword(String username, String pwd) {
HashMap<String, String> headers = new HashMap<String, String>();
String pwdEndpoint =
EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/admin/users/" + username + "/credentials";
//Set the password payload
JSONObject pwdData = new JSONObject();
pwdData.put("newPassword", pwd);
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse httpResponse =
HTTPInvoker.sendHTTPPostWithOAuthSecurity(pwdEndpoint, pwdData.toJSONString(), headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) {
return true;
}
return false;
}
private static String[] getUserPermissions() {
String permissions = "/permission/admin/device-mgt/certificates/manage," +
"/permission/admin/device-mgt/certificates/view," +
"/permission/admin/device-mgt/configurations/view," +
"/permission/admin/device-mgt/devices/enroll/android," +
"/permission/admin/device-mgt/devices/enroll/ios," +
"/permission/admin/device-mgt/devices/owning-device/view," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/applications," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/blacklist-app," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/camera," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/change-lock-code," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/clear-password," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/encrypt," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/enterprise-wipe," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/info," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/install-app," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/location," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/lock," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/logcat," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/mute," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/password-policy," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/ring," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/reboot," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/send-notification," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/uninstall-app," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/update-app," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/unlock," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/upgrade," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/vpn," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/webclip," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/wifi," +
"/permission/admin/device-mgt/devices/owning-device/operations/android/wipe," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/airplay," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/apn," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/app-list," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/app-lock," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/app-to-per-app-vpn," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/cal-subscription," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/caldav," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/cellular," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/clear-passcode," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/device-info," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/email," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/enterprise-app," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/enterprise-wipe," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/get-restrictions," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/ldap," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/location," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/lock," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/notification," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/passcode-policy," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/per-app-vpn," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/profile-list," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/remove-app," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/remove-profile," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/restriction," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/ring," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/store-app," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/vpn," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/webclip," +
"/permission/admin/device-mgt/devices/owning-device/operations/ios/wifi," +
"/permission/admin/device-mgt/notifications/view," +
"/permission/admin/device-mgt/platform-configurations/view," +
"/permission/admin/device-mgt/policies/view," +
"/permission/admin/device-mgt/applications/manage," +
"/permission/admin/manage/mobileapp/create," +
"/permission/admin/manage/mobileapp/install," +
"/permission/admin/manage/resources/browse," +
"/permission/admin/manage/webapp/subscribe," +
"/permission/admin/manage/search/advanced-search," +
"/permission/admin/manage/search/resources," +
"/permission/admin/manage/resources/govern/mobileapp/list," +
"/permission/admin/login";
return permissions.split(",");
}
public static boolean createRole(String roleName, String[] users) {
HashMap<String, String> headers = new HashMap<String, String>();
String roleEndpoint = EMMQSGConfig.getInstance().getEmmHost() + "/api/device-mgt/v1.0/roles";
//Set the role payload
JSONObject roleData = new JSONObject();
roleData.put("roleName", roleName);
JSONArray perms = new JSONArray();
String[] permissions = getUserPermissions();
for (String perm : permissions) {
perms.add(perm);
}
roleData.put("permissions", perms);
JSONArray usrs = new JSONArray();
for (String usr : users) {
usrs.add(usr);
}
roleData.put("permissions", perms);
roleData.put("users", usrs);
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse httpResponse =
HTTPInvoker.sendHTTPPostWithOAuthSecurity(roleEndpoint, roleData.toJSONString(), headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
return true;
}
return false;
}
}

@ -0,0 +1,44 @@
/*
* 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.mdm.qsg.dto;
/**
* This holds the domain-model of client-credentials.
*/
public class ClientCredentials {
private String clientKey;
private String clientSecret;
public String getClientKey() {
return clientKey;
}
public void setClientKey(String clientKey) {
this.clientKey = clientKey;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
}

@ -0,0 +1,80 @@
/*
* 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.mdm.qsg.dto;
/**
* This holds the model object of EMM configuration.
*/
public class EMMQSGConfig {
private String dcrEndPoint;
private String oauthEndPoint;
private String emmHost;
private String username;
private String password;
private static EMMQSGConfig instance = new EMMQSGConfig();
private EMMQSGConfig() {
}
public String getDcrEndPoint() {
return dcrEndPoint;
}
public void setDcrEndPoint(String dcrEndPoint) {
this.dcrEndPoint = dcrEndPoint;
}
public String getOauthEndPoint() {
return oauthEndPoint;
}
public void setOauthEndPoint(String oauthEndPoint) {
this.oauthEndPoint = oauthEndPoint;
}
public String getEmmHost() {
return emmHost;
}
public void setEmmHost(String emmHost) {
this.emmHost = emmHost;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static EMMQSGConfig getInstance() {
return instance;
}
}

@ -0,0 +1,44 @@
/*
* 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.mdm.qsg.dto;
/**
* This holds the domain-model of HTTP Response.
*/
public class HTTPResponse {
private String response;
private int responseCode;
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
}

@ -0,0 +1,107 @@
/*
* 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.mdm.qsg.dto;
/**
* This serves as the domain-model of MobileApplication related data.
*/
public class MobileApplication {
private String appId;
private String packageId;
private String version;
private String icon;
private String banner;
private String screenshot1;
private String screenshot2;
private String screenshot3;
private String platform;
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getPackageId() {
return packageId;
}
public void setPackageId(String packageId) {
this.packageId = packageId;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getBanner() {
return banner;
}
public void setBanner(String banner) {
this.banner = banner;
}
public String getScreenshot1() {
return screenshot1;
}
public void setScreenshot1(String screenshot1) {
this.screenshot1 = screenshot1;
}
public String getScreenshot2() {
return screenshot2;
}
public void setScreenshot2(String screenshot2) {
this.screenshot2 = screenshot2;
}
public String getScreenshot3() {
return screenshot3;
}
public void setScreenshot3(String screenshot3) {
this.screenshot3 = screenshot3;
}
}

@ -0,0 +1,65 @@
/*
* 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.mdm.qsg.utils;
/**
* This class defines the constants used by the EMm-QSG package.
*/
public final class Constants {
public static final class DeviceType {
private DeviceType() {
throw new AssertionError();
}
public static final String ANDROID = "android";
public static final String WINDOWS = "windows";
public static final String IOS = "ios";
}
public static final class ContentType {
private ContentType() {
throw new AssertionError();
}
public static final String APPLICATION_JSON = "application/json";
public static final String APPLICATION_URL_ENCODED = "application/x-www-form-urlencoded";
}
public static final class Header {
private Header() {
throw new AssertionError();
}
public static final String AUTH = "Authorization";
public static final String CONTENT_TYPE = "Content-Type";
}
public static final class HTTPStatus {
private HTTPStatus() {
throw new AssertionError();
}
public static final int OK = 200;
public static final int CREATED = 201;
}
public static final String UTF_8 = "utf-8";
public static final String EMM_USER_ROLE = "emm-user";
}

@ -0,0 +1,437 @@
/*
* 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.mdm.qsg.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.wso2.mdm.qsg.dto.HTTPResponse;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
/**
* This class provides the utility methods to make a HTTP request.
*/
public class HTTPInvoker {
private static final String OAUTH_BEARER = "Bearer ";
public static String oAuthToken;
private static HttpClient createHttpClient()
throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
HttpClientBuilder b = HttpClientBuilder.create();
// setup a Trust Strategy that allows all certificates.
//
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
b.setSSLContext(sslContext);
//b.setSSLHostnameVerifier(new NoopHostnameVerifier());
// don't check Hostnames, either.
// -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
// here's the special part:
// -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
// -- and create a Registry, to register it.
//
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
// now, we create connection-manager using our Registry.
// -- allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
b.setConnectionManager(connMgr);
// finally, build the HttpClient;
// -- done!
CloseableHttpClient client = b.build();
return client;
}
public static HTTPResponse sendHTTPPostWithURLParams(String url, List<NameValuePair> params, HashMap<String, String>
headers) {
HttpPost post = null;
HttpResponse response = null;
CloseableHttpClient httpclient = null;
HTTPResponse httpResponse = new HTTPResponse();
try {
httpclient = (CloseableHttpClient) createHttpClient();
post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
for (String key : headers.keySet()) {
post.setHeader(key, headers.get(key));
}
response = httpclient.execute(post);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
BufferedReader rd = null;
try {
rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer result = new StringBuffer();
String line = "";
try {
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
httpResponse.setResponse(result.toString());
return httpResponse;
}
public static HTTPResponse sendHTTPPost(String url, String payload, HashMap<String, String>
headers) {
HttpPost post = null;
HttpResponse response = null;
HTTPResponse httpResponse = new HTTPResponse();
CloseableHttpClient httpclient = null;
try {
httpclient = (CloseableHttpClient) createHttpClient();
StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
post = new HttpPost(url);
post.setEntity(requestEntity);
for (String key : headers.keySet()) {
post.setHeader(key, headers.get(key));
}
response = httpclient.execute(post);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
BufferedReader rd = null;
try {
rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer result = new StringBuffer();
String line = "";
try {
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
httpResponse.setResponse(result.toString());
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
return httpResponse;
}
public static HTTPResponse sendHTTPPutWithOAuthSecurity(String url, String payload, HashMap<String, String>
headers) {
HttpPut put = null;
HttpResponse response = null;
HTTPResponse httpResponse = new HTTPResponse();
CloseableHttpClient httpclient = null;
try {
httpclient = (CloseableHttpClient) createHttpClient();
StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
put = new HttpPut(url);
put.setEntity(requestEntity);
for (String key : headers.keySet()) {
put.setHeader(key, headers.get(key));
}
put.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
response = httpclient.execute(put);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
BufferedReader rd = null;
try {
rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer result = new StringBuffer();
String line = "";
try {
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
httpResponse.setResponse(result.toString());
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
return httpResponse;
}
public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, String payload, HashMap<String, String>
headers) {
HttpPost post = null;
HttpResponse response = null;
HTTPResponse httpResponse = new HTTPResponse();
CloseableHttpClient httpclient = null;
try {
httpclient = (CloseableHttpClient) createHttpClient();
StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
post = new HttpPost(url);
post.setEntity(requestEntity);
for (String key : headers.keySet()) {
post.setHeader(key, headers.get(key));
}
post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
response = httpclient.execute(post);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
BufferedReader rd = null;
try {
rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer result = new StringBuffer();
String line = "";
try {
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
httpResponse.setResponse(result.toString());
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
return httpResponse;
}
public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, HttpEntity entity, HashMap<String, String>
headers) {
HttpPost post = null;
HttpResponse response = null;
HTTPResponse httpResponse = new HTTPResponse();
CloseableHttpClient httpclient = null;
try {
httpclient = (CloseableHttpClient) createHttpClient();
post = new HttpPost(url);
post.setEntity(entity);
for (String key : headers.keySet()) {
post.setHeader(key, headers.get(key));
}
post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
response = httpclient.execute(post);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
BufferedReader rd = null;
try {
rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer result = new StringBuffer();
String line = "";
try {
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
httpResponse.setResponse(result.toString());
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
return httpResponse;
}
public static HTTPResponse uploadFile(String url, String fileName, String fileContentType) {
HttpPost post = null;
HttpResponse response = null;
HTTPResponse httpResponse = new HTTPResponse();
CloseableHttpClient httpclient = null;
try {
httpclient = (CloseableHttpClient) createHttpClient();
post = new HttpPost(url);
File file = new File(fileName);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, fileContentType);
mpEntity.addPart("file", cbFile);
post.setEntity(mpEntity);
post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
//post.setHeader(Constants.Header.CONTENT_TYPE, "multipart/form-data");
post.setHeader("Accept", Constants.ContentType.APPLICATION_JSON);
response = httpclient.execute(post);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
BufferedReader rd = null;
try {
rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer result = new StringBuffer();
String line = "";
try {
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
httpResponse.setResponse(result.toString());
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
return httpResponse;
}
}

@ -0,0 +1,142 @@
/*
* 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.mdm.qsg.utils;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.mdm.qsg.dto.ClientCredentials;
import org.wso2.mdm.qsg.dto.EMMQSGConfig;
import org.wso2.mdm.qsg.dto.HTTPResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class holds the utility methods used by the EMM-QSG package.
*/
public class QSGUtils {
public static EMMQSGConfig initConfig() {
Properties props = new Properties();
InputStream input = null;
EMMQSGConfig emmConfig = null;
try {
input = new FileInputStream("config.properties");
// load a properties file and set the properties
props.load(input);
emmConfig = EMMQSGConfig.getInstance();
emmConfig.setEmmHost(props.getProperty("emm-host"));
emmConfig.setDcrEndPoint(props.getProperty("dcr-endpoint"));
emmConfig.setOauthEndPoint(props.getProperty("oauth-endpoint"));
emmConfig.setUsername(props.getProperty("username"));
emmConfig.setPassword(props.getProperty("password"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return emmConfig;
}
private static ClientCredentials getClientCredentials() {
ClientCredentials clientCredentials = null;
HashMap<String, String> headers = new HashMap<String, String>();
String dcrEndPoint = EMMQSGConfig.getInstance().getDcrEndPoint();
//Set the DCR payload
JSONObject obj = new JSONObject();
obj.put("owner", "admin");
obj.put("clientName", "qsg");
obj.put("grantType", "refresh_token password client_credentials");
obj.put("tokenScope", "user:view,user:manage,user:admin:reset-password,role:view,role:manage,policy:view," +
"policy:manage,application:manage,appm:create,appm:publish,appm:update,appm:read");
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_JSON);
HTTPResponse httpResponse = HTTPInvoker.sendHTTPPost(dcrEndPoint, obj.toJSONString(), headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.CREATED) {
try {
JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
clientCredentials = new ClientCredentials();
clientCredentials.setClientKey((String) jsonObject.get("client_id"));
clientCredentials.setClientSecret((String) jsonObject.get("client_secret"));
} catch (ParseException e) {
e.printStackTrace();
}
}
return clientCredentials;
}
public static String getOAuthToken() {
QSGUtils.initConfig();
ClientCredentials clientCredentials = getClientCredentials();
String authorizationStr = clientCredentials.getClientKey() + ":" + clientCredentials.getClientSecret();
String authHeader = "Basic " + new String(Base64.encodeBase64(authorizationStr.getBytes()));
HashMap<String, String> headers = new HashMap<String, String>();
//Set the form params
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", EMMQSGConfig.getInstance().getUsername()));
urlParameters.add(new BasicNameValuePair("password", EMMQSGConfig.getInstance().getPassword()));
urlParameters.add(new BasicNameValuePair("grant_type", "password"));
urlParameters.add(new BasicNameValuePair("scope",
"user:view user:manage user:admin:reset-password role:view role:manage policy:view policy:manage " +
"application:manage appm:create appm:publish appm:update appm:read"));
//Set the headers
headers.put(Constants.Header.CONTENT_TYPE, Constants.ContentType.APPLICATION_URL_ENCODED);
headers.put(Constants.Header.AUTH, authHeader);
HTTPResponse httpResponse = HTTPInvoker
.sendHTTPPostWithURLParams(EMMQSGConfig.getInstance().getOauthEndPoint(), urlParameters, headers);
if (httpResponse.getResponseCode() == Constants.HTTPStatus.OK) {
try {
JSONObject jsonObject = (JSONObject) new JSONParser().parse(httpResponse.getResponse());
return (String) jsonObject.get("access_token");
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
public static boolean isValidEmailAddress(String email) {
String emailPattern =
"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
Pattern p = Pattern.compile(emailPattern);
Matcher m = p.matcher(email);
return m.matches();
}
public static String getResourceId(String resourcePath) {
return resourcePath.substring(resourcePath.lastIndexOf('/') + 1);
}
}

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<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/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.iot</groupId>
<artifactId>wso2iot-core-parent</artifactId>
<version>3.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>wso2iot-core-scripts</artifactId>
<packaging>pom</packaging>
<name>WSO2 IoT - Core - Scripts</name>
<url>http://maven.apache.org</url>
<modules>
<module>mobile-qsg</module>
</modules>
</project>

@ -1012,6 +1012,17 @@
<artifactId>org.wso2.iot.core.admin.styles</artifactId>
<version>${product.iot.version}</version>
</dependency>
<!--mobile-qsg dependencies-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${apache.httpmime.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${apache.httpclient.version}</version>
</dependency>
<!-- ********************************* Analytics Distribution Features START ********************************* -->
@ -1677,6 +1688,9 @@
<!-- CDMF Analytics -->
<cdmf.analytics.version>1.0.4-SNAPSHOT</cdmf.analytics.version>
<apache.httpmime.version>4.2.5</apache.httpmime.version>
<apache.httpclient.version>4.5.2</apache.httpclient.version>
</properties>
<scm>

Loading…
Cancel
Save