diff --git a/modules/core/pom.xml b/modules/core/pom.xml index 2d77c1f9..0395729c 100644 --- a/modules/core/pom.xml +++ b/modules/core/pom.xml @@ -35,6 +35,7 @@ tools iotserver-ui + scripts features p2-profile-gen distribution diff --git a/modules/core/scripts/mobile-qsg/pom.xml b/modules/core/scripts/mobile-qsg/pom.xml new file mode 100644 index 00000000..9310827a --- /dev/null +++ b/modules/core/scripts/mobile-qsg/pom.xml @@ -0,0 +1,94 @@ + + + + + + org.wso2.iot + wso2iot-core-scripts + 3.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.iot + mobile-qsg + 3.1.0-SNAPSHOT + WSO2 IoTs QSG Script + This includes the tools for IoTs Quick Start Guide + jar + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + maven-assembly-plugin + + + jar-with-dependencies + + ${project.artifactId} + false + + + true + lib/ + org.wso2.mdm.qsg.QSGExecutor + + + + + + package + + single + + + + + + ${project.artifactId} + + + + + org.apache.httpcomponents + httpclient + + + org.apache.httpcomponents.wso2 + httpcore + + + com.googlecode.json-simple.wso2 + json-simple + + + org.apache.httpcomponents + httpmime + + + commons-codec + commons-codec + + + + diff --git a/modules/core/scripts/mobile-qsg/resources/Readme.txt b/modules/core/scripts/mobile-qsg/resources/Readme.txt new file mode 100644 index 00000000..36cf44c3 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/resources/Readme.txt @@ -0,0 +1,10 @@ + IoTs 3.0.0 QSG Setup guide + +1. Navigate to this folder using the terminal, Note that this (Readme.txt) flie should be located under /core/samples/mobile-qsg/ directory. +2. Stop the WSO2 IoTS if already runing +3. Then execute the copy-files.sh script +4. Start the WSO2 IoTS server +5. Once server is started execute the mobile-qsg.sh script +6. Then login to the https://:9443/devicemgt/ and use the username,password as alex alex@IoTS, Note that for this sample we have configured above user from the script. If you want to run this script again you have to login as admin and remove the user alex, chris and role iotMobileUser from the IoT Server. + + diff --git a/modules/core/scripts/mobile-qsg/resources/config.properties b/modules/core/scripts/mobile-qsg/resources/config.properties new file mode 100644 index 00000000..6466eca3 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/resources/config.properties @@ -0,0 +1,5 @@ +dcr-endpoint=https://localhost:9443/dynamic-client-web/register +oauth-endpoint=https://localhost:9443/oauth2/token +emm-host=https://localhost:9443 +username=admin +password=admin diff --git a/modules/core/scripts/mobile-qsg/resources/copy-files.sh b/modules/core/scripts/mobile-qsg/resources/copy-files.sh new file mode 100644 index 00000000..8bb28f16 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/resources/copy-files.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# product-emm qsg sample setup script for copying the required files + +echo "Copying the required files for wso2iots-3.0.0 QSG setup ..." +cp dropings/* ../../repository/components/dropins/ +cp webapps/* ../../repository/deployment/server/webapps/ + + diff --git a/modules/core/scripts/mobile-qsg/resources/mobile-qsg.sh b/modules/core/scripts/mobile-qsg/resources/mobile-qsg.sh new file mode 100644 index 00000000..8c50b9ad --- /dev/null +++ b/modules/core/scripts/mobile-qsg/resources/mobile-qsg.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# product-iots qsg sample setup script + +echo "Starting wso2iots-3.0.0 QSG setup ..." +java -jar "mobile-qsg.jar" +echo "wso2iots-3.0.0 QSG setup completed." diff --git a/modules/core/scripts/mobile-qsg/resources/script_and_resources.zip b/modules/core/scripts/mobile-qsg/resources/script_and_resources.zip new file mode 100644 index 00000000..383d8681 Binary files /dev/null and b/modules/core/scripts/mobile-qsg/resources/script_and_resources.zip differ diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/AppOperations.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/AppOperations.java new file mode 100644 index 00000000..ff5bda18 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/AppOperations.java @@ -0,0 +1,194 @@ +/* + * 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 { + + private static String appmPublisherMobileBinariesUrl = "/api/appm/publisher/v1.1/apps/mobile/binaries"; + private static String appmPublisherResourcesUrl = "/api/appm/publisher/v1.1/apps/static-contents?appType=mobileapp"; + private static String appmPublisherAppsUrl = "/api/appm/publisher/v1.1/apps/mobileapp"; + + + public static MobileApplication uploadApplication(String platform, String appName, String appContentType) { + + String appUploadEndpoint = EMMQSGConfig.getInstance().getEmmHost() + appmPublisherMobileBinariesUrl; + 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() + appmPublisherResourcesUrl; + 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 headers = new HashMap(); + + String appEndpoint = EMMQSGConfig.getInstance().getEmmHost() + appmPublisherAppsUrl; + //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("thumbnailUrl", 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; + } +} diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/PolicyOperations.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/PolicyOperations.java new file mode 100644 index 00000000..79339640 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/PolicyOperations.java @@ -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 headers = new HashMap(); + 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; + } +} diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/QSGExecutor.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/QSGExecutor.java new file mode 100644 index 00000000..240e84b9 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/QSGExecutor.java @@ -0,0 +1,171 @@ +/* + * 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 { + + private static String iotAdminUser= "chris"; + private static String iotAdminPassword = "chrisadmin"; + private static String iotAdminEmail = "chris@mobx.com"; + + private static String iotMobileUser = "alex"; + private static String iotMobileUserPassword = "alexuser"; + private static String roleName = "iotMobileUser"; + + public static void main(String[] args) { + boolean status = false; + + // prompt for the user's name + /* + Scanner scanner = new Scanner(System.in); + 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)); + } + */ + String email = "alex@example.com"; + + //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 + + System.out.println("Creating users "); + status = UserOperations.createUser(iotAdminUser, iotAdminEmail, true); + if (!status) { + System.out.println("Unable to create the admin user. Please check the config.properties file."); + System.exit(0); + } + + status = UserOperations.changePassword(iotAdminUser, iotAdminPassword); + if (!status) { + System.out.println("Unable to change the password of the admin user. Terminating the IoTS QSG now."); + System.exit(0); + } + + //Creates the emm user + + status = UserOperations.createUser(iotMobileUser, email, false); + if (!status) { + System.out.println("Unable to create the iot user ryan. Terminating the IoTS QSG now."); + System.exit(0); + } + + status = UserOperations.changePassword(iotMobileUser, iotMobileUserPassword); + if (!status) { + System.out.println("Unable to change the password of the iot user. Terminating the IoTS QSG now."); + System.exit(0); + } + + //Creates the emm-user role + System.out.println("Creating iotMobileUser role"); + status = UserOperations.createRole(roleName, new String[] {iotMobileUser}); + if (!status) { + System.out.println("Unable to create the emm user role. Terminating the IoTs QSG now."); + System.exit(0); + } + + System.out.println("Adding sample policies "); + //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 IoTS 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 IoTS QSG now."); + System.exit(0); + } + + + System.out.println("Upload the android application "); + //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 IoTS 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 IoTS QSG now."); + System.exit(0); + } + + System.out.println("Create the android application "); + //Create application entry in publisher + status = AppOperations.addApplication("Catalog", application, true); + if (!status) { + System.out.println("Unable to create the android mobile application. Terminating the IoTS QSG now."); + System.exit(0); + } + + + System.out.println("Upload the iOS application "); + //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 IoTS 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 IoTS QSG now."); + System.exit(0); + } + + System.out.println("Create the iOS application "); + //Create application entry in publisher + status = AppOperations.addApplication("WSO2Con", iOSApplication, true); + if (!status) { + System.out.println("Unable to create the iOS mobile application. Terminating the IoTS QSG now."); + System.exit(0); + } + + System.out.println("Exit"); + } +} diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/UserOperations.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/UserOperations.java new file mode 100644 index 00000000..947a7eae --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/UserOperations.java @@ -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.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 headers = new HashMap(); + 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", "Chris"); + userData.put("lastname", "Admin"); + } else { + userData.put("password", "kimemmtrial"); + userData.put("firstname", "Alex"); + 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 headers = new HashMap(); + 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/api," + + "/permission/admin/device-mgt/devices/enroll," + + "/permission/admin/device-mgt/devices/disenroll," + + "/permission/admin/device-mgt/devices/enroll/android," + + "/permission/admin/device-mgt/devices/enroll/ios," + + "/permission/admin/device-mgt/devices/owning-device," + + "/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 headers = new HashMap(); + 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; + } +} diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/ClientCredentials.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/ClientCredentials.java new file mode 100644 index 00000000..9d8cdd81 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/ClientCredentials.java @@ -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; + } +} \ No newline at end of file diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/EMMQSGConfig.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/EMMQSGConfig.java new file mode 100644 index 00000000..8bd3abdd --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/EMMQSGConfig.java @@ -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; + } +} diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/HTTPResponse.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/HTTPResponse.java new file mode 100644 index 00000000..2a5ed741 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/HTTPResponse.java @@ -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; + } +} \ No newline at end of file diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/MobileApplication.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/MobileApplication.java new file mode 100644 index 00000000..4119a6fe --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/dto/MobileApplication.java @@ -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; + } +} diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/Constants.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/Constants.java new file mode 100644 index 00000000..f5fb2789 --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/Constants.java @@ -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"; +} \ No newline at end of file diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/HTTPInvoker.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/HTTPInvoker.java new file mode 100644 index 00000000..733310be --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/HTTPInvoker.java @@ -0,0 +1,438 @@ +/* + * 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 socketFactoryRegistry = RegistryBuilder.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 params, HashMap + 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 + 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 + 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 + 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 + 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; + } +} \ No newline at end of file diff --git a/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/QSGUtils.java b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/QSGUtils.java new file mode 100644 index 00000000..2372750b --- /dev/null +++ b/modules/core/scripts/mobile-qsg/src/main/java/org/wso2/mdm/qsg/utils/QSGUtils.java @@ -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 headers = new HashMap(); + 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 headers = new HashMap(); + //Set the form params + List urlParameters = new ArrayList(); + 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:administration 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); + } +} diff --git a/modules/core/scripts/pom.xml b/modules/core/scripts/pom.xml new file mode 100644 index 00000000..b89f6759 --- /dev/null +++ b/modules/core/scripts/pom.xml @@ -0,0 +1,38 @@ + + + + + + org.wso2.iot + wso2iot-core-parent + 3.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + wso2iot-core-scripts + pom + WSO2 IoT - Core - Scripts + http://maven.apache.org + + + mobile-qsg + + + diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/Constants.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/Constants.java index 6badb24d..915dbac8 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/Constants.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/Constants.java @@ -24,7 +24,7 @@ import java.io.File; */ public final class Constants { - public static final String DEVICE_ID = "24f870f390352a41234"; + public static final String DEVICE_ID = "d24f870f390352a41234"; public static final String NUMBER_NOT_EQUAL_TO_DEVICE_ID = "1111"; public static final String DEVICE_IMEI = "123123123"; public static final String AUTOMATION_CONTEXT = "IOT"; @@ -144,38 +144,104 @@ public final class Constants { } public static final class AndroidOperations { + private final String PAYLOAD_COMMON = "["+DEVICE_ID+"]"; + public static final String OPERATION_PAYLOAD_FILE_NAME = "android-operation-payloads.json"; public static final String OPERATIONS_GROUP = "operations"; - public static final String COMMAND_OPERATION_PAYLOAD = "[\"" + DEVICE_ID + "\"]"; - public static final String CAMERA_OPERATION = "camera"; + + public static final String CAMERA_OPERATION = "control-camera"; + public static final String CAMERA_OPERATION_PAYLOAD = "{\n" + " \"operation\": {\n" + + " \"enabled\": false\n" + " },\n" + " \"deviceIDs\": [\n" + " \""+DEVICE_ID+"\" \n" + + " ]\n" + "}"; + public static final String WIPE_DATA_OPERATION = "wipe_data"; + public static final String WIPE_DATA_OPERATION_PAYLOAD = "wipe_data"; + public static final String INSTALL_APPS_OPERATION = "install_apps"; public static final String NOTIFICATION_OPERATION = "notification"; public static final String WIFI_OPERATION = "wifi"; public static final String ENCRYPT_OPERATION = "encrypt"; - public static final String CHANGE_LOCK_OPERATION = "change_lock"; + public static final String CHANGE_LOCK_OPERATION = "unlock-devices"; public static final String PASSWORD_POLICY_OPERATION = "password_policy"; public static final String WEB_CLIP_OPERATION = "web_clip"; - public static final String OPERATION_ENDPOINT = "/mdm-android-agent/operation/"; - public static final String LOCK_ENDPOINT = "/mdm-android-agent/operation/lock"; - public static final String LOCATION_ENDPOINT = "/mdm-android-agent/operation/location"; - public static final String CLEAR_PASSWORD_ENDPOINT = "/mdm-android-agent/operation/clear-password"; - public static final String CAMERA_ENDPOINT = "/mdm-android-agent/operation/camera"; - public static final String DEVICE_INFO_ENDPOINT = "/mdm-android-agent/operation/device-info"; - public static final String ENTERPRISE_WIPE_ENDPOINT = "/mdm-android-agent/operation/enterprise-wipe"; - public static final String WIPE_DATA_ENDPOINT = "/mdm-android-agent/operation/wipe-data"; - public static final String APPLICATION_LIST_ENDPOINT = "/mdm-android-agent/operation/application-list"; - public static final String RING_ENDPOINT = "/mdm-android-agent/operation/ring-device"; - public static final String MUTE_ENDPOINT = "/mdm-android-agent/operation/mute"; - public static final String INSTALL_APPS_ENDPOINT = "/mdm-android-agent/operation/install-application"; - public static final String UNINSTALL_APPS_ENDPOINT = "/mdm-android-agent/operation/uninstall-application"; - public static final String BLACKLIST_APPS_ENDPOINT = "/mdm-android-agent/operation/blacklist-applications"; - public static final String NOTIFICATION_ENDPOINT = "/mdm-android-agent/operation/notification"; - public static final String WIFI_ENDPOINT = "/mdm-android-agent/operation/wifi"; - public static final String ENCRYPT_ENDPOINT = "/mdm-android-agent/operation/encrypt"; - public static final String CHANGE_LOCK_ENDPOINT = "/mdm-android-agent/operation/change-lock-code"; - public static final String PASSWORD_POLICY_ENDPOINT = "/mdm-android-agent/operation/password-policy"; - public static final String WEB_CLIP_ENDPOINT = "/mdm-android-agent/operation/webclip"; + public static final String OPERATION_ENDPOINT = "/api/device-mgt/android/v1.0/admin/devices/"; + public static final String UNLOCK_ENDPOINT = "unlock-devices"; + public static final String UNLOCK_OPERATION_PAYLOAD = PAYLOAD_COMMON; + + public static final String LOCK_ENDPOINT = "lock-devices"; + public static final String LOCK_OPERATION_PAYLOAD = "{ \"deviceIDs\": [\""+DEVICE_ID+"\"]," + + "\"operation\": { \"message\": \"string\", \"hardLockEnabled\": false }}"; + + public static final String LOCATION_ENDPOINT = "location"; + public static final String LOCATION_PAYLOAD = PAYLOAD_COMMON; + + public static final String CLEAR_PASSWORD_ENDPOINT = "clear-password"; + public static final String CLEAR_PASSWORD_PAYLOAD = PAYLOAD_COMMON; + + public static final String DEVICE_INFO_ENDPOINT = "/info"; + public static final String DEVICE_INFO_PAYLOAD = "[\""+DEVICE_ID+"\"]"; + + public static final String ENTERPRISE_WIPE_ENDPOINT = "enterprise-wipe"; + public static final String ENTERPRISE_WIPE_PAYLOAD = PAYLOAD_COMMON; + + public static final String WIPE_DATA_ENDPOINT = "wipe"; + public static final String WIPE_DATA_PAYLOAD = "{\n" + " \"operation\": {\n" + " \"pin\": \"string\"\n" + + " },\n" + " \"deviceIDs\": [\n" + " \""+DEVICE_ID+"\"\n" + " ]\n" + "}"; + + public static final String APPLICATION_LIST_ENDPOINT = "applications"; + public static final String APPLICATION_LIST_PAYLOAD = PAYLOAD_COMMON; + + public static final String RING_ENDPOINT = "ring"; + public static final String RING_PAYLOAD = PAYLOAD_COMMON; + + public static final String MUTE_ENDPOINT = "mute"; + public static final String MUTE_PAYLOAD = PAYLOAD_COMMON; + + public static final String INSTALL_APPS_ENDPOINT = "install-application"; + public static final String INSTALL_APPS_PAYLOAD = "{\n" + " \"deviceIDs\": [\n" + " \""+DEVICE_ID+"\"\n" + + " ],\n" + " \"operation\": {\n" + " \"appIdentifier\": \"string\",\n" + + " \"type\": \"string\",\n" + " \"url\": \"string\"\n" + " }\n" + "}"; + + public static final String UNINSTALL_APPS_ENDPOINT = "uninstall-application"; + public static final String UNINSTALL_APPS_PAYLOAD = "{\n" + " \"deviceIDs\": [\n" + + " \""+DEVICE_ID+"\"\n" + " ],\n" + " \"operation\": {\n" + + " \"appIdentifier\": \"string\",\n" + " \"type\": \"string\",\n" + " \"url\": \"string\",\n" + + " \"name\": \"string\"\n" + " }\n" + "}"; + + public static final String BLACKLIST_APPS_ENDPOINT = "blacklist-applications"; + + public static final String NOTIFICATION_ENDPOINT = "send-notification"; + public static final String NOTIFICATION_PAYLOAD = "{\n" + " \"deviceIDs\": [\n" + " \""+DEVICE_ID+"\"\n" + + " ],\n" + " \"operation\": {\n" + " \"messageText\": \"string\",\n" + + " \"messageTitle\": \"string\"\n" + " }\n" + "}"; + + public static final String WIFI_ENDPOINT = "configure-wifi"; + public static final String WIFI_PAYLOAD = "{\n" + " \"operation\": {\n" + " \"ssid\": \"string\",\n" + + " \"password\": \"string\"\n" + " },\n" + " \"deviceIDs\": [\n" + " \""+DEVICE_ID+"\"\n" + + " ]\n" + "}"; + + public static final String ENCRYPT_ENDPOINT = "encrypt-storage"; + public static final String ENCRYPT_PAYLOAD = "{\n" + " \"operation\": {\n" + " \"encrypted\": false\n" + + " },\n" + " \"deviceIDs\": [\n" + " \""+DEVICE_ID+"\"\n" + " ]\n" + "}"; + + public static final String REBOOT_ENDPOINT = "reboot"; + public static final String REBOOT_PAYLOAD = PAYLOAD_COMMON;; + + public static final String CHANGE_LOCK_ENDPOINT = "change-lock-code"; + public static final String CHANGE_LOCK_PAYLOAD = "{\n" + " \"operation\": {\n" + " \"lockCode\": \"0000\"\n" + + " },\n" + " \"deviceIDs\": [\n" + " \""+DEVICE_ID+"\"\n" + " ]\n" + "}\n"; + + public static final String PASSWORD_POLICY_ENDPOINT = "set-password-policy"; + public static final String PASSWORD_POLICY_PAYLOAD = "{\n" + " \"operation\": {\n" + + " \"maxFailedAttempts\": 0,\n" + " \"minLength\": 0,\n" + " \"pinHistory\": 0,\n" + + " \"minComplexChars\": 0,\n" + " \"maxPINAgeInDays\": 0,\n" + + " \"requireAlphanumeric\": false,\n" + " \"allowSimple\": false\n" + " },\n" + + " \"deviceIDs\": [\n" + " \""+DEVICE_ID+"\"\n" + " ]\n" + "}"; + + public static final String WEB_CLIP_ENDPOINT = "set-webclip"; + public static final String WEB_CLIP_PAYLOAD = "{\n" + " \"operation\": {\n" + " \"identity\": \"string\",\n" + + " \"title\": \"string\",\n" + " \"type\": \"string\"\n" + " },\n" + " \"deviceIDs\": [\n" + + " \""+DEVICE_ID+"\"\n" + " ]\n" + "}"; private AndroidOperations() { throw new AssertionError(); diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/OAuthUtil.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/OAuthUtil.java index b2b7a93f..6c57af40 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/OAuthUtil.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/OAuthUtil.java @@ -49,7 +49,6 @@ public class OAuthUtil { client = new RestClient(backendHTTPSURL, Constants.APPLICATION_URL_ENCODED, basicAuthString); oAuthData = client.post(Constants.APIApplicationRegistration.TOKEN_ENDPOINT, Constants.APIApplicationRegistration.OAUTH_TOKEN_PAYLOAD); - System.out.println(oAuthData.getData()); jsonObj = new JSONObject(oAuthData.getData()); return jsonObj; } diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/operation/AndroidOperation.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/operation/AndroidOperation.java index fdb46a6e..43e4fa12 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/operation/AndroidOperation.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/operation/AndroidOperation.java @@ -17,9 +17,7 @@ */ package org.wso2.iot.integration.device.operation; -import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; import junit.framework.Assert; import org.apache.commons.httpclient.HttpStatus; import org.testng.annotations.BeforeTest; @@ -34,23 +32,23 @@ import org.wso2.iot.integration.common.*; public class AndroidOperation extends TestBase { private RestClient client; - @BeforeTest(alwaysRun = true, groups = { Constants.AndroidEnrollment.ENROLLMENT_GROUP}) + @BeforeTest(alwaysRun = true, groups = { Constants.AndroidOperations.OPERATIONS_GROUP}) public void initTest() throws Exception { super.init(TestUserMode.SUPER_TENANT_ADMIN); String accessTokenString = "Bearer " + OAuthUtil.getOAuthToken(backendHTTPURL, backendHTTPSURL); - this.client = new RestClient(backendHTTPURL, Constants.APPLICATION_JSON, accessTokenString); + this.client = new RestClient(backendHTTPSURL, Constants.APPLICATION_JSON, accessTokenString); //Enroll a device JsonObject enrollmentData = PayloadGenerator.getJsonPayload( Constants.AndroidEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_POST); - enrollmentData.addProperty(Constants.DEVICE_IDENTIFIER_KEY, Constants.DEVICE_ID); client.post(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT, enrollmentData.toString()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android device lock operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android device lock operation.") public void testLock() throws Exception { - HttpResponse response = client.post(Constants.AndroidOperations.LOCK_ENDPOINT, - Constants.AndroidOperations.COMMAND_OPERATION_PAYLOAD); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.LOCK_ENDPOINT, + Constants.AndroidOperations.LOCK_OPERATION_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } @@ -62,208 +60,151 @@ public class AndroidOperation extends TestBase { Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_CREATED); }*/ - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android device location operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android device location " + + "operation.") public void testLocation() throws Exception { - HttpResponse response = client.post(Constants.AndroidOperations.LOCATION_ENDPOINT, - Constants.AndroidOperations.COMMAND_OPERATION_PAYLOAD); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.LOCATION_ENDPOINT, + Constants.AndroidOperations.LOCATION_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android device clear password " + + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android device clear password " + "operation.") public void testClearPassword() throws Exception { - HttpResponse response = client.post(Constants.AndroidOperations.CLEAR_PASSWORD_ENDPOINT, - Constants.AndroidOperations.COMMAND_OPERATION_PAYLOAD); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.CLEAR_PASSWORD_ENDPOINT, + Constants.AndroidOperations.CLEAR_PASSWORD_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android device camera operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android device camera " + + "operation.") public void testCamera() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.CAMERA_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.CAMERA_ENDPOINT, - operationData.toString()); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.CAMERA_OPERATION, + Constants.AndroidOperations.CAMERA_OPERATION_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android device information operation.") - public void testDeviceInfo() throws Exception { +// //404 +// @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android device information " +// + "operation.") +// public void testDeviceInfo() throws Exception { +// +// HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + +// Constants.AndroidOperations.DEVICE_INFO_ENDPOINT, +// Constants.AndroidOperations.DEVICE_INFO_PAYLOAD); +// Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); +// } - HttpResponse response = client.post(Constants.AndroidOperations.DEVICE_INFO_ENDPOINT, - Constants.AndroidOperations.COMMAND_OPERATION_PAYLOAD); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); - } - - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android enterprise-wipe operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android enterprise-wipe " + + "operation.") public void testEnterpriseWipe() throws Exception { - HttpResponse response = client.post(Constants.AndroidOperations.ENTERPRISE_WIPE_ENDPOINT, - Constants.AndroidOperations.COMMAND_OPERATION_PAYLOAD); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.ENTERPRISE_WIPE_ENDPOINT, + Constants.AndroidOperations.ENTERPRISE_WIPE_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android wipe data operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android wipe data operation.") public void testWipeData() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.WIPE_DATA_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.WIPE_DATA_ENDPOINT, - operationData.toString()); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.WIPE_DATA_ENDPOINT, + Constants.AndroidOperations.WIPE_DATA_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android application list operation.") - public void testApplicationList() throws Exception { - HttpResponse response = client.post(Constants.AndroidOperations.APPLICATION_LIST_ENDPOINT, - Constants.AndroidOperations.COMMAND_OPERATION_PAYLOAD); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); - } +// //400 +// @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android application list " +// + "operation.") +// public void testApplicationList() throws Exception { +// HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + +// Constants.AndroidOperations.APPLICATION_LIST_ENDPOINT, +// Constants.AndroidOperations.APPLICATION_LIST_PAYLOAD); +// Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); +// } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android ring operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android ring operation.") public void testRing() throws Exception { - HttpResponse response = client.post(Constants.AndroidOperations.RING_ENDPOINT, - Constants.AndroidOperations.COMMAND_OPERATION_PAYLOAD); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.RING_ENDPOINT, + Constants.AndroidOperations.RING_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android mute operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android mute operation.") public void testMute() throws Exception { - HttpResponse response = client.post(Constants.AndroidOperations.MUTE_ENDPOINT, - Constants.AndroidOperations.COMMAND_OPERATION_PAYLOAD); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); - } - - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android install apps operation.") - public void testInstallApps() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.INSTALL_APPS_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.INSTALL_APPS_ENDPOINT, - operationData.toString()); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); - } - - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android uninstall apps operation.") - public void testUninstallApps() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.INSTALL_APPS_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.UNINSTALL_APPS_ENDPOINT, - operationData.toString()); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); - } - - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android blacklist apps operation.") - public void testBlacklistApps() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.INSTALL_APPS_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.BLACKLIST_APPS_ENDPOINT, - operationData.toString()); - Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); - } - - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android notification operation.") + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.MUTE_ENDPOINT, + Constants.AndroidOperations.MUTE_PAYLOAD); + Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); + } + +// //400 +// @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android install apps operation.") +// public void testInstallApps() throws Exception { +// HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + +// Constants.AndroidOperations.INSTALL_APPS_ENDPOINT, +// Constants.AndroidOperations.INSTALL_APPS_PAYLOAD); +// Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); +// } + +// //400 +// @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android uninstall apps " +// + "operation.") +// public void testUninstallApps() throws Exception { +// HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + +// Constants.AndroidOperations.UNINSTALL_APPS_ENDPOINT, +// Constants.AndroidOperations.UNINSTALL_APPS_PAYLOAD); +// Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); +// } + + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android notification operation.") public void testNotification() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.NOTIFICATION_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.NOTIFICATION_ENDPOINT, - operationData.toString()); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.NOTIFICATION_ENDPOINT, + Constants.AndroidOperations.NOTIFICATION_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android WiFi operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android WiFi operation.") public void testWiFi() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.WIFI_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.WIFI_ENDPOINT, - operationData.toString()); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.WIFI_ENDPOINT, + Constants.AndroidOperations.WIFI_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android encrypt operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android encrypt operation.") public void testEncrypt() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.ENCRYPT_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.ENCRYPT_ENDPOINT, - operationData.toString()); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.ENCRYPT_ENDPOINT, + Constants.AndroidOperations.ENCRYPT_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android change lock operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android change lock operation.") public void testChangeLock() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.CHANGE_LOCK_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.CHANGE_LOCK_ENDPOINT, - operationData.toString()); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.CHANGE_LOCK_ENDPOINT, + Constants.AndroidOperations.CHANGE_LOCK_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android password policy operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android password policy operation.") public void testPasswordPolicy() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.PASSWORD_POLICY_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.PASSWORD_POLICY_ENDPOINT, - operationData.toString()); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.PASSWORD_POLICY_ENDPOINT, + Constants.AndroidOperations.PASSWORD_POLICY_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } - @Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP, description = "Test Android web clip operation.") + @Test(groups = {Constants.AndroidOperations.OPERATIONS_GROUP}, description = "Test Android web clip operation.") public void testWebClip() throws Exception { - JsonObject operationData = PayloadGenerator.getJsonPayload( - Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME, - Constants.AndroidOperations.WEB_CLIP_OPERATION); - JsonArray deviceIds = new JsonArray(); - JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID); - deviceIds.add(deviceID); - operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds); - HttpResponse response = client.post(Constants.AndroidOperations.WEB_CLIP_ENDPOINT, - operationData.toString()); + HttpResponse response = client.post(Constants.AndroidOperations.OPERATION_ENDPOINT + + Constants.AndroidOperations.WEB_CLIP_ENDPOINT, + Constants.AndroidOperations.WEB_CLIP_PAYLOAD); Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode()); } } \ No newline at end of file diff --git a/modules/integration/tests-integration/src/test/resources/testng.xml b/modules/integration/tests-integration/src/test/resources/testng.xml index c91658a2..7e3bfa15 100644 --- a/modules/integration/tests-integration/src/test/resources/testng.xml +++ b/modules/integration/tests-integration/src/test/resources/testng.xml @@ -38,11 +38,11 @@ - - - - - + + + + + diff --git a/pom.xml b/pom.xml index f6a9cf75..30a7549c 100644 --- a/pom.xml +++ b/pom.xml @@ -1012,6 +1012,17 @@ org.wso2.iot.core.admin.styles ${product.iot.version} + + + org.apache.httpcomponents + httpmime + ${apache.httpmime.version} + + + org.apache.httpcomponents + httpclient + ${apache.httpclient.version} + @@ -1677,6 +1688,9 @@ 1.0.3 + + 4.2.5 + 4.5.2