diff --git a/modules/core/distribution/src/repository/conf/app-manager.xml b/modules/core/distribution/src/repository/conf/app-manager.xml index 106046b4..246b410d 100644 --- a/modules/core/distribution/src/repository/conf/app-manager.xml +++ b/modules/core/distribution/src/repository/conf/app-manager.xml @@ -414,14 +414,13 @@ MDM running on separate JVM. Calls MDM methods via secured REST API. Use this when run Store/Publisher/MDM in deployed in separate JVMs. This will be the most suitable active MDM when deployed on production environment. --> - + /store/extensions/assets/mobileapp/resources/models/%s.png - https://localhost:9443/mdm-admin - https://localhost:9443/oauth2/token - WjLm24IxBVLF0oz0VJfmtJbjJbka - v3KkIQXkJ1SDp_Bf8uUQxu5p7TQa - admin - admin + https://localhost:9443 + https://localhost:9443/oauth2 + admin + admin + 100 diff --git a/modules/core/distribution/src/repository/conf/security/Owasp.CsrfGuard.Carbon.properties b/modules/core/distribution/src/repository/conf/security/Owasp.CsrfGuard.Carbon.properties index 62cb1c57..131b993f 100644 --- a/modules/core/distribution/src/repository/conf/security/Owasp.CsrfGuard.Carbon.properties +++ b/modules/core/distribution/src/repository/conf/security/Owasp.CsrfGuard.Carbon.properties @@ -471,7 +471,7 @@ org.owasp.csrfguard.unprotected.storeAcs=%servletContext%/store/acs org.owasp.csrfguard.unprotected.apiStoreAcs=%servletContext%/api-store/acs org.owasp.csrfguard.unprotected.apiStoreApis=%servletContext%/api-store/apis org.owasp.csrfguard.unprotected.portalAcs=%servletContext%/portal/acs -org.owasp.csrfguard.unprotected.portalApis=%servletContext%/portal/apis +org.owasp.csrfguard.unprotected.portalApis=%servletContext%/portal/apis/* org.owasp.csrfguard.unprotected.socialAcs=%servletContext%/social/acs org.owasp.csrfguard.unprotected.socialApis=%servletContext%/social/apis org.owasp.csrfguard.unprotected.appStoreDevices=%servletContext%/store/apps/devices/* diff --git a/modules/core/p2-profile-gen/pom.xml b/modules/core/p2-profile-gen/pom.xml index 72a450dc..08a9855b 100644 --- a/modules/core/p2-profile-gen/pom.xml +++ b/modules/core/p2-profile-gen/pom.xml @@ -432,6 +432,9 @@ org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.appmgt.mdm.osgiconnector.feature:${carbon.device.mgt.plugin.version} + + org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.appmgt.mdm.restconnector.feature:${carbon.device.mgt.plugin.version} + @@ -459,9 +462,6 @@ org.wso2.carbon.store:org.wso2.carbon.social.feature:${carbon.store.version} - - org.wso2.carbon.appmgt:org.wso2.carbon.appmgt.mdm.restconnector.feature:${appmgt.feature.version} - @@ -844,6 +844,10 @@ org.wso2.carbon.appmgt.mdm.osgiconnector.feature.group ${carbon.device.mgt.plugin.version} + + org.wso2.carbon.appmgt.mdm.restconnector.feature.group + ${carbon.device.mgt.plugin.version} + @@ -859,10 +863,6 @@ org.wso2.carbon.appmgt.mdm.wso2emm.feature.group ${appmgt.feature.version} - - org.wso2.carbon.appmgt.mdm.restconnector.feature.group - ${appmgt.feature.version} - org.wso2.carbon.appmgt.mobile.feature.group ${appmgt.feature.version} @@ -1589,10 +1589,6 @@ org.wso2.carbon.appmgt.mdm.wso2emm.feature.group ${appmgt.feature.version} - - org.wso2.carbon.appmgt.mdm.restconnector.feature.group - ${appmgt.feature.version} - org.wso2.carbon.appmgt.mobile.feature.group ${appmgt.feature.version} @@ -1605,6 +1601,10 @@ org.wso2.carbon.appmgt.mdm.osgiconnector.feature.group ${carbon.device.mgt.plugin.version} + + org.wso2.carbon.appmgt.mdm.restconnector.feature.group + ${carbon.device.mgt.plugin.version} + org.apache.axis2.transport.mail.feature.group @@ -1998,10 +1998,6 @@ org.wso2.carbon.appmgt.mdm.wso2emm.feature.group ${appmgt.feature.version} - - org.wso2.carbon.appmgt.mdm.restconnector.feature.group - ${appmgt.feature.version} - org.wso2.carbon.appmgt.mobile.feature.group ${appmgt.feature.version} @@ -2014,6 +2010,10 @@ org.wso2.carbon.appmgt.mdm.osgiconnector.feature.group ${carbon.device.mgt.plugin.version} + + org.wso2.carbon.appmgt.mdm.restconnector.feature.group + ${carbon.device.mgt.plugin.version} + org.wso2.carbon.tenant.mgt.common.feature.group @@ -2490,10 +2490,6 @@ org.wso2.carbon.appmgt.mdm.wso2emm.feature.group ${appmgt.feature.version} - - org.wso2.carbon.appmgt.mdm.restconnector.feature.group - ${appmgt.feature.version} - org.wso2.carbon.appmgt.mobile.feature.group ${appmgt.feature.version} @@ -2506,6 +2502,10 @@ org.wso2.carbon.appmgt.mdm.osgiconnector.feature.group ${carbon.device.mgt.plugin.version} + + org.wso2.carbon.appmgt.mdm.restconnector.feature.group + ${carbon.device.mgt.plugin.version} + @@ -3168,10 +3168,6 @@ org.wso2.carbon.appmgt.mdm.wso2emm.feature.group ${appmgt.feature.version} - - org.wso2.carbon.appmgt.mdm.restconnector.feature.group - ${appmgt.feature.version} - org.wso2.carbon.appmgt.mobile.feature.group ${appmgt.feature.version} @@ -3184,6 +3180,10 @@ org.wso2.carbon.appmgt.mdm.osgiconnector.feature.group ${carbon.device.mgt.plugin.version} + + org.wso2.carbon.appmgt.mdm.restconnector.feature.group + ${carbon.device.mgt.plugin.version} + 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/pom.xml b/modules/integration/pom.xml index 0356182d..72e02fa3 100644 --- a/modules/integration/pom.xml +++ b/modules/integration/pom.xml @@ -34,7 +34,7 @@ tests-artifacts tests-common tests-integration - tests-iot-web-ui + diff --git a/modules/integration/tests-integration/pom.xml b/modules/integration/tests-integration/pom.xml index 57a0e5bd..b830d057 100644 --- a/modules/integration/tests-integration/pom.xml +++ b/modules/integration/tests-integration/pom.xml @@ -16,8 +16,7 @@ ~ specific language governing permissions and limitations ~ under the License. --> - + org.wso2.iot wso2iot-integration @@ -31,8 +30,6 @@ Backend Integration Tests for WSO2 IOT Server. jar - - @@ -46,7 +43,7 @@ src/test/resources/testng.xml - ${skipTests} + @@ -247,10 +244,6 @@ - - org.wso2.iot - org.wso2.carbon.iot.core.integration.ui.pages - org.wso2.carbon.automation org.wso2.carbon.automation.engine @@ -269,8 +262,8 @@ - - true - + + + 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 920bd879..d80a0042 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 = "1234"; + 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"; @@ -33,6 +33,7 @@ public final class Constants { public static final String OAUTH_CLIENT_ID = "client_id"; public static final String OAUTH_CLIENT_SECRET = "client_secret"; public static final String OAUTH_ACCESS_TOKEN = "access_token"; + public static final String SCOPE = "scope"; public static final String ANDROID_DEVICE_TYPE = "android"; public static final String HTTP_METHOD_POST = "POST"; public static final String HTTP_METHOD_PUT = "PUT"; @@ -61,6 +62,36 @@ public final class Constants { + " \"applicationName\":\"app_12345\",\n" + " \"isAllowedToAllDomains\":false,\n" + " \"tags\":[\"android\", \"device_management\"],\n" + " \"isMappingAnExistingOAuthApp\":false\n" + "}").toString(); + public static final String PERMISSION_LIST = "default perm:admin-groups:count perm:admin-groups:view " + + "perm:admin-users:view perm:admin:certificates:add perm:admin:certificates:delete " + + "perm:admin:certificates:details perm:admin:certificates:verify perm:admin:certificates:view " + + "perm:admin:devices:view perm:android:blacklist-applications perm:android:change-lock-code " + + "perm:android:clear-password perm:android:configure-vpn perm:android:configure-wifi " + + "perm:android:control-camera perm:android:disenroll perm:android:encrypt-storage " + + "perm:android:enroll perm:android:enterprise-wipe perm:android:info " + + "perm:android:install-application perm:android:location perm:android:lock-devices " + + "perm:android:logcat perm:android:manage-configuration perm:android:mute perm:android:reboot " + + "perm:android:ring perm:android:send-notification perm:android:set-password-policy " + + "perm:android:set-webclip perm:android:uninstall-application perm:android:unlock-devices " + + "perm:android:update-application perm:android:upgrade-firmware perm:android:view-configuration " + + "perm:android:wipe perm:applications:install perm:applications:uninstall perm:dashboard:by-groups " + + "perm:dashboard:count-overview perm:dashboard:details perm:dashboard:device-counts " + + "perm:dashboard:feature-non-compliant perm:dashboard:filtered-count perm:dashboard:non-compliant " + + "perm:dashboard:non-compliant-count perm:dashboard:vulnerabilities perm:device-types:features " + + "perm:device-types:types perm:devices:applications perm:devices:compliance-data perm:devices:delete" + + " perm:devices:details perm:devices:effective-policy perm:devices:features perm:devices:operations " + + "perm:devices:search perm:devices:update perm:devices:view perm:get-activity perm:groups:add " + + "perm:groups:assign perm:groups:count perm:groups:device perm:groups:devices " + + "perm:groups:devices-add perm:groups:devices-count perm:groups:devices-remove perm:groups:groups " + + "perm:groups:groups-view perm:groups:remove perm:groups:roles perm:groups:share perm:groups:update " + + "perm:manage-configuration perm:notifications:mark-checked perm:notifications:view " + + "perm:policies:activate perm:policies:changes perm:policies:deactivate perm:policies:get-details " + + "perm:policies:get-policy-details perm:policies:manage perm:policies:priorities " + + "perm:policies:remove perm:policies:update perm:roles:add perm:roles:add-users " + + "perm:roles:create-combined-role perm:roles:delete perm:roles:details perm:roles:permissions " + + "perm:roles:update perm:roles:view perm:users:add perm:users:count perm:users:credentials " + + "perm:users:delete perm:users:details perm:users:is-exist perm:users:roles perm:users:search " + + "perm:users:send-invitation perm:users:update perm:users:user-details perm:view-configuration"; private APIApplicationRegistration() { throw new AssertionError(); @@ -113,38 +144,104 @@ public final class Constants { } public static final class AndroidOperations { + private static 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(); @@ -202,6 +299,7 @@ public final class Constants { public static final String VIEW_DEVICE_TYPES_ENDPOINT = "/mdm-admin/devices/types"; public static final String VIEW_DEVICE_RESPONSE_PAYLOAD_FILE_NAME = "mobile-device-mgt-view-device-types-response-payloads.json"; + public static final String NO_DEVICE = "{\"devices\":[],\"count\":0}"; private MobileDeviceManagement() { 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 dc93dedf..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 @@ -27,10 +27,17 @@ import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; */ public class OAuthUtil { - public static String getOAuthToken(String backendHTTPURL, String backendHTTPSURL) - throws Exception { - RestClient client = new RestClient(backendHTTPURL, Constants.APPLICATION_JSON); - client.setHttpHeader("Authorization", "Basic YWRtaW46YWRtaW4="); + public static String getScopes(String backendHTTPURL, String backendHTTPSURL) throws Exception { + return getOAuthTokenPair(backendHTTPURL, backendHTTPSURL).get(Constants.SCOPE).toString(); + } + + public static String getOAuthToken(String backendHTTPURL, String backendHTTPSURL) throws Exception { + return getOAuthTokenPair(backendHTTPURL, backendHTTPSURL).get(Constants.OAUTH_ACCESS_TOKEN).toString(); + } + + public static JSONObject getOAuthTokenPair(String backendHTTPURL, String backendHTTPSURL) throws Exception { + String AuthString = "Basic YWRtaW46YWRtaW4="; + RestClient client = new RestClient(backendHTTPURL, Constants.APPLICATION_JSON, AuthString); HttpResponse oAuthData = client.post(Constants.APIApplicationRegistration.API_APP_REGISTRATION_ENDPOINT, Constants.APIApplicationRegistration.API_APP_REGISTRATION_PAYLOAD); JSONObject jsonObj = new JSONObject(oAuthData.getData()); @@ -42,8 +49,7 @@ 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.get(Constants.OAUTH_ACCESS_TOKEN).toString(); + return jsonObj; } } diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/RestClient.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/RestClient.java index 620d59b6..5767f486 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/RestClient.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/RestClient.java @@ -17,11 +17,13 @@ */ package org.wso2.iot.integration.common; +import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException; import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import java.io.*; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.Charset; @@ -73,7 +75,7 @@ public class RestClient { this.requestHeaders.remove(headerName); } - public HttpResponse post(String endpoint, String body) throws Exception { + public HttpResponse post(String endpoint, String body) throws MalformedURLException, AutomationFrameworkException { return HttpRequestUtil.doPost(new URL(backEndUrl + endpoint), body, requestHeaders); } diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/TestBase.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/TestBase.java index 33c9d2bb..a4f2c05e 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/TestBase.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/common/TestBase.java @@ -19,7 +19,6 @@ package org.wso2.iot.integration.common; import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.engine.context.TestUserMode; -import org.wso2.carbon.automation.engine.frameworkutils.CodeCoverageUtils; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; import org.wso2.carbon.integration.common.utils.LoginLogoutClient; @@ -29,7 +28,6 @@ import javax.xml.xpath.XPathExpressionException; * This is the base test class that provides common details necessary for other test cases. */ public class TestBase { - static String accessToken; protected AutomationContext automationContext; protected String backendHTTPSURL; protected String backendHTTPURL; diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/enrollment/AndroidEnrollment.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/enrollment/AndroidEnrollment.java index cf806cea..4687ad44 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/enrollment/AndroidEnrollment.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/device/enrollment/AndroidEnrollment.java @@ -17,7 +17,9 @@ */ package org.wso2.iot.integration.device.enrollment; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import junit.framework.Assert; import org.apache.commons.httpclient.HttpStatus; import org.testng.annotations.BeforeClass; @@ -32,8 +34,10 @@ import org.wso2.iot.integration.common.*; */ public class AndroidEnrollment extends TestBase { private RestClient client; + private String deviceId; - @BeforeClass(alwaysRun = true, groups = { Constants.AndroidEnrollment.ENROLLMENT_GROUP}) + @BeforeClass(alwaysRun = true, groups = { Constants.AndroidEnrollment.ENROLLMENT_GROUP}, dependsOnGroups = + Constants.MobileDeviceManagement.MOBILE_DEVICE_MANAGEMENT_GROUP) public void initTest() throws Exception { super.init(TestUserMode.SUPER_TENANT_ADMIN); String accessTokenString = "Bearer " + OAuthUtil.getOAuthToken(backendHTTPURL, backendHTTPSURL); @@ -42,17 +46,23 @@ public class AndroidEnrollment extends TestBase { @Test(description = "Test an Android device enrollment.") public void testEnrollment() throws Exception { - String enrollmentData = PayloadGenerator.getJsonPayloadToString(Constants.AndroidEnrollment - .ENROLLMENT_PAYLOAD_FILE_NAME); + String enrollmentData = PayloadGenerator.getJsonPayload(Constants.AndroidEnrollment + .ENROLLMENT_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_POST).toString(); HttpResponse response = client.post(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT, enrollmentData); + JsonParser jsonParser = new JsonParser(); + JsonElement element = jsonParser.parse(response.getData()); + JsonObject jsonObject = element.getAsJsonObject(); + JsonElement msg = jsonObject.get("responseMessage"); + deviceId = msg.getAsString().split("\'")[1].split("\'")[0]; Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode()); - AssertUtil.jsonPayloadCompare(PayloadGenerator.getJsonPayloadToString( - Constants.AndroidEnrollment.ENROLLMENT_RESPONSE_PAYLOAD_FILE_NAME), response.getData(), true); + AssertUtil.jsonPayloadCompare(PayloadGenerator.getJsonPayload( + Constants.AndroidEnrollment.ENROLLMENT_RESPONSE_PAYLOAD_FILE_NAME, + Constants.HTTP_METHOD_POST).toString(), response.getData(), true); } @Test(description = "Test an Android device is enrolled.", dependsOnMethods = {"testEnrollment"}) public void testIsEnrolled() throws Exception { - HttpResponse response = client.get(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT + Constants.DEVICE_ID); + HttpResponse response = client.get(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT + "/" + deviceId + "/status"); Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode()); AssertUtil.jsonPayloadCompare(PayloadGenerator.getJsonPayload( Constants.AndroidEnrollment.ENROLLMENT_RESPONSE_PAYLOAD_FILE_NAME, @@ -64,21 +74,19 @@ public class AndroidEnrollment extends TestBase { JsonObject enrollmentData = PayloadGenerator.getJsonPayload( Constants.AndroidEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_PUT); - enrollmentData.addProperty(Constants.DEVICE_IDENTIFIER_KEY, Constants.DEVICE_ID); - HttpResponse response = client.put(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT + Constants.DEVICE_ID, + HttpResponse response = client.put(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT + "/" + deviceId, enrollmentData.toString()); AssertUtil.jsonPayloadCompare(PayloadGenerator.getJsonPayload( Constants.AndroidEnrollment.ENROLLMENT_RESPONSE_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_PUT).toString(), response.getData(), true); } - @Test(description = "Test disenrollment.", dependsOnMethods = {"testModifyEnrollment"}) + @Test(description = "Test disEnrollment.", dependsOnMethods = {"testModifyEnrollment"}) public void testDisEnrollDevice() throws Exception { - HttpResponse response = client.delete(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT + Constants.DEVICE_ID); + HttpResponse response = client.delete(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT + "/" + deviceId); Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode()); AssertUtil.jsonPayloadCompare(PayloadGenerator.getJsonPayload( - Constants.AndroidEnrollment.ENROLLMENT_RESPONSE_PAYLOAD_FILE_NAME, - Constants.HTTP_METHOD_DELETE).toString(), - response.getData(), true); + Constants.AndroidEnrollment.ENROLLMENT_RESPONSE_PAYLOAD_FILE_NAME, + Constants.HTTP_METHOD_DELETE).toString(), response.getData(), true); } } 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/java/org/wso2/iot/integration/mobileDevice/MobileDeviceManagement.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/mobileDevice/MobileDeviceManagement.java index caf575f6..9f9db680 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/mobileDevice/MobileDeviceManagement.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/mobileDevice/MobileDeviceManagement.java @@ -41,8 +41,7 @@ public class MobileDeviceManagement extends TestBase { @Test(description = "Add an Android device.") public void addEnrollment() throws Exception { JsonObject enrollmentData = PayloadGenerator.getJsonPayload( - Constants.AndroidEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME, - Constants.HTTP_METHOD_POST); + Constants.AndroidEnrollment.ENROLLMENT_PAYLOAD_FILE_NAME, Constants.HTTP_METHOD_POST); enrollmentData.addProperty(Constants.DEVICE_IDENTIFIER_KEY, Constants.DEVICE_ID); IOTResponse response = client.post(Constants.AndroidEnrollment.ENROLLMENT_ENDPOINT, enrollmentData.toString()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatus()); @@ -55,7 +54,7 @@ public class MobileDeviceManagement extends TestBase { public void testCountDevices() throws Exception { IOTResponse response = client.get(Constants.MobileDeviceManagement.GET_DEVICE_COUNT_ENDPOINT); Assert.assertEquals(HttpStatus.SC_OK, response.getStatus()); - Assert.assertTrue(response.getBody().toString().equals(Constants.MobileDeviceManagement.NO_OF_DEVICES)); + Assert.assertTrue(response.getBody().equals(Constants.MobileDeviceManagement.NO_OF_DEVICES)); } diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/mobileDevice/MobileDeviceManagementWithNoDevices.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/mobileDevice/MobileDeviceManagementWithNoDevices.java index d29a3a08..b2e76bea 100644 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/mobileDevice/MobileDeviceManagementWithNoDevices.java +++ b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/mobileDevice/MobileDeviceManagementWithNoDevices.java @@ -20,20 +20,40 @@ package org.wso2.iot.integration.mobileDevice; import junit.framework.Assert; import org.apache.commons.httpclient.HttpStatus; +import org.junit.experimental.theories.Theories; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.iot.integration.common.*; +import java.util.concurrent.TimeUnit; + /** * This class contains integration tests for API Mobile Device Management with No Devices Enrolled. */ public class MobileDeviceManagementWithNoDevices extends TestBase { private IOTHttpClient client; + /** + * @BeforeSuite annotation is added to run this verification before the test suite starts. + * As in IoT server, apis are published after the server startup. Due to that the generated token doesn't get + * required scope. + * This method delays test suit startup until the tokens get required scopes. + * @throws Exception + */ + @BeforeSuite + public void verifyApiPublishing() throws Exception { + super.init(TestUserMode.SUPER_TENANT_ADMIN); + + while (!checkScopes(Constants.APIApplicationRegistration.PERMISSION_LIST)) { + TimeUnit.SECONDS.sleep(5); + } + } + @BeforeClass(alwaysRun = true, groups = { Constants.MobileDeviceManagement.MOBILE_DEVICE_MANAGEMENT_GROUP}) public void initTest() throws Exception { - super.init(TestUserMode.SUPER_TENANT_ADMIN); + String accessTokenString = "Bearer " + OAuthUtil.getOAuthToken(backendHTTPSURL, backendHTTPSURL); this.client = new IOTHttpClient(backendHTTPSURL, Constants.APPLICATION_JSON, accessTokenString); } @@ -42,14 +62,12 @@ public class MobileDeviceManagementWithNoDevices extends TestBase { public void testCountDevicesWithNoDevices() throws Exception { IOTResponse response = client.get(Constants.MobileDeviceManagement.GET_DEVICE_COUNT_ENDPOINT); Assert.assertEquals(HttpStatus.SC_OK, response.getStatus()); - Assert.assertEquals(Constants.ZERO, response.getBody()); + Assert.assertEquals(Constants.MobileDeviceManagement.NO_DEVICE, response.getBody()); } -// @Test(description = "Test view devices with no added devices") -// public void testViewDevicesWithNoDevices() throws Exception { -// IOTResponse response = client.get(Constants.MobileDeviceManagement.GET_ALL_DEVICES_ENDPOINT); -// Assert.assertEquals(HttpStatus.SC_OK, response.getStatus()); -// Assert.assertEquals(response.getBody(), Constants.NULL); -// } + private boolean checkScopes(String permissionsList) throws Exception { + String tokenString = OAuthUtil.getScopes(backendHTTPSURL, backendHTTPSURL); + return tokenString.contains(permissionsList); + } } \ No newline at end of file diff --git a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/util/RestartTest.java b/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/util/RestartTest.java deleted file mode 100644 index e991592c..00000000 --- a/modules/integration/tests-integration/src/test/java/org/wso2/iot/integration/util/RestartTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.wso2.iot.integration.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.BeforeClass; -import org.testng.Assert; -import org.testng.annotations.Test; -import org.wso2.carbon.automation.engine.context.TestUserMode; -import org.wso2.carbon.integration.common.admin.client.LogViewerClient; -import org.wso2.carbon.integration.common.utils.exceptions.AutomationUtilException; -import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; -import org.wso2.carbon.logging.view.stub.LogViewerLogViewerException; -import org.wso2.carbon.logging.view.stub.types.carbon.LogEvent; -import org.wso2.iot.integration.common.TestBase; - -import javax.xml.xpath.XPathExpressionException; -import java.net.MalformedURLException; -import java.rmi.RemoteException; -import java.util.concurrent.*; - -public class RestartTest extends TestBase { - - private Log log = LogFactory.getLog(RestartTest.class); - private LogViewerClient logViewerClient; - - @BeforeClass - public void initTest() throws Exception { - super.init(TestUserMode.SUPER_TENANT_ADMIN); - logViewerClient = new LogViewerClient(getBackendHTTPSURL(), getSessionCookie()); - } - - @Test(description = "Test restarting the server") - public void serverRestartTest() { - ServerConfigurationManager serverManager; - try { - serverManager = new ServerConfigurationManager(automationContext); - log.info("Restart Triggered -------------------------------------------------------------------"); - serverManager.restartGracefully(); - logViewerClient.getAllRemoteSystemLogs(); - waitForRestart(); - } catch (AutomationUtilException | XPathExpressionException | MalformedURLException e) { - log.error("Restart failed due to : " + e.getLocalizedMessage()); - } catch (RemoteException | LogViewerLogViewerException e) { - log.error("Cannot get server log due to : " + e.getLocalizedMessage()); - } - } - - /** - * Wait until the server restarts. - * This method looks for "Mgt console URL:" to be appeared in the terminal. - * If it does not appear within the given timeout an Exception will be thrown. - */ - private void waitForRestart() { - ExecutorService service = Executors.newSingleThreadExecutor(); - try { - Runnable r = new Runnable() { - @Override - public void run() { - try { - LogEvent[] logEvents = logViewerClient.getAllRemoteSystemLogs(); - for (LogEvent event : logEvents) { - log.info(event.getMessage() + " @ " + event.getLogTime()); - if (event.getMessage().contains("Mgt Console URL : " )){ - log.info("Server restarted successfully"); - Assert.assertTrue(true); - } - } - } catch (RemoteException | LogViewerLogViewerException e) { - log.error("Error reading logs. \n" + e.getMessage()); - Assert.assertTrue(false); - } - } - }; - - Future f = service.submit(r); - - f.get(30, TimeUnit.MINUTES); - } catch (final InterruptedException e) { - log.error("Interrupted "+e.getMessage()); - Assert.assertTrue(false); - } catch (final TimeoutException e) { - log.error("Timeout " + e.getMessage()); - Assert.assertTrue(false); - } catch (final ExecutionException e) { - log.error("Execution failed " + e.getMessage()); - Assert.assertTrue(false); - } finally { - service.shutdown(); - } - } - -} diff --git a/modules/integration/tests-integration/src/test/resources/automation.xml b/modules/integration/tests-integration/src/test/resources/automation.xml index b538772d..5e6200ee 100644 --- a/modules/integration/tests-integration/src/test/resources/automation.xml +++ b/modules/integration/tests-integration/src/test/resources/automation.xml @@ -24,7 +24,7 @@ - 300000 + 100000 diff --git a/modules/integration/tests-integration/src/test/resources/payloads/android-enrollment-payloads.json b/modules/integration/tests-integration/src/test/resources/payloads/android-enrollment-payloads.json index f246be2f..ca0c8a6b 100644 --- a/modules/integration/tests-integration/src/test/resources/payloads/android-enrollment-payloads.json +++ b/modules/integration/tests-integration/src/test/resources/payloads/android-enrollment-payloads.json @@ -1,92 +1,186 @@ { - "id": 101234, - "name": "androiddevice1234", - "type": "android", - "description": "this is an android device", - "deviceIdentifier": "d24f870f390352a41234", - "enrolmentInfo": { + "POST": { "id": 101234, - "device": { + "name": "androiddevice1234", + "type": "android", + "description": "this is an android device", + "deviceIdentifier": "d24f870f390352a41234", + "enrolmentInfo": { + "id": 101234, + "device": { + }, + "dateOfEnrolment": 0, + "dateOfLastUpdate": 0, + "ownership": "BYOD", + "status": "CREATED", + "owner": "admin" }, - "dateOfEnrolment": 0, - "dateOfLastUpdate": 0, - "ownership": "BYOD", - "status": "CREATED", - "owner": "admin" - }, - "features": [ - { - "id": 10, - "code": "aaaa1111", - "name": "newfeature1", - "description": "this is the new feature 1", - "deviceType": "android", - "metadataEntries": [ - { - "id": 10, - "value": { + "features": [ + { + "id": 10, + "code": "aaaa1111", + "name": "newfeature1", + "description": "this is the new feature 1", + "deviceType": "android", + "metadataEntries": [ + { + "id": 10, + "value": { + } } - } - ] - } - ], - "properties": [ - { - "name": "property1", - "value": "value1" - } - ], - "deviceInfo": { - "deviceModel": "S8", - "vendor": "SAMSUNG", - "osVersion": "5.1", - "batteryLevel": 1, - "internalTotalMemory": 32, - "internalAvailableMemory": 24, - "externalTotalMemory": 64, - "externalAvailableMemory": 60, - "operator": "dialog", - "connectionType": "GSM", - "mobileSignalStrength": 1, - "ssid": "picassowifi", - "cpuUsage": 0, - "totalRAMMemory": 2, - "availableRAMMemory": 1, - "pluggedIn": false, - "location": { - "deviceId": 0, - "deviceIdentifier": { - "id": "string", - "type": "string" + ] + } + ], + "properties": [ + { + "name": "property1", + "value": "value1" + } + ], + "deviceInfo": { + "deviceModel": "S8", + "vendor": "SAMSUNG", + "osVersion": "5.1", + "batteryLevel": 1, + "internalTotalMemory": 32, + "internalAvailableMemory": 24, + "externalTotalMemory": 64, + "externalAvailableMemory": 60, + "operator": "dialog", + "connectionType": "GSM", + "mobileSignalStrength": 1, + "ssid": "picassowifi", + "cpuUsage": 0, + "totalRAMMemory": 2, + "availableRAMMemory": 1, + "pluggedIn": false, + "location": { + "deviceId": 0, + "deviceIdentifier": { + "id": "string", + "type": "string" + }, + "latitude": 0, + "longitude": 0, + "street1": "string", + "street2": "string", + "city": "string", + "state": "string", + "zip": "string", + "country": "string" }, - "latitude": 0, - "longitude": 0, - "street1": "string", - "street2": "string", - "city": "string", - "state": "string", - "zip": "string", - "country": "string" - }, - "deviceDetailsMap": { + "deviceDetailsMap": { + }, + "imei": "string", + "imsi": "string" }, - "imei": "string", - "imsi": "string" + "applications": [ + { + "id": 0, + "platform": "string", + "category": "string", + "name": "string", + "locationUrl": "string", + "imageUrl": "string", + "version": "string", + "type": "string", + "appProperties": { + }, + "applicationIdentifier": "string", + "memoryUsage": 0 + } + ] }, - "applications": [ - { - "id": 0, - "platform": "string", - "category": "string", - "name": "string", - "locationUrl": "string", - "imageUrl": "string", - "version": "string", - "type": "string", - "appProperties": { + "PUT": { + "id": 101234, + "name": "androiddevice1234", + "type": "android", + "description": "this is an android device", + "deviceIdentifier": "d24f870f390352a41234", + "enrolmentInfo": { + "id": 101234, + "device": { }, - "applicationIdentifier": "string", - "memoryUsage": 0 - } - ] -} \ No newline at end of file + "dateOfEnrolment": 0, + "dateOfLastUpdate": 0, + "ownership": "BYOD", + "status": "CREATED", + "owner": "admin" + }, + "features": [ + { + "id": 10, + "code": "aaaa1111", + "name": "newfeature2", + "description": "this is the new feature 2", + "deviceType": "android", + "metadataEntries": [ + { + "id": 10, + "value": { + } + } + ] + } + ], + "properties": [ + { + "name": "property2", + "value": "value2" + } + ], + "deviceInfo": { + "deviceModel": "S8", + "vendor": "SAMSUNG", + "osVersion": "5.1", + "batteryLevel": 1, + "internalTotalMemory": 32, + "internalAvailableMemory": 24, + "externalTotalMemory": 64, + "externalAvailableMemory": 60, + "operator": "dialog", + "connectionType": "GSM", + "mobileSignalStrength": 1, + "ssid": "picassowifi", + "cpuUsage": 0, + "totalRAMMemory": 2, + "availableRAMMemory": 1, + "pluggedIn": false, + "location": { + "deviceId": 0, + "deviceIdentifier": { + "id": "string", + "type": "string" + }, + "latitude": 0, + "longitude": 0, + "street1": "string", + "street2": "string", + "city": "string", + "state": "string", + "zip": "string", + "country": "string" + }, + "deviceDetailsMap": { + }, + "imei": "string", + "imsi": "string" + }, + "applications": [ + { + "id": 0, + "platform": "string", + "category": "string", + "name": "string", + "locationUrl": "string", + "imageUrl": "string", + "version": "string", + "type": "string", + "appProperties": { + }, + "applicationIdentifier": "string", + "memoryUsage": 0 + } + ] + } +} diff --git a/modules/integration/tests-integration/src/test/resources/payloads/android-enrollment-response-payloads.json b/modules/integration/tests-integration/src/test/resources/payloads/android-enrollment-response-payloads.json index dd51c631..2b158a47 100644 --- a/modules/integration/tests-integration/src/test/resources/payloads/android-enrollment-response-payloads.json +++ b/modules/integration/tests-integration/src/test/resources/payloads/android-enrollment-response-payloads.json @@ -1,4 +1,19 @@ { - "responseCode": "OK", - "responseMessage": "Android device, which carries the id \u0027d24f870f390352a41\u0027 has successfully been enrolled" + "POST": { + "responseCode": "OK", + "responseMessage": "Android device, which carries the id \u0027d24f870f390352a41234\u0027 has successfully been enrolled" + }, + "GET": { + "responseCode": "OK", + "responseMessage": "Android device that carries the id \u0027d24f870f390352a41234\u0027 is enrolled" + }, + "PUT": { + "responseCode": "Accepted", + "responseMessage": "Enrollment of Android device that carries the id \u0027d24f870f390352a41234\u0027 has successfully updated" + }, + "DELETE" : { + "responseCode":"OK", + "responseMessage":"Android device that carries id \u0027d24f870f390352a41234\u0027 has successfully dis-enrolled" + } + } \ No newline at end of file diff --git a/modules/integration/tests-integration/src/test/resources/payloads/permissions.json b/modules/integration/tests-integration/src/test/resources/payloads/permissions.json new file mode 100644 index 00000000..7b3f663a --- /dev/null +++ b/modules/integration/tests-integration/src/test/resources/payloads/permissions.json @@ -0,0 +1,3 @@ +{ + "default perm:admin-groups:count perm:admin-groups:view perm:admin-users:view perm:admin:certificates:add perm:admin:certificates:delete perm:admin:certificates:details perm:admin:certificates:verify perm:admin:certificates:view perm:admin:devices:view perm:android:blacklist-applications perm:android:change-lock-code perm:android:clear-password perm:android:configure-vpn perm:android:configure-wifi perm:android:control-camera perm:android:disenroll perm:android:encrypt-storage perm:android:enroll perm:android:enterprise-wipe perm:android:info perm:android:install-application perm:android:location perm:android:lock-devices perm:android:logcat perm:android:manage-configuration perm:android:mute perm:android:reboot perm:android:ring perm:android:send-notification perm:android:set-password-policy perm:android:set-webclip perm:android:uninstall-application perm:android:unlock-devices perm:android:update-application perm:android:upgrade-firmware perm:android:view-configuration perm:android:wipe perm:applications:install perm:applications:uninstall perm:dashboard:by-groups perm:dashboard:count-overview perm:dashboard:details perm:dashboard:device-counts perm:dashboard:feature-non-compliant perm:dashboard:filtered-count perm:dashboard:non-compliant perm:dashboard:non-compliant-count perm:dashboard:vulnerabilities perm:device-types:features perm:device-types:types perm:devices:applications perm:devices:compliance-data perm:devices:delete perm:devices:details perm:devices:effective-policy perm:devices:features perm:devices:operations perm:devices:search perm:devices:update perm:devices:view perm:get-activity perm:groups:add perm:groups:assign perm:groups:count perm:groups:device perm:groups:devices perm:groups:devices-add perm:groups:devices-count perm:groups:devices-remove perm:groups:groups perm:groups:groups-view perm:groups:remove perm:groups:roles perm:groups:share perm:groups:update perm:manage-configuration perm:notifications:mark-checked perm:notifications:view perm:policies:activate perm:policies:changes perm:policies:deactivate perm:policies:get-details perm:policies:get-policy-details perm:policies:manage perm:policies:priorities perm:policies:remove perm:policies:update perm:roles:add perm:roles:add-users perm:roles:create-combined-role perm:roles:delete perm:roles:details perm:roles:permissions perm:roles:update perm:roles:view perm:users:add perm:users:count perm:users:credentials perm:users:delete perm:users:details perm:users:is-exist perm:users:roles perm:users:search perm:users:send-invitation perm:users:update perm:users:user-details perm:view-configuration" +} \ 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 dd0662b0..7e3bfa15 100644 --- a/modules/integration/tests-integration/src/test/resources/testng.xml +++ b/modules/integration/tests-integration/src/test/resources/testng.xml @@ -18,24 +18,16 @@ - + - + - + - - - - - - @@ -46,11 +38,11 @@ - - - - - + + + + + diff --git a/modules/integration/tests-iot-web-ui/pom.xml b/modules/integration/tests-iot-web-ui/pom.xml index 3aab2b9e..779940fb 100644 --- a/modules/integration/tests-iot-web-ui/pom.xml +++ b/modules/integration/tests-iot-web-ui/pom.xml @@ -250,6 +250,7 @@ org.wso2.iot org.wso2.carbon.iot.core.integration.ui.pages + ${product.iot.version} org.wso2.carbon.automation diff --git a/pom.xml b/pom.xml index e36f1e67..bcc631cd 100644 --- a/pom.xml +++ b/pom.xml @@ -297,12 +297,6 @@ - - org.wso2.iot - org.wso2.carbon.iot.core.integration.ui.pages - ${product.iot.version} - test - @@ -1012,6 +1006,17 @@ org.wso2.iot.core.admin.styles ${product.iot.version} + + + org.apache.httpcomponents + httpmime + ${apache.httpmime.version} + + + org.apache.httpcomponents + httpclient + ${apache.httpclient.version} + @@ -1529,14 +1534,14 @@ 4.7.0 - 2.0.12-SNAPSHOT + 2.0.13 [2.0.0, 3.0.0) 3.1.0-SNAPSHOT - 3.0.9-SNAPSHOT + 3.0.10 6.1.64 @@ -1643,7 +1648,7 @@ 1.0.1 - 1.2.14 + 1.2.15 1.4.4 @@ -1677,6 +1682,9 @@ 1.0.3 + + 4.2.5 + 4.5.2