diff --git a/components/extensions/health-check-api/pom.xml b/components/extensions/health-check-api/pom.xml deleted file mode 100644 index 27bf21b09..000000000 --- a/components/extensions/health-check-api/pom.xml +++ /dev/null @@ -1,162 +0,0 @@ - - - - 4.0.0 - - - org.wso2.carbon.devicemgt-plugins - extensions - 5.0.7-SNAPSHOT - ../pom.xml - - - health-check-api - 5.0.7-SNAPSHOT - - war - Entgra - Health check API - http://entgra.io - - - - - maven-compiler-plugin - - 1.7 - 1.7 - - - - maven-war-plugin - - WEB-INF/lib/*cxf*.jar - api#health-check#v1.0 - - - - - - - - deploy - - compile - - - org.apache.maven.plugins - maven-antrun-plugin - 1.7 - - - compile - - run - - - - - - - - - - - - - - - - - - client - - test - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - test - - java - - - - - - - - - - - - org.apache.cxf - cxf-rt-frontend-jaxws - - - org.apache.cxf - cxf-rt-frontend-jaxrs - - - org.apache.cxf - cxf-rt-transports-http - - - javax.ws.rs - jsr311-api - provided - - - org.wso2.carbon - org.wso2.carbon.utils - provided - - - org.wso2.carbon - org.wso2.carbon.logging - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - provided - - - org.apache.axis2.wso2 - axis2-client - - - - - javax.servlet - servlet-api - provided - - - - diff --git a/components/extensions/health-check-api/src/main/java/io/entgra/healthcheck/HealthCheck.java b/components/extensions/health-check-api/src/main/java/io/entgra/healthcheck/HealthCheck.java deleted file mode 100644 index 354ff27b2..000000000 --- a/components/extensions/health-check-api/src/main/java/io/entgra/healthcheck/HealthCheck.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package io.entgra.healthcheck; - -import io.entgra.healthcheck.utils.APIUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; - -@Path("/") -public class HealthCheck { - - private static Log log = LogFactory.getLog(HealthCheck.class); - - @GET - public Response check() { - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext() - .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); - DeviceManagementProviderService dms = APIUtils.getDeviceManagementService(); - return Response.ok("OK") - .entity(dms.getFunctioningDevicesInSystem()).build(); - } catch (Exception e) { - log.error("Error occurred while invoking health check,", e); - return Response.serverError().entity(e.getMessage()).build(); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } -} diff --git a/components/extensions/health-check-api/src/main/java/io/entgra/healthcheck/utils/APIUtils.java b/components/extensions/health-check-api/src/main/java/io/entgra/healthcheck/utils/APIUtils.java deleted file mode 100644 index 02f19eabe..000000000 --- a/components/extensions/health-check-api/src/main/java/io/entgra/healthcheck/utils/APIUtils.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package io.entgra.healthcheck.utils; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; - -public class APIUtils { - - private static Log log = LogFactory.getLog(APIUtils.class); - private static DeviceManagementProviderService deviceManagementProviderService = null; - - public static DeviceManagementProviderService getDeviceManagementService() { - if (deviceManagementProviderService == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - deviceManagementProviderService = - (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); - if (deviceManagementProviderService == null) { - String msg = "DeviceImpl Management provider service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - return deviceManagementProviderService; - } -} diff --git a/components/extensions/health-check-api/src/main/webapp/META-INF/webapp-classloading.xml b/components/extensions/health-check-api/src/main/webapp/META-INF/webapp-classloading.xml deleted file mode 100644 index 92d38b3c7..000000000 --- a/components/extensions/health-check-api/src/main/webapp/META-INF/webapp-classloading.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - false - - - CXF,Carbon - diff --git a/components/extensions/health-check-api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/extensions/health-check-api/src/main/webapp/WEB-INF/cxf-servlet.xml deleted file mode 100644 index aa0b18716..000000000 --- a/components/extensions/health-check-api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - diff --git a/components/extensions/health-check-api/src/main/webapp/WEB-INF/web.xml b/components/extensions/health-check-api/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index cb92ef15d..000000000 --- a/components/extensions/health-check-api/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - Admin-Webapp - - JAX-WS/JAX-RS Health Check Endpoint - JAX-WS/JAX-RS Health Check - CXFServlet - - org.apache.cxf.transport.servlet.CXFServlet - - 1 - - - CXFServlet - /* - - - 60 - - diff --git a/components/extensions/pom.xml b/components/extensions/pom.xml index 2fc7633fb..17004d9e6 100644 --- a/components/extensions/pom.xml +++ b/components/extensions/pom.xml @@ -35,10 +35,7 @@ cdmf-transport-adapters mb-extensions - siddhi-extensions pull-notification-listeners - remote-session-extension - health-check-api diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/pom.xml b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/pom.xml deleted file mode 100644 index d5fb55f30..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt-plugins - remote-session-extension - 5.0.7-SNAPSHOT - ../pom.xml - - - - 4.0.0 - org.wso2.carbon.device.mgt.extensions.remote.session.endpoint - war - WSO2 - Webapp for UI Remote Session - http://wso2.org - - - - junit - junit - test - - - org.apache.tomcat - tomcat-websocket-api - - - javax.ws.rs - javax.ws.rs-api - - - org.apache.cxf - cxf-rt-frontend-jaxrs - - - org.json.wso2 - json - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.extensions.remote.session - provided - - - - - remote#session - - diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/ClientSessionSubscriptionEndpoint.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/ClientSessionSubscriptionEndpoint.java deleted file mode 100644 index 6fd1d9970..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/ClientSessionSubscriptionEndpoint.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * deviceId 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.endpoint; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.utils.HttpSessionConfigurator; -import org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.utils.ServiceHolder; -import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException; - -import javax.websocket.CloseReason; -import javax.websocket.OnClose; -import javax.websocket.OnError; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; -import javax.websocket.server.PathParam; -import javax.websocket.server.ServerEndpoint; -import java.io.IOException; - -/** - * This class represents web socket endpoint to manage Remote Sessions - */ -@ServerEndpoint(value = "/clients/{deviceType}/{deviceId}", configurator = HttpSessionConfigurator.class) -public class ClientSessionSubscriptionEndpoint extends SubscriptionEndpoint { - - private static final Log log = LogFactory.getLog(ClientSessionSubscriptionEndpoint.class); - - /** - * Web socket onOpen use when client connect to web socket url - * - * @param session - Registered session. - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - */ - @OnOpen - public void onOpen(Session session, @PathParam("deviceType") String deviceType, @PathParam("deviceId") String - deviceId) { - try { - ServiceHolder.getInstance().getRemoteSessionManagementService().initializeSession(session, deviceType, - deviceId); - } catch (RemoteSessionManagementException e) { - if (log.isDebugEnabled()) { - log.error("Error occurred while initializing session ", e); - } - try { - session.close(e.getCloseReason()); - } catch (IOException ex) { - log.error("Failed to disconnect the client.", ex); - } - } - } - - /** - * Web socket onMessage use when client sends a string message - * - * @param session - Registered session. - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - */ - @OnMessage - public void onMessage(Session session, String message, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - super.onMessage(session, message, deviceType, deviceId); - } - - /** - * Web socket onMessage use when client sends a byte message - * - * @param session - Registered session. - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - * @param message - Byte message which needs to send to peer - */ - @OnMessage - public void onMessage(Session session, byte[] message, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - super.onMessage(session, message, deviceType, deviceId); - } - - /** - * Web socket onClose use to handle socket connection close - * - * @param session - Registered session. - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - * @param reason - Status code for web-socket close. - */ - @OnClose - public void onClose(Session session, CloseReason reason, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - super.onClose(session, reason, deviceType, deviceId); - } - - /** - * Web socket onError use to handle socket connection error - * - * @param session - Registered session. - * @param throwable - Web socket exception - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - */ - @OnError - public void onError(Session session, Throwable throwable, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - super.onError(session, throwable, deviceType, deviceId); - } -} \ No newline at end of file diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/DeviceSessionSubscriptionEndpoint.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/DeviceSessionSubscriptionEndpoint.java deleted file mode 100644 index de504eacf..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/DeviceSessionSubscriptionEndpoint.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * deviceId 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.endpoint; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.utils.HttpSessionConfigurator; -import org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.utils.ServiceHolder; -import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException; - -import javax.websocket.CloseReason; -import javax.websocket.OnClose; -import javax.websocket.OnError; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; -import javax.websocket.server.PathParam; -import javax.websocket.server.ServerEndpoint; -import java.io.IOException; - -/** - * This class represents web socket endpoint to manage Remote Sessions - */ -@ServerEndpoint(value = "/devices/{deviceType}/{deviceId}/{operationId}", configurator = HttpSessionConfigurator.class) -public class DeviceSessionSubscriptionEndpoint extends SubscriptionEndpoint { - - private static final Log log = LogFactory.getLog(DeviceSessionSubscriptionEndpoint.class); - - /** - * Web socket onOpen use when device connect to web socket url - * - * @param session - Web socket Session - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - * @param operationId - Operations Id - */ - @OnOpen - public void onOpen(Session session, @PathParam("deviceType") String deviceType, @PathParam("deviceId") String - deviceId, @PathParam("operationId") String operationId) { - try { - ServiceHolder.getInstance().getRemoteSessionManagementService().initializeSession(session, deviceType, - deviceId, operationId); - } catch (RemoteSessionManagementException e) { - if (log.isDebugEnabled()) { - log.error("Error occurred while initializing session ", e); - } - try { - session.close(e.getCloseReason()); - } catch (IOException ex) { - log.error("Failed to disconnect the client.", ex); - } - } - } - - /** - * Web socket onMessage use when device sends a string message - * - * @param session - Registered session. - * @param message - String message which needs to send to peer - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - */ - @OnMessage - public void onMessage(Session session, String message, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - super.onMessage(session, message, deviceType, deviceId); - } - - /** - * Web socket onMessage use when device sends a byte message - * - * @param session - Registered session. - * @param message - Byte message which needs to send to peer - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - */ - @OnMessage - public void onMessage(Session session, byte[] message, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - super.onMessage(session, message, deviceType, deviceId); - } - - /** - * Web socket onClose use to handle socket connection close - * - * @param session - Registered session. - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - * @param reason - Status code for web-socket close. - */ - @OnClose - public void onClose(Session session, CloseReason reason, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - super.onClose(session, reason, deviceType, deviceId); - } - - /** - * Web socket onError use to handle socket connection error - * - * @param session - Registered session. - * @param throwable - Web socket exception - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - */ - @OnError - public void onError(Session session, Throwable throwable, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - super.onError(session, throwable, deviceType, deviceId); - } -} \ No newline at end of file diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/SubscriptionEndpoint.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/SubscriptionEndpoint.java deleted file mode 100644 index f3ed4cd30..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/SubscriptionEndpoint.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * deviceId 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.endpoint; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.utils.ServiceHolder; -import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException; - -import javax.websocket.CloseReason; -import javax.websocket.Session; -import javax.websocket.server.PathParam; -import java.io.IOException; - -/** - * This class represents common web socket endpoint to manage Remote Sessions - */ -public class SubscriptionEndpoint { - - private static final Log log = LogFactory.getLog(SubscriptionEndpoint.class); - - /** - * Web socket onMessage - When client sends a message - * - * @param session - Registered session. - * @param deviceType - DeviceType - * @param message - String Message which needs to send to peer - */ - public void onMessage(Session session, String message, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - if (log.isDebugEnabled()) { - log.debug("Received message from client for RemoteSession id: " + session.getId() + " device type: " + - deviceType + " device id: " + deviceId); - } - try { - ServiceHolder.getInstance().getRemoteSessionManagementService().sendMessageToPeer(session, message); - } catch (RemoteSessionManagementException e) { - if (log.isDebugEnabled()) { - log.error("Error occurred while send message to peer session ", e); - } - try { - session.close(e.getCloseReason()); - } catch (IOException ex) { - if (log.isDebugEnabled()) { - log.error("Failed to disconnect the client.", ex); - } - } - } - } - - /** - * Web socket onMessage use When client sends a message - * - * @param session - Registered session. - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - * @param message - Byte Message which needs to send to peer - */ - public void onMessage(Session session, byte[] message, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - if (log.isDebugEnabled()) { - log.debug("Received message from client for RemoteSession id: " + session.getId() + " device type: " + - deviceType + " device id: " + deviceId); - } - try { - ServiceHolder.getInstance().getRemoteSessionManagementService().sendMessageToPeer(session, message); - } catch (RemoteSessionManagementException e) { - if (log.isDebugEnabled()) { - log.error("Error occurred while send message to peer session ", e); - } - try { - session.close(e.getCloseReason()); - } catch (IOException ex) { - if (log.isDebugEnabled()) { - log.error("Failed to disconnect the client.", ex); - } - } - } - } - - /** - * Web socket onClose use to handle socket connection close - * - * @param session - Registered session. - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - * @param reason - Status code for web-socket close. - */ - public void onClose(Session session, CloseReason reason, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - - ServiceHolder.getInstance().getRemoteSessionManagementService().endSession(session, "Remote session closed"); - if (log.isDebugEnabled()) { - log.debug("websocket closed due to " + reason.getReasonPhrase() + ", for session ID:" + session.getId - () + ", for request URI - " + session.getRequestURI() + " device type: " + deviceType + " device " + - "id: " + deviceId); - } - - } - - /** - * Web socket onError use to handle socket connection error - * - * @param session - Registered session. - * @param throwable - Web socket exception - * @param deviceType - DeviceType - * @param deviceId - Device Identifier - */ - public void onError(Session session, Throwable throwable, @PathParam("deviceType") String deviceType, @PathParam - ("deviceId") String deviceId) { - - if (throwable instanceof IOException) { - if (log.isDebugEnabled()) { - log.error("Error occurred in session ID: " + session.getId() + " device type: " + deviceType + - "device id: " + deviceId + ", for request URI - " + session.getRequestURI() + - ", " + throwable.getMessage(), throwable); - } - } else { - log.error("Error occurred in session ID: " + session.getId() + " device type: " + deviceType + " device " + - "id: " + deviceId + ", for request URI - " + session.getRequestURI() + ", " + throwable.getMessage - (), throwable); - } - try { - ServiceHolder.getInstance().getRemoteSessionManagementService().endSession(session, "Remote session closed"); - if (session.isOpen()) { - session.close(new CloseReason(CloseReason.CloseCodes.PROTOCOL_ERROR, "Unexpected Error Occurred")); - } - } catch (IOException ex) { - if (log.isDebugEnabled()) { - log.error("Failed to disconnect the client.", ex); - } - } - } -} \ No newline at end of file diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/constants/Constants.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/constants/Constants.java deleted file mode 100644 index 544b58d57..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/constants/Constants.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.constants; - -/** - * This holds the constants related to remote session web socket endpoint - */ -public class Constants { - public static final String HTTP_HEADERS = "HttpHeaders"; - - private Constants() { - } -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/utils/HttpSessionConfigurator.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/utils/HttpSessionConfigurator.java deleted file mode 100644 index 6d5513f95..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/utils/HttpSessionConfigurator.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.utils; - -import org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.constants.Constants; - -import javax.websocket.HandshakeResponse; -import javax.websocket.server.HandshakeRequest; -import javax.websocket.server.ServerEndpointConfig; -import java.util.List; -import java.util.Map; - -/** - * Class for handle HTTP session - */ -public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator { - public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { - Map> httpHeaders = request.getHeaders(); - config.getUserProperties().put(Constants.HTTP_HEADERS, httpHeaders); - } -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/utils/ServiceHolder.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/utils/ServiceHolder.java deleted file mode 100644 index 570238bb8..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/java/org/wso2/carbon/device/mgt/extensions/remote/session/endpoint/utils/ServiceHolder.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.endpoint.utils; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.extensions.remote.session.RemoteSessionManagementService; - -/** - * Class for store remote management service instances - */ -public class ServiceHolder { - - private static ServiceHolder instance; - private static final Log log = LogFactory.getLog(ServiceHolder.class); - - private ServiceHolder() { - } - - public synchronized static ServiceHolder getInstance() { - if (instance == null) { - instance = new ServiceHolder(); - } - return instance; - } - - public RemoteSessionManagementService getRemoteSessionManagementService() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - RemoteSessionManagementService RemoteSessionManagementService = - (RemoteSessionManagementService) ctx.getOSGiService(RemoteSessionManagementService.class, null); - if (RemoteSessionManagementService == null) { - String msg = "Remote Session Management service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return RemoteSessionManagementService; - } - -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/webapp/WEB-INF/web.xml b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 9f8a509b1..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - Remote Session - - HttpHeaderSecurityFilter - org.apache.catalina.filters.HttpHeaderSecurityFilter - - hstsEnabled - false - - - - - ContentTypeBasedCachePreventionFilter - org.wso2.carbon.ui.filters.cache.ContentTypeBasedCachePreventionFilter - - patterns - text/html" ,application/json" ,text/plain - - - filterAction - enforce - - - httpHeaders - Cache-Control: no-store, no-cache, must-revalidate, private - - - - - HttpHeaderSecurityFilter - /* - - - - ContentTypeBasedCachePreventionFilter - /* - - diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/pom.xml b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/pom.xml deleted file mode 100644 index 9e8667c25..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/pom.xml +++ /dev/null @@ -1,147 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt-plugins - remote-session-extension - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.device.mgt.extensions.remote.session - bundle - WSO2 Carbon - Remote Session Manager Implementation - WSO2 Carbon - Remote Session Manager Implementation - http://wso2.org - - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon.identity.inbound.auth.oauth2 - org.wso2.carbon.identity.oauth.stub - - - commons-pool.wso2 - commons-pool - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - - - org.json.wso2 - json - - - org.wso2.carbon - org.wso2.carbon.utils - - - org.wso2.carbon - org.wso2.carbon.core - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - - - javax.websocket - javax.websocket-api - - - - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - ${carbon.devicemgt.plugins.version} - Remote Session Manager Bundle - - !org.wso2.carbon.device.mgt.extensions.remote.session.internal, - org.wso2.carbon.device.mgt.extensions.remote.session.* - - - javax.websocket, - org.apache.axis2; version="${axis2.osgi.version.range}", - org.apache.axis2.client; version="${axis2.osgi.version.range}", - org.apache.axis2.context; version="${axis2.osgi.version.range}", - org.apache.axis2.transport.http; version="${axis2.osgi.version.range}", - org.apache.commons.httpclient, - org.apache.commons.httpclient.contrib.ssl, - org.apache.commons.httpclient.params, - org.apache.commons.httpclient.protocol, - org.apache.commons.logging, - org.apache.commons.pool, - org.apache.commons.pool.impl, - org.json, - org.osgi.framework, - org.osgi.service.component, - org.wso2.carbon.context, - org.wso2.carbon.core, - org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.device.mgt.core.*, - org.wso2.carbon.identity.oauth2.stub, - org.wso2.carbon.identity.oauth2.stub.dto, - org.wso2.carbon.utils.multitenancy - - - - - - - - - diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/RemoteSessionManagementService.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/RemoteSessionManagementService.java deleted file mode 100644 index ce6f155d1..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/RemoteSessionManagementService.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.extensions.remote.session; - -import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException; - -import javax.websocket.Session; -import java.io.IOException; - -/** - * Class @{@link RemoteSessionManagementService} use for managing remote sessions - */ -public interface RemoteSessionManagementService { - - /** - * Initialize session based on web socket request .This method is used by the device to connect - * - * @param session Web socket RemoteSession - * @param deviceType Device Type - * @param deviceId Device Id - * @throws RemoteSessionManagementException throws when session has errors with accessing device resources - */ - void initializeSession(Session session, String deviceType, String deviceId) throws - RemoteSessionManagementException; - - /** - * Initialize session based on web socket request . This method is used by the device to connect - * - * @param session Web socket RemoteSession - * @param deviceType Device Type - * @param deviceId Device Id - * @param operationId Operation Id that device needs to connec - * @throws RemoteSessionManagementException throws when session has errors with accessing device resources - */ - void initializeSession(Session session, String deviceType, String deviceId, String operationId) throws - RemoteSessionManagementException; - - /** - * Send string message to connected remote device or client - * - * @param session Web socket RemoteSession - * @param message Message needs to send to peer connection client - * @throws RemoteSessionManagementException - */ - void sendMessageToPeer(Session session, String message) throws RemoteSessionManagementException; - - /** - * Send byte message to connected remote device or client - * - * @param session Web socket RemoteSession - * @param message Message needs to send to peer connection - * @throws RemoteSessionManagementException - */ - void sendMessageToPeer(Session session, byte[] message) throws RemoteSessionManagementException; - - /** - * Close the session - * - * @param session Web socket RemoteSession - */ - void endSession(Session session, String closeReason); - -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/RemoteSessionManagementServiceImpl.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/RemoteSessionManagementServiceImpl.java deleted file mode 100644 index 9af8618ee..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/RemoteSessionManagementServiceImpl.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.extensions.remote.session; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; -import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.AuthenticationInfo; -import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.OAuthAuthenticator; -import org.wso2.carbon.device.mgt.extensions.remote.session.constants.RemoteSessionConstants; -import org.wso2.carbon.device.mgt.extensions.remote.session.dto.RemoteSession; -import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException; -import org.wso2.carbon.device.mgt.extensions.remote.session.internal.RemoteSessionManagementDataHolder; - -import javax.websocket.CloseReason; -import javax.websocket.Session; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -/** - * Class @{@link RemoteSessionManagementServiceImpl} is the implementation of @{@link RemoteSessionManagementService} - * which is used manage initial connection, sending messages to peer session, manage and close the session. - */ -public class RemoteSessionManagementServiceImpl implements RemoteSessionManagementService { - - private static final Log log = LogFactory.getLog(RemoteSessionManagementServiceImpl.class); - - @Override - public void initializeSession(Session session, String deviceType, String deviceId, String operationId) throws - RemoteSessionManagementException { - - // Check whether required configurations are enabled - if (!RemoteSessionManagementDataHolder.getInstance().isEnabled()) { - throw new RemoteSessionManagementException("Remote session feature is disabled."); - } else if (RemoteSessionManagementDataHolder.getInstance().getServerUrl() == null) { - throw new RemoteSessionManagementException("Server url has not been configured."); - } - - // Read Query Parameters for obtain the token - String token = getTokenFromSession(session); - - // if session initiated using operation id means request came from device. - if (operationId == null) { - // Validate the token - OAuthAuthenticator oAuthAuthenticator = RemoteSessionManagementDataHolder.getInstance().getOauthAuthenticator(); - AuthenticationInfo authenticationInfo = oAuthAuthenticator.isAuthenticated(token); - - if (authenticationInfo != null && authenticationInfo.isAuthenticated()) { - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(authenticationInfo - .getTenantDomain() - , true); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(authenticationInfo.getUsername()); - if (deviceId != null && !deviceId.isEmpty() && deviceType != null && !deviceType.isEmpty()) { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(deviceType); - - // Check authorization of user for given device - boolean userAuthorized = RemoteSessionManagementDataHolder.getInstance() - .getDeviceAccessAuthorizationService() - .isUserAuthorized(deviceIdentifier, authenticationInfo.getUsername()); - if (userAuthorized) { - // set common settings for session - session.setMaxBinaryMessageBufferSize(RemoteSessionManagementDataHolder.getInstance() - .getMaxMessageBufferSize()); - session.setMaxTextMessageBufferSize(RemoteSessionManagementDataHolder.getInstance() - .getMaxMessageBufferSize()); - session.setMaxIdleTimeout(RemoteSessionManagementDataHolder.getInstance().getMaxIdleTimeout()); - - initializeClientSession(session, authenticationInfo.getTenantDomain(), deviceType, deviceId); - - log.info("Current remote sessions count: " + RemoteSessionManagementDataHolder.getInstance() - .getSessionMap().size()); - - } else { - throw new RemoteSessionManagementException("Missing device Id or type "); - } - } else { - throw new RemoteSessionManagementException("Unauthorized Access for the device Type : " + deviceType - + " , deviceId : " + deviceId); - } - } catch (OperationManagementException | InvalidDeviceException e) { - String msg = "Error occurred while adding initial operation for the " + - "device Type : " + deviceType + " , deviceId : " + deviceId; - log.error(msg, e); - throw new RemoteSessionManagementException(msg); - } catch (DeviceAccessAuthorizationException e) { - String msg = "Error occurred while device access authorization for the " + - "device Type : " + deviceType + " , " + "deviceId : " + deviceId; - log.error(msg, e); - throw new RemoteSessionManagementException(msg); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - - } else { - throw new RemoteSessionManagementException("Invalid token"); - } - - } else { - // set common settings for session - session.setMaxBinaryMessageBufferSize(RemoteSessionManagementDataHolder.getInstance() - .getMaxMessageBufferSize()); - session.setMaxTextMessageBufferSize(RemoteSessionManagementDataHolder.getInstance() - .getMaxMessageBufferSize()); - session.setMaxIdleTimeout(RemoteSessionManagementDataHolder.getInstance().getMaxIdleTimeout()); - - if (token == null || token.isEmpty()) { - String message = "Could not find a UUID related to the remote session."; - log.error(message); - throw new RemoteSessionManagementException(message); - } else { - String tenantDomain = RemoteSessionManagementDataHolder.getInstance().getUuidToTenantMap().remove(token); - if (tenantDomain == null || tenantDomain.isEmpty()) { - String message = "Invalid UUID (" + token + "), could not create the remote session."; - log.error(message); - throw new RemoteSessionManagementException(message); - } else { - // create new device session - initializeDeviceSession(session, tenantDomain, deviceType, deviceId, operationId, token); - } - } - } - } - - @Override - public void initializeSession(Session session, String deviceType, String deviceId) throws - RemoteSessionManagementException { - initializeSession(session, deviceType, deviceId, null); - } - - /** - * Implements the behaviour of sending message to peer connection - * - * @param session Web socket RemoteSession - * @param message String message needs to send to peer connection - * @throws RemoteSessionManagementException throws when session cannot be made due to invalid data - * @throws RemoteSessionManagementException throws when session has error with accessing device resources - */ - @Override - public void sendMessageToPeer(Session session, String message) throws RemoteSessionManagementException { - JSONObject jsonObject = new JSONObject(message); - RemoteSession remoteSession = RemoteSessionManagementDataHolder.getInstance().getSessionMap().get(session - .getId()); - if (remoteSession != null) { - remoteSession.sendMessageToPeer(jsonObject.toString()); - } else { - throw new RemoteSessionManagementException("Remote Session cannot be found "); - } - } - - - /** - * Implements the behaviour of sending message to peer connection - * - * @param session Web socket RemoteSession - * @param message Byte message needs to send to peer connection - * @throws RemoteSessionManagementException throws when session cannot be made due to invalid data - * @throws RemoteSessionManagementException throws when session has error with accessing device resources - */ - @Override - public void sendMessageToPeer(Session session, byte[] message) throws RemoteSessionManagementException { - - RemoteSession remoteSession = RemoteSessionManagementDataHolder.getInstance().getSessionMap().get(session - .getId()); - if (remoteSession != null) { - remoteSession.sendMessageToPeer(message); - } else { - throw new RemoteSessionManagementException("Remote Session cannot be found "); - } - } - - /** - * Closing the session and cleanup the resources - * - * @param session Web socket Remote Session - */ - @Override - public void endSession(Session session, String closeReason) { - - RemoteSession remoteSession = RemoteSessionManagementDataHolder.getInstance().getSessionMap().remove(session - .getId()); - if (remoteSession != null) { - //String operationId = remoteSession.getOperationId(); - RemoteSessionManagementDataHolder.getInstance().getUuidToTenantMap().remove(remoteSession.getUuidToValidateDevice()); - String deviceKey = remoteSession.getTenantDomain() + "/" + remoteSession.getDeviceType() + "/" + - remoteSession.getDeviceId(); - RemoteSession lastSession = RemoteSessionManagementDataHolder.getInstance() - .getActiveDeviceClientSessionMap().get(deviceKey); - if (lastSession != null && lastSession.getMySession().getId().equals(session.getId())) { - RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap().remove - (deviceKey); - } - if (remoteSession.getPeerSession() != null) { - Session peerSession = remoteSession.getPeerSession().getMySession(); - if (peerSession != null) { - RemoteSessionManagementDataHolder.getInstance().getSessionMap().remove(peerSession.getId()); - if (lastSession != null && lastSession.getMySession().getId().equals(peerSession.getId())) { - RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap().remove - (deviceKey); - } - if (peerSession.isOpen()) { - try { - peerSession.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, closeReason)); - } catch (IOException ex) { - if (log.isDebugEnabled()) { - log.error("Failed to disconnect the client.", ex); - } - } - } - } - } - } - } - - - /** - * Starting new client session - * - * @param session Web socket Session - * @param tenantDomain Tenant domain - * @param deviceType Device Type - * @param deviceId Device Id - * @throws RemoteSessionManagementException throws when session has errors with accessing device resources - * @throws OperationManagementException throws when error occured during new operation - * @throws InvalidDeviceException throws when incorrect device identifier - */ - private void initializeClientSession(Session session, String tenantDomain, String deviceType, String deviceId) throws RemoteSessionManagementException, - OperationManagementException, InvalidDeviceException { - - String uuidToValidateDevice = UUID.randomUUID().toString(); - RemoteSession clientRemote = new RemoteSession(session, tenantDomain, deviceType, deviceId, RemoteSessionConstants - .CONNECTION_TYPE.CLIENT, uuidToValidateDevice); - String deviceKey = tenantDomain + "/" + deviceType + "/" + deviceId; - // Create new remote control operation to start the session - RemoteSession activeSession = RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap - ().putIfAbsent(deviceKey, clientRemote); - if (activeSession != null && activeSession.getMySession().isOpen() && activeSession - .getPeerSession() == null) { - throw new RemoteSessionManagementException("Another client session waiting on device to connect."); - } else { - // if there is pending session exists but already closed, then we need to remove it. - if (activeSession != null) { - RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap().remove - (deviceKey); - try { - activeSession.getMySession().close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "Remote " + - "session closed due to new session request")); - } catch (IOException ex) { - if (log.isDebugEnabled()) { - log.error("Failed to disconnect the client.", ex); - } - } - // Use put if absent for adding session to waiting list since we need to overcome - // multithreaded session requests. - activeSession = RemoteSessionManagementDataHolder.getInstance().getActiveDeviceClientSessionMap() - .putIfAbsent(deviceKey, clientRemote); - } - // If another client tried to start session same time then active session will be - // exist. So we are adding session request only no parallel sessions added to map - if (activeSession == null) { - - // Create operation if session initiated by client - Operation operation = new ConfigOperation(); - operation.setCode(RemoteSessionConstants.REMOTE_CONNECT); - operation.setEnabled(true); - operation.setControl(Operation.Control.NO_REPEAT); - JSONObject payload = new JSONObject(); - payload.put("serverUrl", RemoteSessionManagementDataHolder.getInstance().getServerUrl()); - payload.put("uuidToValidateDevice", uuidToValidateDevice); - RemoteSessionManagementDataHolder.getInstance().getUuidToTenantMap - ().put(uuidToValidateDevice, tenantDomain); - if (log.isDebugEnabled()) { - log.debug("UUID " + uuidToValidateDevice + " is generated against the tenant : " + - RemoteSessionManagementDataHolder.getInstance().getUuidToTenantMap().get(uuidToValidateDevice)); - } - operation.setPayLoad(payload.toString()); - String date = new SimpleDateFormat(RemoteSessionConstants.DATE_FORMAT_NOW).format(new Date()); - operation.setCreatedTimeStamp(date); - List deviceIdentifiers = new ArrayList<>(); - deviceIdentifiers.add(new DeviceIdentifier(deviceId, deviceType)); - Activity activity = RemoteSessionManagementDataHolder.getInstance(). - getDeviceManagementProviderService().addOperation(deviceType, operation, deviceIdentifiers); - clientRemote.setOperationId(activity.getActivityId().replace(DeviceManagementConstants - .OperationAttributes.ACTIVITY, "")); - RemoteSessionManagementDataHolder.getInstance().getSessionMap().put(session.getId(), clientRemote); - - log.info("Client remote session opened for session id: " + session.getId() + " device Type : " + - deviceType + " , " + "deviceId : " + deviceId); - } else { - throw new RemoteSessionManagementException("Another client session waiting on " + - "device to connect."); - } - } - } - - /** - * Starting new device session - * - * @param session Web socket Session - * @param tenantDomain Tenant domain - * @param deviceType Device Type - * @param deviceId Device Id - * @param operationId Operation id - * @throws RemoteSessionManagementException throws when session has errors with accessing device resources - */ - private void initializeDeviceSession(Session session, String tenantDomain, String deviceType, String deviceId, - String operationId, String uuidToValidateDevice) throws RemoteSessionManagementException { - String deviceKey = tenantDomain + "/" + deviceType + "/" + deviceId; - RemoteSession activeSession = RemoteSessionManagementDataHolder.getInstance() - .getActiveDeviceClientSessionMap().get(deviceKey); - if (activeSession != null) { - RemoteSession clientRemote = RemoteSessionManagementDataHolder.getInstance().getSessionMap().get - (activeSession.getMySession().getId()); - if (clientRemote != null) { - if (clientRemote.getOperationId().equals(operationId)) { - RemoteSession deviceRemote = new RemoteSession(session, tenantDomain, deviceType, deviceId, - RemoteSessionConstants.CONNECTION_TYPE.DEVICE, uuidToValidateDevice); - deviceRemote.setOperationId(operationId); - deviceRemote.setPeerSession(clientRemote); - clientRemote.setPeerSession(deviceRemote); - RemoteSessionManagementDataHolder.getInstance().getSessionMap().put(session.getId(), deviceRemote); - // Send Remote connect response - JSONObject message = new JSONObject(); - message.put(RemoteSessionConstants.REMOTE_CONNECT_CODE, RemoteSessionConstants.REMOTE_CONNECT); - deviceRemote.sendMessageToPeer(message.toString()); - log.info("Device session opened for session id: " + session.getId() + " device Type : " + - deviceType + " , " + "deviceId : " + deviceId); - } else { - throw new RemoteSessionManagementException("Device and Operation information " + - "does not matched with client information for operation id: " + operationId + " device " + - "Type : " + deviceType + " , " + "deviceId : " + deviceId); - } - } else { - throw new RemoteSessionManagementException("Device session is inactive for " + "operation id: " + - operationId + " device Type : " + deviceType + " , " + "deviceId : " + deviceId); - } - } else { - throw new RemoteSessionManagementException("Device session is inactive for operation " + "id: " + - operationId + " device Type : " + deviceType + " , " + "deviceId : " + deviceId); - } - - } - - /** - * Retrieving the token from the http session - * - * @param session WebSocket session - * @return retrieved token - */ - private String getTokenFromSession(Session session) { - if (session == null) { - return null; - } - String queryString = session.getQueryString(); - if (queryString != null) { - String[] allQueryParamPairs = queryString.split(RemoteSessionConstants.OAuthTokenValidator - .QUERY_STRING_SEPERATOR); - for (String keyValuePair : allQueryParamPairs) { - String[] queryParamPair = keyValuePair.split(RemoteSessionConstants.OAuthTokenValidator - .QUERY_KEY_VALUE_SEPERATOR); - if (queryParamPair.length != 2) { - log.warn("Invalid query string [" + queryString + "] passed in."); - break; - } - if (queryParamPair[0].equals(RemoteSessionConstants.OAuthTokenValidator.TOKEN_IDENTIFIER)) { - return queryParamPair[1]; - } - } - } - return null; - } -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/AuthenticationInfo.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/AuthenticationInfo.java deleted file mode 100644 index e7d77e5bd..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/AuthenticationInfo.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.authentication; - -import java.util.Map; - -/** - * This is returned after authentication. - */ -public class AuthenticationInfo { - - /** - * this variable is used to check whether the client is authenticated. - */ - private boolean authenticated; - private String username; - private String tenantDomain; - - /** - * To hold authentication related properties eg: scopes in oauth - */ - private Map properties; - - /** - * returns whether the client is authenticated - */ - public boolean isAuthenticated() { - return authenticated; - } - - public void setAuthenticated(boolean authenticated) { - this.authenticated = authenticated; - } - - /** - * returns the authenticated client username - */ - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - /** - * return the authenticated client tenant domain - */ - public String getTenantDomain() { - return tenantDomain; - } - - public void setTenantDomain(String tenantDomain) { - this.tenantDomain = tenantDomain; - } - - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/OAuthAuthenticator.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/OAuthAuthenticator.java deleted file mode 100644 index c8ecdab26..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/OAuthAuthenticator.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.authentication; - -import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.oauth.OAuthTokenValidator; - -import java.util.List; -import java.util.Map; - -/** - * {@link OAuthAuthenticator} for validate tokens to web socket api - */ -public class OAuthAuthenticator { - OAuthTokenValidator oAuthTokenValidator; - - public void init(Map globalProperties) { - oAuthTokenValidator = new OAuthTokenValidator(globalProperties); - } - - public AuthenticationInfo isAuthenticated(String token) { - return oAuthTokenValidator.validateToken(token); - } -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/OAuthTokenValidator.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/OAuthTokenValidator.java deleted file mode 100644 index 0d17dad8a..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/OAuthTokenValidator.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and limitations under the License. - * - */ - -package org.wso2.carbon.device.mgt.extensions.remote.session.authentication.oauth; - -import org.apache.axis2.context.ServiceContext; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.pool.impl.GenericObjectPool; -import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.AuthenticationInfo; -import org.wso2.carbon.device.mgt.extensions.remote.session.constants.RemoteSessionConstants; -import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - -import java.rmi.RemoteException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * This acts as a contract point for OAuth token validation. - */ -public class OAuthTokenValidator { - - private static String cookie; - private GenericObjectPool stubs; - private static Log log = LogFactory.getLog(OAuthTokenValidator.class); - - public OAuthTokenValidator(Map globalProperties) { - this.stubs = new GenericObjectPool(new OAuthTokenValidatorStubFactory(globalProperties)); - } - - /** - * This method gets a string accessToken and validates it - * - * @param token oauth token - * @return AuthenticationInfo with the validated results. - */ - public AuthenticationInfo validateToken(String token) { - if (token == null) { - AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setAuthenticated(false); - return authenticationInfo; - } - OAuth2TokenValidationServiceStub tokenValidationServiceStub = null; - try { - Object stub = this.stubs.borrowObject(); - if (stub != null) { - tokenValidationServiceStub = (OAuth2TokenValidationServiceStub) stub; - return getAuthenticationInfo(token, tokenValidationServiceStub); - } else { - log.warn("Stub initialization failed."); - } - } catch (RemoteException e) { - log.error("Error on connecting with the validation endpoint.", e); - } catch (Exception e) { - log.error("Error occurred in borrowing an validation stub from the pool.", e); - - } finally { - try { - if (tokenValidationServiceStub != null) { - this.stubs.returnObject(tokenValidationServiceStub); - } - } catch (Exception e) { - log.warn("Error occurred while returning the object back to the oauth token validation service " + - "stub pool.", e); - } - } - AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - authenticationInfo.setAuthenticated(false); - return authenticationInfo; - } - - /** - * This creates an AuthenticationInfo object that is used for authorization. This method will validate the token - * and - * sets the required parameters to the object. - * - * @param token that needs to be validated. - * @param tokenValidationServiceStub stub that is used to call the external service. - * @return AuthenticationInfo This contains the information related to authenticated client. - * @throws RemoteException that triggers when failing to call the external service.. - */ - private AuthenticationInfo getAuthenticationInfo(String token, - OAuth2TokenValidationServiceStub tokenValidationServiceStub) - throws RemoteException { - AuthenticationInfo authenticationInfo = new AuthenticationInfo(); - OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); - OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = - new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); - accessToken.setTokenType(RemoteSessionConstants.OAuthTokenValidator.TOKEN_TYPE); - accessToken.setIdentifier(token); - validationRequest.setAccessToken(accessToken); - boolean authenticated; - OAuth2TokenValidationResponseDTO tokenValidationResponse; - tokenValidationResponse = tokenValidationServiceStub.validate(validationRequest); - if (tokenValidationResponse == null) { - authenticationInfo.setAuthenticated(false); - return authenticationInfo; - } - authenticated = tokenValidationResponse.getValid(); - if (authenticated) { - String authorizedUser = tokenValidationResponse.getAuthorizedUser(); - String username = MultitenantUtils.getTenantAwareUsername(authorizedUser); - String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser); - authenticationInfo.setUsername(username); - authenticationInfo.setTenantDomain(tenantDomain); - String scopes[] = tokenValidationResponse.getScope(); - if (scopes != null) { - Map properties = new HashMap<>(); - properties.put(RemoteSessionConstants.SCOPE_IDENTIFIER, scopes); - authenticationInfo.setProperties(properties); - } - } else { - if (log.isDebugEnabled()) { - log.debug("Token validation failed for token: " + token); - } - } - ServiceContext serviceContext = tokenValidationServiceStub._getServiceClient() - .getLastOperationContext().getServiceContext(); - cookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING); - authenticationInfo.setAuthenticated(authenticated); - return authenticationInfo; - } - -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/OAuthTokenValidatorStubFactory.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/OAuthTokenValidatorStubFactory.java deleted file mode 100644 index 399b08c01..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/OAuthTokenValidatorStubFactory.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.extensions.remote.session.authentication.oauth; - -import org.apache.axis2.AxisFault; -import org.apache.axis2.Constants; -import org.apache.axis2.client.Options; -import org.apache.axis2.client.ServiceClient; -import org.apache.axis2.transport.http.HTTPConstants; -import org.apache.axis2.transport.http.HttpTransportProperties; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpConnectionManager; -import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; -import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory; -import org.apache.commons.httpclient.params.HttpConnectionManagerParams; -import org.apache.commons.httpclient.protocol.Protocol; -import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.commons.pool.BasePoolableObjectFactory; -import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.oauth.exception.OAuthTokenValidationException; -import org.wso2.carbon.device.mgt.extensions.remote.session.constants.RemoteSessionConstants; -import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException; -import org.wso2.carbon.device.mgt.extensions.remote.session.util.PropertyUtils; -import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.util.Map; - - -/** - * This follows object pool pattern to manage the stub for oauth validation service. - */ -public class OAuthTokenValidatorStubFactory extends BasePoolableObjectFactory { - private static final Log log = LogFactory.getLog(OAuthTokenValidatorStubFactory.class); - private HttpClient httpClient; - Map tokenValidationProperties; - - public OAuthTokenValidatorStubFactory(Map globalProperties) { - this.tokenValidationProperties = globalProperties; - this.httpClient = createHttpClient(); - } - - /** - * This creates a OAuth2TokenValidationServiceStub object to the pool. - * - * @return an OAuthValidationStub object - * @throws Exception thrown when creating the object. - */ - @Override - public Object makeObject() throws Exception { - return this.generateStub(); - } - - /** - * This is used to clean up the OAuth validation stub and releases to the object pool. - * - * @param o object that needs to be released. - * @throws Exception throws when failed to release to the pool - */ - @Override - public void passivateObject(Object o) throws Exception { - if (o instanceof OAuth2TokenValidationServiceStub) { - OAuth2TokenValidationServiceStub stub = (OAuth2TokenValidationServiceStub) o; - stub._getServiceClient().cleanupTransport(); - } - } - - /** - * This is used to create a stub which will be triggered through object pool factory, which will create an - * instance of it. - * - * @return OAuth2TokenValidationServiceStub stub that is used to call an external service. - * @throws OAuthTokenValidationException will be thrown when initialization failed. - */ - private OAuth2TokenValidationServiceStub generateStub() throws OAuthTokenValidationException { - OAuth2TokenValidationServiceStub stub; - try { - URL hostURL = new URL(PropertyUtils.replaceProperty(tokenValidationProperties.get( - (RemoteSessionConstants.TOKEN_VALIDATION_ENDPOINT_URL))) - + RemoteSessionConstants.TOKEN_VALIDATION_CONTEX); - stub = new OAuth2TokenValidationServiceStub(hostURL.toString()); - ServiceClient client = stub._getServiceClient(); - client.getServiceContext().getConfigurationContext().setProperty( - HTTPConstants.CACHED_HTTP_CLIENT, httpClient); - - HttpTransportProperties.Authenticator auth = - new HttpTransportProperties.Authenticator(); - auth.setPreemptiveAuthentication(true); - String username = tokenValidationProperties.get(RemoteSessionConstants.USERNAME); - String password = tokenValidationProperties.get(RemoteSessionConstants.PASSWORD); - auth.setUsername(username); - auth.setPassword(password); - Options options = client.getOptions(); - options.setProperty(HTTPConstants.AUTHENTICATE, auth); - options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); - client.setOptions(options); - if (hostURL.getProtocol().equals("https")) { - // set up ssl factory since axis2 https notification is used. - EasySSLProtocolSocketFactory sslProtocolSocketFactory = createProtocolSocketFactory(); - int port = hostURL.getPort(); - if (port == -1) { - port = 443; - } - Protocol authhttps = new Protocol(hostURL.getProtocol(), - (ProtocolSocketFactory) sslProtocolSocketFactory, port); - Protocol.registerProtocol(hostURL.getProtocol(), authhttps); - options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, authhttps); - } - - } catch (AxisFault axisFault) { - throw new OAuthTokenValidationException( - "Error occurred while creating the OAuth2TokenValidationServiceStub.", axisFault); - } catch (MalformedURLException e) { - throw new OAuthTokenValidationException( - "Error occurred while parsing token endpoint URL", e); - } catch (RemoteSessionManagementException e) { - throw new OAuthTokenValidationException("Invalid token endpoint url", e); - } - - return stub; - } - - /** - * This is required to create a trusted connection with the external entity. - * Have to manually configure it since we use CommonHTTPTransport(axis2 notification) in axis2. - * - * @return an EasySSLProtocolSocketFactory for SSL communication. - */ - private EasySSLProtocolSocketFactory createProtocolSocketFactory() throws OAuthTokenValidationException { - try { - return new EasySSLProtocolSocketFactory(); - } catch (IOException e) { - String errorMsg = "Failed to initiate EasySSLProtocolSocketFactory."; - throw new OAuthTokenValidationException(errorMsg, e); - } catch (GeneralSecurityException e) { - String errorMsg = "Failed to set the key material in easy ssl factory."; - throw new OAuthTokenValidationException(errorMsg, e); - } - } - - /** - * This created httpclient pool that can be used to connect to external entity. This connection can be configured - * via broker.xml by setting up the required http connection parameters. - * - * @return an instance of HttpClient that is configured with MultiThreadedHttpConnectionManager - */ - private HttpClient createHttpClient() { - HttpConnectionManagerParams params = new HttpConnectionManagerParams(); - params.setDefaultMaxConnectionsPerHost(Integer.parseInt(tokenValidationProperties.get( - RemoteSessionConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST))); - params.setMaxTotalConnections(Integer.parseInt(tokenValidationProperties.get( - RemoteSessionConstants.MAXIMUM_TOTAL_HTTP_CONNECTION))); - HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); - connectionManager.setParams(params); - return new HttpClient(connectionManager); - } -} \ No newline at end of file diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/constants/RemoteSessionConstants.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/constants/RemoteSessionConstants.java deleted file mode 100644 index 33684eac2..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/constants/RemoteSessionConstants.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.extensions.remote.session.constants; - -/** - * This holds the constants related to remote session - */ -public class RemoteSessionConstants { - - public static final String SCOPE_IDENTIFIER = "scopes"; - public static final String TOKEN_VALIDATION_ENDPOINT_URL = "tokenValidationUrl"; - public static final String TOKEN_VALIDATION_CONTEX = "/services/OAuth2TokenValidationService"; - public static final String USERNAME = "username"; - public static final String PASSWORD = "password"; - public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; - public static final int MAX_BUFFER_SIZE = 640 * 1024; - - public enum CONNECTION_TYPE { - CLIENT, DEVICE - } - - public static final String QUERY_STRING = "queryString"; - public static final String MAXIMUM_TOTAL_HTTP_CONNECTION = "maximumTotalHttpConnection"; - public static final String MAXIMUM_HTTP_CONNECTION_PER_HOST = "maximumHttpConnectionPerHost"; - public static final String DEFAULT_MAXIMUM_HTTP_CONNECTION_PER_HOST = "2"; - public static final String DEFAULT_MAXIMUM_TOTAL_HTTP_CONNECTIONS = "100"; - - // Initial remote connection operation related Constants - public static final String REMOTE_CONNECT = "REMOTE_CONNECT"; - public static final String REMOTE_CONNECT_CODE = "code"; - - private RemoteSessionConstants() { - } - - /** - * OAuthTokenValidator specific constants - */ - public final class OAuthTokenValidator { - public static final String COOKIE_KEY_VALUE_SEPERATOR = "="; - public static final String COOKIE_KEYPAIR_SEPERATOR = ";"; - public static final String COOKIE = "cookie"; - public static final String TOKEN_TYPE = "bearer"; - public static final String TOKEN_IDENTIFIER = "websocketToken"; - public static final String QUERY_STRING_SEPERATOR = "&"; - public static final String QUERY_KEY_VALUE_SEPERATOR = "="; - public static final String QUERY_STRING = "queryString"; - - private OAuthTokenValidator() { - } - } - -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/dto/RemoteSession.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/dto/RemoteSession.java deleted file mode 100644 index 79bb31b2f..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/dto/RemoteSession.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.extensions.remote.session.dto; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.extensions.remote.session.constants.RemoteSessionConstants; -import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException; -import org.wso2.carbon.device.mgt.extensions.remote.session.internal.RemoteSessionManagementDataHolder; - -import javax.websocket.Session; -import java.io.IOException; -import java.nio.ByteBuffer; - -/** - * {@link RemoteSession} will represent remote websocket session - * This class implements the behaviours of sending message to the session in multithreaded context. - */ -public class RemoteSession { - - private static final Log log = LogFactory.getLog(RemoteSession.class); - private String tenantDomain; - private String operationId; - private String deviceType; - private String deviceId; - private String uuidToValidateDevice; - private long lastMessageTimeStamp = System.currentTimeMillis(); - private RemoteSession peerSession; - private Session mySession; - private final Object writeLockObject = new Object(); - private int maxMessagesPerSecond; - private int messageAllowance; - private double messageRatePerSecond; - private RemoteSessionConstants.CONNECTION_TYPE connectionType; - - public RemoteSession(Session session, String tenantDomain, String deviceType, String deviceId, - RemoteSessionConstants.CONNECTION_TYPE connectionType, String uuidToValidateDevice) { - this.mySession = session; - this.deviceType = deviceType; - this.deviceId = deviceId; - this.tenantDomain = tenantDomain; - this.connectionType = connectionType; - this.uuidToValidateDevice = uuidToValidateDevice; - maxMessagesPerSecond = RemoteSessionManagementDataHolder.getInstance().getMaxMessagesPerSecond(); - messageAllowance = maxMessagesPerSecond; - messageRatePerSecond = (double) maxMessagesPerSecond / 1000; - } - - private void sendMessage(Object message) throws RemoteSessionManagementException { - if (message != null) { - boolean isMessageCountExceed = false; - if (mySession != null && mySession.isOpen()) { - synchronized (writeLockObject) { - try { - isMessageCountExceed = applyRateLimit(); - if (!isMessageCountExceed) { - if (message instanceof String) { - mySession.getBasicRemote().sendText(message.toString()); - } else { - mySession.getBasicRemote().sendBinary(ByteBuffer.wrap((byte[]) message)); - } - this.lastMessageTimeStamp = System.currentTimeMillis(); - } else { - log.warn("Message count per second is exceeded for device id :" + deviceId); - } - } catch (IOException e) { - log.warn("Send data to session failed due to ", e); - } - } - } else { - throw new RemoteSessionManagementException("Peer Session already closed "); - } - } else { - throw new RemoteSessionManagementException("Message is empty"); - } - } - - public void sendMessageToPeer(Object message) throws RemoteSessionManagementException { - peerSession.sendMessage(message); - } - - /** - * Use for limit the messages for given time - * - * @return message rate applied - */ - private boolean applyRateLimit() { - long currentTime = System.currentTimeMillis(); - messageAllowance += (currentTime - lastMessageTimeStamp) * messageRatePerSecond; - if (messageAllowance > maxMessagesPerSecond) { - messageAllowance = maxMessagesPerSecond; - } - if (messageAllowance >= 1) { - lastMessageTimeStamp = currentTime; - messageAllowance -= 1; - return false; - } else { - return true; - } - } - - public String getUuidToValidateDevice() { - return uuidToValidateDevice; - } - - public Session getMySession() { - return mySession; - } - - public RemoteSession getPeerSession() { - return peerSession; - } - - public void setPeerSession(RemoteSession peerSession) { - this.peerSession = peerSession; - } - - public String getTenantDomain() { - return tenantDomain; - } - - public String getOperationId() { - return operationId; - } - - public void setOperationId(String operationId) { - this.operationId = operationId; - } - - public String getDeviceType() { - return deviceType; - } - - public String getDeviceId() { - return deviceId; - } - - public RemoteSessionConstants.CONNECTION_TYPE getConnectionType() { - return connectionType; - } -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/exception/RemoteSessionManagementException.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/exception/RemoteSessionManagementException.java deleted file mode 100644 index 741f04e31..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/exception/RemoteSessionManagementException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.extensions.remote.session.exception; - - -import javax.websocket.CloseReason; - -/** - * This Exception will be thrown, when there any management issues with Remote Session. - */ -public class RemoteSessionManagementException extends Exception { - - CloseReason closeReason; - - public RemoteSessionManagementException(String msg) { - super(msg); - this.closeReason = new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, msg); - } - - public CloseReason getCloseReason() { - return closeReason; - } - - -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/internal/RemoteSessionManagementDataHolder.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/internal/RemoteSessionManagementDataHolder.java deleted file mode 100644 index d1c2f058c..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/internal/RemoteSessionManagementDataHolder.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.extensions.remote.session.internal; - -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.OAuthAuthenticator; -import org.wso2.carbon.device.mgt.extensions.remote.session.dto.RemoteSession; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Class {@link RemoteSessionManagementDataHolder} will hold the configurations and in memory storage strictures to - * manage remote sessions. - */ -public class RemoteSessionManagementDataHolder { - - private static RemoteSessionManagementDataHolder thisInstance = new RemoteSessionManagementDataHolder(); - private DeviceManagementProviderService deviceManagementProviderService; - private DeviceAccessAuthorizationService deviceAccessAuthorizationService; - private boolean isEnabled; - private String serverUrl; - private long maxIdleTimeout; - private int maxMessageBufferSize; - private int maxMessagesPerSecond; - private OAuthAuthenticator oAuthAuthenticator; - private Map activeDeviceClientSessionMap = new ConcurrentHashMap(); - private Map sessionMap = new ConcurrentHashMap(); - private Map uuidToTenantMap = new ConcurrentHashMap<>(); - - public Map getUuidToTenantMap() { - return uuidToTenantMap; - } - - public static RemoteSessionManagementDataHolder getInstance() { - return thisInstance; - } - - public DeviceManagementProviderService getDeviceManagementProviderService() { - return deviceManagementProviderService; - } - - public void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) { - this.deviceManagementProviderService = deviceManagementProviderService; - } - - public DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() { - return deviceAccessAuthorizationService; - } - - public void setDeviceAccessAuthorizationService(DeviceAccessAuthorizationService deviceAccessAuthorizationService) { - this.deviceAccessAuthorizationService = deviceAccessAuthorizationService; - } - - public OAuthAuthenticator getOauthAuthenticator() { - return oAuthAuthenticator; - } - - public void setOauthAuthenticator(OAuthAuthenticator oAuthAuthenticator) { - this.oAuthAuthenticator = oAuthAuthenticator; - } - - public Map getSessionMap() { - return sessionMap; - } - - public Map getActiveDeviceClientSessionMap() { - return activeDeviceClientSessionMap; - } - - public boolean isEnabled() { - return isEnabled; - } - - public void setEnabled(boolean enabled) { - isEnabled = enabled; - } - - public String getServerUrl() { - return serverUrl; - } - - public void setServerUrl(String serverUrl) { - this.serverUrl = serverUrl; - } - - public int getMaxMessagesPerSecond() { - return maxMessagesPerSecond; - } - - public void setMaxMessagesPerSecond(int maxMessagesPerSecond) { - this.maxMessagesPerSecond = maxMessagesPerSecond; - } - - public long getMaxIdleTimeout() { - return maxIdleTimeout; - } - - public void setMaxIdleTimeout(long maxIdleTimeout) { - this.maxIdleTimeout = maxIdleTimeout; - } - - public int getMaxMessageBufferSize() { - return maxMessageBufferSize; - } - - public void setMaxMessageBufferSize(int MaxMessageBufferSize) { - this.maxMessageBufferSize = MaxMessageBufferSize; - } -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/internal/RemoteSessionManagementServiceComponent.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/internal/RemoteSessionManagementServiceComponent.java deleted file mode 100644 index da394210c..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/internal/RemoteSessionManagementServiceComponent.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.extensions.remote.session.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.core.ServerStartupObserver; -import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.extensions.remote.session.RemoteSessionManagementService; -import org.wso2.carbon.device.mgt.extensions.remote.session.RemoteSessionManagementServiceImpl; -import org.wso2.carbon.device.mgt.extensions.remote.session.listener.RemoteSessionManagerStartupListener; - -/** - * @scr.component name="RemoteSessionManagementServiceComponent" immediate="true" - * @scr.reference name="carbon.device.mgt.provider" - * interface="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementProviderService" - * unbind="unsetDeviceManagementProviderService" - * @scr.reference name="device.manager.service" - * interface="org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService" - * cardinality="0..n" - * policy="dynamic" - * bind="setDeviceAccessAuthorizationService" - * unbind="unsetDeviceAccessAuthorizationService" - */ - -public class RemoteSessionManagementServiceComponent { - - private static final Log log = LogFactory.getLog(RemoteSessionManagementServiceComponent.class); - - protected void activate(ComponentContext componentContext) { - try { - - BundleContext bundleContext = componentContext.getBundleContext(); - bundleContext.registerService(ServerStartupObserver.class.getName(), new - RemoteSessionManagerStartupListener(), null); - bundleContext.registerService(RemoteSessionManagementService.class.getName(), new - RemoteSessionManagementServiceImpl(), null); - if (log.isDebugEnabled()) { - log.debug("Remote Session device access service implementation bundle has been successfully " + - "initialized"); - } - } catch (Throwable e) { - log.error("Error occurred while initializing Remote Session device access service " + - "implementation bundle", e); - } - } - - protected void deactivate(ComponentContext componentContext) { - //Do nothing - } - - protected void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) { - RemoteSessionManagementDataHolder.getInstance() - .setDeviceManagementProviderService(deviceManagementProviderService); - } - - protected void unsetDeviceManagementProviderService(DeviceManagementProviderService - deviceManagementProviderService) { - RemoteSessionManagementDataHolder.getInstance().setDeviceManagementProviderService(null); - } - - protected void setDeviceAccessAuthorizationService(DeviceAccessAuthorizationService - deviceAccessAuthorizationService) { - RemoteSessionManagementDataHolder.getInstance() - .setDeviceAccessAuthorizationService(deviceAccessAuthorizationService); - } - - protected void unsetDeviceAccessAuthorizationService(DeviceAccessAuthorizationService - deviceAccessAuthorizationService) { - RemoteSessionManagementDataHolder.getInstance().setDeviceManagementProviderService(null); - } - -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/listener/RemoteSessionManagerStartupListener.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/listener/RemoteSessionManagerStartupListener.java deleted file mode 100644 index 8236cb848..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/listener/RemoteSessionManagerStartupListener.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.extensions.remote.session.listener; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.core.ServerStartupObserver; -import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; -import org.wso2.carbon.device.mgt.core.config.keymanager.KeyManagerConfigurations; -import org.wso2.carbon.device.mgt.core.config.remote.session.RemoteSessionConfiguration; -import org.wso2.carbon.device.mgt.extensions.remote.session.authentication.OAuthAuthenticator; -import org.wso2.carbon.device.mgt.extensions.remote.session.constants.RemoteSessionConstants; -import org.wso2.carbon.device.mgt.extensions.remote.session.internal.RemoteSessionManagementDataHolder; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -import java.util.HashMap; -import java.util.Map; - -/** - * Startup listener is been used to make sure the receiver gets activated after the server start up to avoid - * Bundle not loading issues. - * This will configure the values for remote session management - */ -public class RemoteSessionManagerStartupListener implements ServerStartupObserver { - - private static final Log log = LogFactory.getLog(RemoteSessionManagerStartupListener.class); - - @Override - public void completingServerStartup() { - } - - @Override - public void completedServerStartup() { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( - MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); - try { - RemoteSessionConfiguration rsConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig - ().getRemoteSessionConfiguration(); - KeyManagerConfigurations kmConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig() - .getKeyManagerConfigurations(); - - RemoteSessionManagementDataHolder.getInstance().setEnabled(rsConfig.isEnabled()); - RemoteSessionManagementDataHolder.getInstance().setServerUrl(rsConfig.getRemoteSessionServerUrl()); - Map configProperties = new HashMap<>(); - - // Set max idle timeout in milliseconds - RemoteSessionManagementDataHolder.getInstance().setMaxIdleTimeout((long) rsConfig.getSessionIdleTimeOut() * - 60000); - // Set max buffer size for messages. - if (rsConfig.getMaxMessageBufferSize() > 0) { - RemoteSessionManagementDataHolder.getInstance() - .setMaxMessageBufferSize(rsConfig.getMaxMessageBufferSize() * 1024); - } else { - RemoteSessionManagementDataHolder.getInstance(). - setMaxMessageBufferSize(RemoteSessionConstants.MAX_BUFFER_SIZE); - } - - // Set max messages per second. - if (rsConfig.getMaxMessagesPerSession() > 0) { - RemoteSessionManagementDataHolder.getInstance().setMaxMessagesPerSecond(rsConfig - .getMaxMessagesPerSession()); - } - // Token validation related configuration - configProperties.put(RemoteSessionConstants.TOKEN_VALIDATION_ENDPOINT_URL, kmConfig.getServerUrl()); - configProperties.put(RemoteSessionConstants.USERNAME, kmConfig.getAdminUsername()); - configProperties.put(RemoteSessionConstants.PASSWORD, kmConfig.getAdminPassword()); - if (rsConfig.getMaxHTTPConnectionPerHost() > 0) { - - configProperties.put(RemoteSessionConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST, - String.valueOf(rsConfig.getMaxHTTPConnectionPerHost())); - } else { - configProperties.put(RemoteSessionConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST, RemoteSessionConstants - .DEFAULT_MAXIMUM_HTTP_CONNECTION_PER_HOST); - } - if (rsConfig.getMaxTotalHTTPConnections() > 0) { - configProperties.put(RemoteSessionConstants.MAXIMUM_TOTAL_HTTP_CONNECTION, String.valueOf(rsConfig - .getMaxTotalHTTPConnections())); - } else { - configProperties.put(RemoteSessionConstants.MAXIMUM_TOTAL_HTTP_CONNECTION, RemoteSessionConstants - .DEFAULT_MAXIMUM_TOTAL_HTTP_CONNECTIONS); - } - - OAuthAuthenticator oAuthAuthenticator = new OAuthAuthenticator(); - oAuthAuthenticator.init(configProperties); - RemoteSessionManagementDataHolder.getInstance().setOauthAuthenticator(oAuthAuthenticator); - - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - } - -} diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/util/PropertyUtils.java b/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/util/PropertyUtils.java deleted file mode 100644 index cb63b97ac..000000000 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/util/PropertyUtils.java +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you under the Apache License, -* Version 2.0 (the "License"); you may not use this file except -* in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ - -package org.wso2.carbon.device.mgt.extensions.remote.session.util; - -import org.wso2.carbon.device.mgt.extensions.remote.session.exception.RemoteSessionManagementException; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Class for reading web socket url parameters - */ -public class PropertyUtils { - - /** - * Replace URL with placeholders with properties - * @param urlWithPlaceholders URL - * @return replaced url - * @throws RemoteSessionManagementException - */ - public static String replaceProperty(String urlWithPlaceholders) throws RemoteSessionManagementException { - String regex = "\\$\\{(.*?)\\}"; - Pattern pattern = Pattern.compile(regex); - Matcher matchPattern = pattern.matcher(urlWithPlaceholders); - while (matchPattern.find()) { - String sysPropertyName = matchPattern.group(1); - String sysPropertyValue = System.getProperty(sysPropertyName); - if (sysPropertyValue != null && !sysPropertyName.isEmpty()) { - urlWithPlaceholders = urlWithPlaceholders.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue); - } else { - throw new RemoteSessionManagementException("System property - " + sysPropertyName - + " is not defined, hence cannot resolve : " + urlWithPlaceholders); - } - } - return urlWithPlaceholders; - } -} diff --git a/components/extensions/remote-session-extension/pom.xml b/components/extensions/remote-session-extension/pom.xml deleted file mode 100644 index d6488c370..000000000 --- a/components/extensions/remote-session-extension/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt-plugins - extensions - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - remote-session-extension - pom - WSO2 Carbon - Remote Sessions Extension - http://wso2.org - - - org.wso2.carbon.device.mgt.extensions.remote.session - org.wso2.carbon.device.mgt.extensions.remote.session.endpoint - - - - - - - org.apache.felix - maven-scr-plugin - ${maven.scr.version} - - - generate-scr-scrdescriptor - - scr - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/pom.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/pom.xml deleted file mode 100644 index 0774b29df..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/pom.xml +++ /dev/null @@ -1,260 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt-plugins - siddhi-extensions - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.extension.siddhi.device - bundle - WSO2 Siddhi Execution Extension - Device management Core functionality as Siddhi extension - http://wso2.org - - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - - - org.wso2.siddhi - siddhi-core - - - org.wso2.siddhi - siddhi-query-api - - - log4j - log4j - - - org.json.wso2 - json - - - org.wso2.carbon.devicemgt - org.wso2.carbon.identity.jwt.client.extension - - - io.github.openfeign - feign-core - - - io.github.openfeign - feign-jaxrs - - - io.github.openfeign - feign-gson - - - io.github.openfeign - feign-slf4j - - - com.squareup.okhttp3 - okhttp - - - com.squareup.okio - okio - - - io.github.openfeign - feign-okhttp - - - javax.ws.rs - jsr311-api - - - com.h2database.wso2 - h2-database-engine - test - - - org.testng - testng - test - - - org.wso2.carbon - org.wso2.carbon.queuing - test - - - org.wso2.carbon - org.wso2.carbon.ndatasource.core - test - - - commons-dbcp.wso2 - commons-dbcp - test - - - commons-pool.wso2 - commons-pool - test - - - org.wso2.carbon - javax.cache.wso2 - test - - - asm - asm - RELEASE - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon - org.wso2.carbon.utils - - - org.wso2.carbon - org.wso2.carbon.user.api - - - org.wso2.carbon - org.wso2.carbon.base - - - org.wso2.carbon - org.wso2.carbon.registry.core - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${wso2.maven.compiler.source} - ${wso2.maven.compiler.target} - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - - org.wso2.extension.siddhi.device, - org.wso2.extension.siddhi.device.* - - - feign, - feign.codec, - feign.auth, - feign.gson, - feign.slf4j, - javax.net.ssl, - javax.xml, - javax.xml.bind, - javax.xml.bind.annotation, - javax.xml.parsers;resolution:=optional, - org.apache.commons.lang, - org.w3c.dom, - org.wso2.carbon.base, - org.wso2.carbon.utils, - org.wso2.carbon.user.api, - org.json;version="${orbit.version.json.range}", - org.wso2.siddhi.core.*, - org.wso2.siddhi.query.api.*, - org.wso2.carbon.device.mgt.core.*, - org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.identity.jwt.client.*, - org.apache.commons.logging, - org.wso2.carbon.context, - android.util;resolution:=optional, - javax.annotation;resolution:=optional, - javax.net;resolution:=optional, - javax.security.auth.x500;resolution:=optional, - javax.crypto;resolution:=optional, - javax.crypto.spec;resolution:=optional - - - jsr311-api, - feign-jaxrs, - feign-okhttp, - okhttp, - okio - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - file:src/test/resources/log4j.properties - - - src/test/resources/testng.xml - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/AddNotificationFunctionProcessor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/AddNotificationFunctionProcessor.java deleted file mode 100644 index ec9cfd347..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/AddNotificationFunctionProcessor.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; -import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; -import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.query.processor.stream.function.StreamFunctionProcessor; -import org.wso2.siddhi.query.api.definition.AbstractDefinition; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -import java.util.ArrayList; -import java.util.List; - -public class AddNotificationFunctionProcessor extends StreamFunctionProcessor { - - private static final Log log = LogFactory.getLog(AddNotificationFunctionProcessor.class); - - /** - * The init method of the StreamProcessor, this method will be called before other methods - * - * @param abstractDefinition the incoming stream definition - * @param attributeExpressionExecutors the executors of each function parameters - * @param executionPlanContext the context of the execution plan - * @return the additional output attributes introduced by the function - */ - @Override - protected List init(AbstractDefinition abstractDefinition, - ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 3) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to device:addNotification() function, required 3 but found " + - attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument (deviceIdentifier) of device:addNotification() " + - "function, required " + Attribute.Type.STRING + " as deviceIdentifier, but found " + - attributeExpressionExecutors[0].getReturnType().toString()); - } - if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument (deviceType) of device:addNotification() " + - "function, required " + Attribute.Type.STRING + " as deviceType, but found " + - attributeExpressionExecutors[1].getReturnType().toString()); - } - if (attributeExpressionExecutors[2].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the third argument (description) of device:addNotification() " + - "function, required " + Attribute.Type.STRING + " as description, but found " + - attributeExpressionExecutors[2].getReturnType().toString()); - } - ArrayList attributes = new ArrayList<>(); - attributes.add(new Attribute("notified", Attribute.Type.BOOL)); - return attributes; - } - - /** - * The process method of the StreamFunction, used when more than one function parameters are provided - * - * @param data the data values for the function parameters - * @return the data for additional output attributes introduced by the function - */ - @Override - protected Object[] process(Object[] data) { - if (data[0] == null || data[1] == null || data[2] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:addNotification() function. " + - "Neither of any three arguments cannot be null"); - } - boolean isNotified = false; - String deviceId = (String) data[0]; - String deviceType = (String) data[1]; - String description = (String) data[2]; - Notification notification = new Notification(); - notification.setStatus(Notification.Status.NEW.name()); - notification.setDeviceIdentifier(deviceId); - notification.setDeviceType(deviceType); - notification.setDescription(description); - - NotificationManagementService notificationManagementService = DeviceUtils.getNotificationManagementService(); - try { - isNotified = notificationManagementService.addNotification(new DeviceIdentifier(deviceId, deviceType), notification); - } catch (NotificationManagementException e) { - // We are not throwing this exception to siddhi runtime as it will break the complete siddhi execution - // flow for the event stream coming in. - log.error("Error occurred while adding notification '" + notification.toString() + "' for " + - deviceType + " device with id " + deviceId, e); - } - - return new Object[]{isNotified}; - } - - /** - * The process method of the StreamFunction, used when zero or one function parameter is provided - * - * @param data null if the function parameter count is zero or runtime data value of the function parameter - * @return the data for additional output attribute introduced by the function - */ - @Override - protected Object[] process(Object data) { - return new Object[0]; - } - - /** - * This will be called only once and this can be used to acquire - * required resources for the processing element. - * This will be called after initializing the system and before - * starting to process the events. - */ - @Override - public void start() { - - } - - /** - * This will be called only once and this can be used to release - * the acquired resources for processing. - * This will be called before shutting down the system. - */ - @Override - public void stop() { - - } - - /** - * Used to collect the serializable state of the processing element, that need to be - * persisted for the reconstructing the element to the same state on a different point of time - * - * @return stateful objects of the processing element as an array - */ - @Override - public Object[] currentState() { - return new Object[0]; - } - - /** - * Used to restore serialized state of the processing element, for reconstructing - * the element to the same state as if was on a previous point of time. - * - * @param objects the stateful objects of the element as an array on - * the same order provided by currentState(). - */ - @Override - public void restoreState(Object[] objects) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/AddOperationFunctionProcessor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/AddOperationFunctionProcessor.java deleted file mode 100644 index f3abc1a99..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/AddOperationFunctionProcessor.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device; - -import feign.Feign; -import feign.Logger; -import feign.gson.GsonDecoder; -import feign.gson.GsonEncoder; -import feign.jaxrs.JAXRSContract; -import feign.okhttp.OkHttpClient; -import feign.slf4j.Slf4jLogger; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONArray; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.extension.siddhi.device.client.OAuthRequestInterceptor; -import org.wso2.extension.siddhi.device.client.configs.SiddhiExtensionConfigReader; -import org.wso2.extension.siddhi.device.client.dto.OperationRequest; -import org.wso2.extension.siddhi.device.client.services.OperationService; -import org.wso2.extension.siddhi.device.utils.ClientUtils; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.query.processor.stream.function.StreamFunctionProcessor; -import org.wso2.siddhi.query.api.definition.AbstractDefinition; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -public class AddOperationFunctionProcessor extends StreamFunctionProcessor { - - private static final Log log = LogFactory.getLog(AddOperationFunctionProcessor.class); - private static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss"; - private static final String DEVICE_MGT_BASE_CONTEXT = "/api/device-mgt/v1.0"; - private OperationService operationService; - - public AddOperationFunctionProcessor() { - operationService = Feign.builder().client(new OkHttpClient(ClientUtils.getSSLClient())) - .logger(new Slf4jLogger()) - .logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor()) - .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) - .target(OperationService.class, ClientUtils.replaceProperties( - SiddhiExtensionConfigReader.getInstance().getConfig().getGatewayEndpoint() + - DEVICE_MGT_BASE_CONTEXT)); - } - - /** - * The init method of the StreamProcessor, this method will be called before other methods - * - * @param abstractDefinition the incoming stream definition - * @param attributeExpressionExecutors the executors of each function parameters - * @param executionPlanContext the context of the execution plan - * @return the additional output attributes introduced by the function - */ - @Override - protected List init(AbstractDefinition abstractDefinition, - ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 6) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to device:addOperation() function, required 3 but found " + - attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument (deviceIdentifiers) of device:addOperation() " + - "function, required " + Attribute.Type.STRING + " as deviceIdentifiers, but found " + - attributeExpressionExecutors[0].getReturnType().toString()); - } - if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument (deviceType) of device:addOperation() " + - "function, required " + Attribute.Type.STRING + " as deviceType, but found " + - attributeExpressionExecutors[1].getReturnType().toString()); - } - if (attributeExpressionExecutors[2].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the third argument (code) of device:addOperation() " + - "function, required " + Attribute.Type.STRING + " as code, but found " + - attributeExpressionExecutors[2].getReturnType().toString()); - } - if (attributeExpressionExecutors[3].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the fourth argument (type) of device:addOperation() " + - "function, required " + Attribute.Type.STRING + " as type, but found " + - attributeExpressionExecutors[3].getReturnType().toString()); - } - if (attributeExpressionExecutors[4].getReturnType() != Attribute.Type.BOOL) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the fifth argument (isEnabled) of device:addOperation() " + - "function, required " + Attribute.Type.BOOL + " as isEnabled, but found " + - attributeExpressionExecutors[4].getReturnType().toString()); - } - if (attributeExpressionExecutors[5].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the fifth argument (payLoad) of device:addOperation() " + - "function, required " + Attribute.Type.STRING + " as payLoad, but found " + - attributeExpressionExecutors[5].getReturnType().toString()); - } - ArrayList attributes = new ArrayList<>(); - attributes.add(new Attribute("activity_id", Attribute.Type.STRING)); - return attributes; - } - - /** - * The process method of the StreamFunction, used when more than one function parameters are provided - * - * @param data the data values for the function parameters - * @return the data for additional output attributes introduced by the function - */ - @Override - protected Object[] process(Object[] data) { - if (data[0] == null || data[1] == null || data[2] == null || data[3] == null || data[4] == null || data[5] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:addOperation() function. " + - "Neither of any three arguments cannot be null"); - } - - JSONArray deviceIds = new JSONArray((String) data[0]); - String deviceType = (String) data[1]; - List deviceIdentifiers = new ArrayList<>(); - for (int i = 0; i < deviceIds.length(); i++) { - deviceIdentifiers.add(deviceIds.getString(i)); - } - - Operation operation = new Operation(); - operation.setType(Operation.Type.valueOf((String) data[3])); - operation.setStatus(Operation.Status.PENDING); - operation.setCode((String) data[2]); - operation.setEnabled((Boolean) data[4]); - String payloadString = (String) data[5]; - operation.setPayLoad(payloadString.replaceAll("'", "\"")); - - String date = new SimpleDateFormat(DATE_FORMAT_NOW).format(new Date()); - operation.setCreatedTimeStamp(date); - - OperationRequest operationRequest = new OperationRequest(); - operationRequest.setDeviceIdentifiers(deviceIdentifiers); - operationRequest.setOperation(operation); - try { - Activity activity = operationService.addOperation(deviceType, operationRequest); - return new Object[]{activity.getActivityId()}; - } catch (Exception e) { - log.error("Error occurred while adding the operation " + operation.toString(), e); - return new Object[]{null}; - } - } - - /** - * The process method of the StreamFunction, used when zero or one function parameter is provided - * - * @param data null if the function parameter count is zero or runtime data value of the function parameter - * @return the data for additional output attribute introduced by the function - */ - @Override - protected Object[] process(Object data) { - return new Object[0]; - } - - /** - * This will be called only once and this can be used to acquire - * required resources for the processing element. - * This will be called after initializing the system and before - * starting to process the events. - */ - @Override - public void start() { - - } - - /** - * This will be called only once and this can be used to release - * the acquired resources for processing. - * This will be called before shutting down the system. - */ - @Override - public void stop() { - - } - - /** - * Used to collect the serializable state of the processing element, that need to be - * persisted for the reconstructing the element to the same state on a different point of time - * - * @return stateful objects of the processing element as an array - */ - @Override - public Object[] currentState() { - return new Object[0]; - } - - /** - * Used to restore serialized state of the processing element, for reconstructing - * the element to the same state as if was on a previous point of time. - * - * @param objects the stateful objects of the element as an array on - * the same order provided by currentState(). - */ - @Override - public void restoreState(Object[] objects) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/GetDevicesOfStatusFunctionExecutor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/GetDevicesOfStatusFunctionExecutor.java deleted file mode 100644 index b5ba99410..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/GetDevicesOfStatusFunctionExecutor.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.device; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONArray; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.executor.function.FunctionExecutor; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -import java.util.List; - -/** - * getDevicesOfStatus(status [, deviceType]) - * Returns devices with specified status - * Accept Type(s): (STRING, STRING) - * Return Type(s): (STRING) - */ -public class GetDevicesOfStatusFunctionExecutor extends FunctionExecutor { - - private static Log log = LogFactory.getLog(GetDevicesOfStatusFunctionExecutor.class); - private Attribute.Type returnType = Attribute.Type.STRING; - - @Override - protected void init(ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 1 && attributeExpressionExecutors.length != 2) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to device:getDevicesOfStatus() function, required 2 but found " + - attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument (status) of device:getDevicesOfStatus() " + - "function, required " + Attribute.Type.STRING + " as status, but found " + - attributeExpressionExecutors[0].getReturnType().toString()); - } - if (attributeExpressionExecutors.length == 2 - && attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument (device type) of device:getDevicesOfStatus() " + - "function, required " + Attribute.Type.STRING + " as device type, but found " + - attributeExpressionExecutors[1].getReturnType().toString()); - } - } - - @Override - protected Object execute(Object[] data) { - if (data[0] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfStatus() function. " + - "First argument cannot be null"); - } - if (data.length == 2 && data[1] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfStatus() function. " + - "Second argument cannot be null"); - } - String status = (String) data[0]; - String deviceType = null; - if (data.length == 2) { - deviceType = (String) data[1]; - } - - JSONArray deviceIds = new JSONArray(); - try { - DeviceManagementProviderService deviceManagementProviderService = DeviceUtils.getDeviceManagementProviderService(); - List devices = deviceManagementProviderService.getDevicesByStatus(EnrolmentInfo.Status.valueOf(status), false); - for (Device device : devices) { - if (deviceType == null || deviceType.equalsIgnoreCase(device.getType())) { - deviceIds.put(device.getDeviceIdentifier()); - } - } - } catch (DeviceManagementException e) { - log.error("Error occurred while getting devices with status " + status, e); - } - return deviceIds.toString(); - } - - @Override - protected Object execute(Object data) { - return execute(new Object[]{data}); - } - - @Override - public void start() { - //Nothing to start - } - - @Override - public void stop() { - //Nothing to stop - } - - @Override - public Attribute.Type getReturnType() { - return returnType; - } - - @Override - public Object[] currentState() { - return null; //No need to maintain a state. - } - - @Override - public void restoreState(Object[] state) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/GetDevicesOfUserFunctionExecutor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/GetDevicesOfUserFunctionExecutor.java deleted file mode 100644 index 82c278b25..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/GetDevicesOfUserFunctionExecutor.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.device; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONArray; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.executor.function.FunctionExecutor; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -import java.util.List; - -/** - * getDevicesOfUser(user , deviceType [, status]) - * Returns list of ids of devices belongs to a user - * Accept Type(s): (STRING, STRING, STRING) - * Return Type(s): (STRING) - */ -public class GetDevicesOfUserFunctionExecutor extends FunctionExecutor { - - private static Log log = LogFactory.getLog(GetDevicesOfUserFunctionExecutor.class); - private Attribute.Type returnType = Attribute.Type.STRING; - - @Override - protected void init(ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 2 && attributeExpressionExecutors.length != 3) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to device:getDevicesOfUser() function, minimum 2, or 3 with " + - "optional. but found " + attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument (user) of device:getDevicesOfUser() " + - "function, required " + Attribute.Type.STRING + " as user, but found " + - attributeExpressionExecutors[0].getReturnType().toString()); - } - if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument (device type) of device:getDevicesOfUser() " + - "function, required " + Attribute.Type.STRING + " as device type, but found " + - attributeExpressionExecutors[1].getReturnType().toString()); - } - if (attributeExpressionExecutors.length == 3 - && attributeExpressionExecutors[2].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid optional parameter type found for the third argument (status) of " + - "device:getDevicesOfUser() function, required " + Attribute.Type.STRING + " as status, but found " + - attributeExpressionExecutors[2].getReturnType().toString()); - } - } - - @Override - protected Object execute(Object[] data) { - if (data[0] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " + - "First argument cannot be null"); - } - if (data[1] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " + - "Second argument cannot be null"); - } - if (data.length == 3 && data[2] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " + - "Third argument cannot be null"); - } - String user = (String) data[0]; - String deviceType = (String) data[1]; - String status = null; - if (data.length == 3) { - status = (String) data[2]; - } - - JSONArray deviceIds = new JSONArray(); - try { - DeviceManagementProviderService deviceManagementProviderService = DeviceUtils.getDeviceManagementProviderService(); - List devices = deviceManagementProviderService.getDevicesOfUser(user, deviceType, false); - for (Device device : devices) { - if (status == null || status.equalsIgnoreCase(device.getEnrolmentInfo().getStatus().toString())) { - deviceIds.put(device.getDeviceIdentifier()); - } - } - } catch (DeviceManagementException e) { - log.error("Error occurred while getting " + deviceType + " devices of user " + user + - ", with status " + status, e); - } - return deviceIds.toString(); - } - - @Override - protected Object execute(Object data) { - return null; //Since the getDevicesOfUser function takes in 2 or 3 parameters, this method does not get called. Hence,not implemented. - } - - @Override - public void start() { - //Nothing to start - } - - @Override - public void stop() { - //Nothing to stop - } - - @Override - public Attribute.Type getReturnType() { - return returnType; - } - - @Override - public Object[] currentState() { - return null; //No need to maintain a state. - } - - @Override - public void restoreState(Object[] state) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/HasDevicesOfStatusFunctionExecutor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/HasDevicesOfStatusFunctionExecutor.java deleted file mode 100644 index 8dda52f81..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/HasDevicesOfStatusFunctionExecutor.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.device; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.executor.function.FunctionExecutor; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -import java.util.List; - -/** - * hasDevicesOfStatus(status [, deviceType]) - * Returns true if there are devices with specified status - * Accept Type(s): (STRING, STRING) - * Return Type(s): (BOOL) - */ -public class HasDevicesOfStatusFunctionExecutor extends FunctionExecutor { - - private static Log log = LogFactory.getLog(HasDevicesOfStatusFunctionExecutor.class); - private Attribute.Type returnType = Attribute.Type.BOOL; - - @Override - protected void init(ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 1 && attributeExpressionExecutors.length != 2) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to device:hasDevicesOfStatus() function, required 2 but found " + - attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument (status) of device:hasDevicesOfStatus() " + - "function, required " + Attribute.Type.STRING + " as status, but found " + - attributeExpressionExecutors[0].getReturnType().toString()); - } - if (attributeExpressionExecutors.length == 2 - && attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument (device type) of device:hasDevicesOfStatus() " + - "function, required " + Attribute.Type.STRING + " as device type, but found " + - attributeExpressionExecutors[1].getReturnType().toString()); - } - } - - @Override - protected Object execute(Object[] data) { - if (data[0] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:hasDevicesOfStatus() function. " + - "First argument cannot be null"); - } - if (data.length == 2 && data[1] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:hasDevicesOfStatus() function. " + - "Second argument cannot be null"); - } - String status = (String) data[0]; - String deviceType = null; - if (data.length == 2) { - deviceType = (String) data[1]; - } - try { - DeviceManagementProviderService deviceManagementProviderService = DeviceUtils.getDeviceManagementProviderService(); - List devices = deviceManagementProviderService.getDevicesByStatus(EnrolmentInfo.Status.valueOf(status), false); - if (deviceType == null) { - return !devices.isEmpty(); - } else { - for (Device device : devices) { - if (deviceType.equalsIgnoreCase(device.getType())) { - return true; - } - } - return false; - } - } catch (DeviceManagementException e) { - log.error("Error occurred while getting devices with status " + status, e); - } - return false; - } - - @Override - protected Object execute(Object data) { - return execute(new Object[]{data}); - } - - @Override - public void start() { - //Nothing to start - } - - @Override - public void stop() { - //Nothing to stop - } - - @Override - public Attribute.Type getReturnType() { - return returnType; - } - - @Override - public Object[] currentState() { - return null; //No need to maintain a state. - } - - @Override - public void restoreState(Object[] state) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/HasDevicesOfUserFunctionExecutor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/HasDevicesOfUserFunctionExecutor.java deleted file mode 100644 index 94279dcd8..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/HasDevicesOfUserFunctionExecutor.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.device; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.executor.function.FunctionExecutor; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -import java.util.List; - -/** - * hasDevicesOfUser(user , deviceType [, status]) - * Returns true if there are devices belonging to user - * Accept Type(s): (STRING, STRING, STRING) - * Return Type(s): (BOOL) - */ -public class HasDevicesOfUserFunctionExecutor extends FunctionExecutor { - - private static Log log = LogFactory.getLog(HasDevicesOfUserFunctionExecutor.class); - private Attribute.Type returnType = Attribute.Type.BOOL; - - @Override - protected void init(ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 2 && attributeExpressionExecutors.length != 3) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to device:getDevicesOfUser() function, minimum 2, or 3 with " + - "optional. but found " + attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument (user) of device:getDevicesOfUser() " + - "function, required " + Attribute.Type.STRING + " as user, but found " + - attributeExpressionExecutors[0].getReturnType().toString()); - } - if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument (device type) of device:getDevicesOfUser() " + - "function, required " + Attribute.Type.STRING + " as device type, but found " + - attributeExpressionExecutors[1].getReturnType().toString()); - } - if (attributeExpressionExecutors.length == 3 - && attributeExpressionExecutors[2].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid optional parameter type found for the third argument (status) of " + - "device:getDevicesOfUser() function, required " + Attribute.Type.STRING + " as status, but found " + - attributeExpressionExecutors[2].getReturnType().toString()); - } - } - - @Override - protected Object execute(Object[] data) { - if (data[0] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " + - "First argument cannot be null"); - } - if (data[1] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " + - "Second argument cannot be null"); - } - if (data.length == 3 && data[2] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " + - "Third argument cannot be null"); - } - String user = (String) data[0]; - String deviceType = (String) data[1]; - String status = null; - if (data.length == 3) { - status = (String) data[2]; - } - - try { - DeviceManagementProviderService deviceManagementProviderService = DeviceUtils.getDeviceManagementProviderService(); - List devices = deviceManagementProviderService.getDevicesOfUser(user, deviceType, false); - if (status == null) { - return !devices.isEmpty(); - } else { - for (Device device : devices) { - if (status.equalsIgnoreCase(device.getEnrolmentInfo().getStatus().toString())) { - return true; - } - } - return false; - } - } catch (DeviceManagementException e) { - log.error("Error occurred while getting " + deviceType + " devices of user " + user + - ", with status " + status, e); - } - return false; - } - - @Override - protected Object execute(Object data) { - return null; //Since the getDevicesOfUser function takes in 2 or 3 parameters, this method does not get called. Hence,not implemented. - } - - @Override - public void start() { - //Nothing to start - } - - @Override - public void stop() { - //Nothing to stop - } - - @Override - public Attribute.Type getReturnType() { - return returnType; - } - - @Override - public Object[] currentState() { - return null; //No need to maintain a state. - } - - @Override - public void restoreState(Object[] state) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/IsEnrolledFunctionExecutor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/IsEnrolledFunctionExecutor.java deleted file mode 100644 index 1cc94d751..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/IsEnrolledFunctionExecutor.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.device; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.executor.function.FunctionExecutor; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -/** - * isEnrolled(deviceId, deviceType) - * Returns true if device enrolled. - * Accept Type(s): (STRING, STRING) - * Return Type(s): (BOOL) - */ -public class IsEnrolledFunctionExecutor extends FunctionExecutor { - - private static Log log = LogFactory.getLog(IsEnrolledFunctionExecutor.class); - private Attribute.Type returnType = Attribute.Type.BOOL; - - @Override - protected void init(ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 2) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to device:isEnrolled() function, required 2, but found " - + attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType()!= Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument (deviceId) of device:isEnrolled() " + - "function, required " + Attribute.Type.STRING + ", but found " + - attributeExpressionExecutors[0].getReturnType().toString()); - } - if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument (deviceType) of device:isEnrolled() " + - "function, required " + Attribute.Type.STRING + ", but found " + - attributeExpressionExecutors[1].getReturnType().toString()); - } - } - - @Override - protected Object execute(Object[] data) { - if (data[0] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:isEnrolled() function. " + - "First argument cannot be null"); - } - if (data[1] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:isEnrolled() function. " + - "Second argument cannot be null"); - } - - String deviceId = (String) data[0]; - String deviceType = (String) data[1]; - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); - try { - DeviceManagementProviderService deviceManagementService = DeviceUtils.getDeviceManagementProviderService(); - return deviceManagementService.isEnrolled(deviceIdentifier); - } catch (DeviceManagementException e) { - log.error("Error occurred while checking device is enrolled.", e); - } - return false; - } - - @Override - protected Object execute(Object data) { - return null; //Since the getDevicesOfUser function takes in 2 parameters, this method does not get called. Hence,not implemented. - } - - @Override - public void start() { - //Nothing to start - } - - @Override - public void stop() { - //Nothing to stop - } - - @Override - public Attribute.Type getReturnType() { - return returnType; - } - - @Override - public Object[] currentState() { - return null; //No need to maintain a state. - } - - @Override - public void restoreState(Object[] state) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/IsInGroupFunctionExecutor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/IsInGroupFunctionExecutor.java deleted file mode 100644 index 56b52ef95..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/IsInGroupFunctionExecutor.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.device; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; -import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.executor.function.FunctionExecutor; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - - -/** - * isInGroup(groupId, deviceId, deviceType) - * Returns true if device belongs to group, otherwise false. - * Accept Type(s): (INTEGER, STRING, STRING) - * Return Type(s): (BOOL) - */ -public class IsInGroupFunctionExecutor extends FunctionExecutor { - - private static Log log = LogFactory.getLog(IsInGroupFunctionExecutor.class); - private Attribute.Type returnType = Attribute.Type.BOOL; - - @Override - protected void init(ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 3) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to device:isInGroup() function, required 3, but found " - + attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType()!= Attribute.Type.INT) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument (group id) of device:isInGroup() " + - "function, required " + Attribute.Type.INT + ", but found " + - attributeExpressionExecutors[0].getReturnType().toString()); - } - if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument (device id) of device:isInGroup() " + - "function, required " + Attribute.Type.STRING + ", but found " + - attributeExpressionExecutors[1].getReturnType().toString()); - } - if (attributeExpressionExecutors[2].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the third argument (device type) of device:isInGroup() " + - "function, required " + Attribute.Type.STRING + ", but found " + - attributeExpressionExecutors[2].getReturnType().toString()); - } - } - - @Override - protected Object execute(Object[] data) { - if (data[0] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:isInGroup() function. " + - "First argument cannot be null"); - } - if (data[1] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:isInGroup() function. " + - "Second argument cannot be null"); - } - if (data[2] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to device:isInGroup() function. " + - "Third argument cannot be null"); - } - Integer groupId = (Integer) data[0]; - String deviceId = (String) data[1]; - String deviceType = (String) data[2]; - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType); - GroupManagementProviderService groupManagementService = DeviceUtils.getGroupManagementProviderService(); - try { - return groupManagementService.isDeviceMappedToGroup(groupId, deviceIdentifier); - } catch (GroupManagementException e) { - log.error("Error occurred while checking device is belonging to group.", e); - } - return false; - } - - @Override - protected Object execute(Object data) { - return null; //Since the isInGroup function takes in 3 parameters, this method does not get called. Hence,not implemented. - } - - @Override - public void start() { - //Nothing to start - } - - @Override - public void stop() { - //Nothing to stop - } - - @Override - public Attribute.Type getReturnType() { - return returnType; - } - - @Override - public Object[] currentState() { - return null; //No need to maintain a state. - } - - @Override - public void restoreState(Object[] state) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/OAuthRequestInterceptor.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/OAuthRequestInterceptor.java deleted file mode 100755 index 41f4bf690..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/OAuthRequestInterceptor.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client; - -import feign.Feign; -import feign.Logger; -import feign.RequestInterceptor; -import feign.RequestTemplate; -import feign.auth.BasicAuthRequestInterceptor; -import feign.gson.GsonDecoder; -import feign.gson.GsonEncoder; -import feign.jaxrs.JAXRSContract; -import feign.okhttp.OkHttpClient; -import feign.slf4j.Slf4jLogger; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.identity.jwt.client.extension.JWTClient; -import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; -import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.extension.siddhi.device.client.configs.SiddhiExtensionConfigReader; -import org.wso2.extension.siddhi.device.client.dto.OAuthApplication; -import org.wso2.extension.siddhi.device.client.dto.RegistrationProfile; -import org.wso2.extension.siddhi.device.client.exception.APIMClientOAuthException; -import org.wso2.extension.siddhi.device.client.services.DCRService; -import org.wso2.extension.siddhi.device.utils.ClientUtils; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; - -/** - * This is a request interceptor to add oauth token header. - */ -public class OAuthRequestInterceptor implements RequestInterceptor { - - private static final String APPLICATION_NAME = "siddhi_extension_client"; - private static final String REQUIRED_SCOPES = "perm:devices:operations"; - private static final String[] API_TAGS = {"device_management"}; - private DCRService dcrService; - private static OAuthApplication oAuthApplication; - private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class); - - /** - * Creates an interceptor that authenticates all requests. - */ - public OAuthRequestInterceptor() { - String username = SiddhiExtensionConfigReader.getInstance().getConfig().getUsername(); - String password = SiddhiExtensionConfigReader.getInstance().getConfig().getPassword(); - dcrService = Feign.builder().client(new OkHttpClient(ClientUtils.getSSLClient())).logger(new Slf4jLogger()) - .logLevel(Logger.Level.FULL) - .requestInterceptor(new BasicAuthRequestInterceptor(username, password)) - .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) - .target(DCRService.class, ClientUtils.replaceProperties( - SiddhiExtensionConfigReader.getInstance().getConfig().getDcrEndpoint())); - } - - @Override - public void apply(RequestTemplate template) { - if (oAuthApplication == null) { - RegistrationProfile registrationProfile = new RegistrationProfile(); - registrationProfile.setApiApplicationName(APPLICATION_NAME); - registrationProfile.setIsAllowedToAllDomains(true); - registrationProfile.setTags(API_TAGS); - oAuthApplication = dcrService.register(registrationProfile); - } - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - try { - String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName(); - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { - username = username + "@" + tenantDomain; - } - JWTClient jwtClient = DeviceUtils.getJWTClientManagerService().getJWTClient(); - AccessTokenInfo tenantBasedAccessTokenInfo = jwtClient.getAccessToken(oAuthApplication.getClientId(), - oAuthApplication.getClientSecret(), username, REQUIRED_SCOPES); - if (tenantBasedAccessTokenInfo.getAccessToken() != null) { - String headerValue = "Bearer " + tenantBasedAccessTokenInfo.getAccessToken(); - template.header("Authorization", headerValue); - } - } catch (JWTClientException e) { - String msg = "Failed to retrieve oauth token using jwt"; - log.error(msg, e); - throw new APIMClientOAuthException(msg, e); - } catch (UserStoreException e) { - String msg = "Unable to retrieve realm config for tenant " + tenantDomain; - log.error(msg, e); - throw new APIMClientOAuthException(msg, e); - } - } - -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/configs/SiddhiExtensionConfig.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/configs/SiddhiExtensionConfig.java deleted file mode 100644 index 0021ca690..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/configs/SiddhiExtensionConfig.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.configs; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This holds the configuration api manager integration. - */ -@XmlRootElement(name = "SiddhiExtensionConfiguration") -public class SiddhiExtensionConfig { - - String dcrEndpoint; - String gatewayEndpoint; - String username; - String password; - - @XmlElement(name = "DCREndpoint", required = true) - public String getDcrEndpoint() { - return dcrEndpoint; - } - - public void setDcrEndpoint(String dcrEndpoint) { - this.dcrEndpoint = dcrEndpoint; - } - - @XmlElement(name = "GatewayEndpoint", required = true) - public String getGatewayEndpoint() { - return gatewayEndpoint; - } - - public void setGatewayEndpoint(String gatewayEndpoint) { - this.gatewayEndpoint = gatewayEndpoint; - } - - @XmlElement(name = "Username", required = true) - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - @XmlElement(name = "Password", required = true) - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/configs/SiddhiExtensionConfigReader.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/configs/SiddhiExtensionConfigReader.java deleted file mode 100644 index 5a2211463..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/configs/SiddhiExtensionConfigReader.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.configs; - -import org.w3c.dom.Document; -import org.wso2.carbon.utils.CarbonUtils; -import org.wso2.extension.siddhi.device.client.exception.APIMClientException; -import org.wso2.extension.siddhi.device.client.exception.InvalidConfigurationStateException; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; - -/** - * This holds the configuration parser for api integration.xml - */ -public class SiddhiExtensionConfigReader { - - private static SiddhiExtensionConfig config; - private static SiddhiExtensionConfigReader configReader = new SiddhiExtensionConfigReader(); - private static boolean isInitialized = false; - private static final String SIDDHI_INTEGRATION_CONFIG_PATH = - CarbonUtils.getCarbonConfigDirPath() + File.separator + "siddhi-integration.xml"; - - private SiddhiExtensionConfigReader() { - - } - - private static String apimIntegrationXmlFilePath = ""; - - //TOD file may be a part of another file - public static SiddhiExtensionConfigReader getInstance() { - if (!isInitialized) { - try { - init(); - } catch (APIMClientException e) { - throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " + - "initialized properly"); - } - } - return configReader; - } - - public static void init() throws APIMClientException { - try { - File siddhiConfigFile = new File(SIDDHI_INTEGRATION_CONFIG_PATH); - Document doc = convertToDocument(siddhiConfigFile); - - JAXBContext ctx = JAXBContext.newInstance(SiddhiExtensionConfig.class); - Unmarshaller unmarshaller = ctx.createUnmarshaller(); - config = (SiddhiExtensionConfig) unmarshaller.unmarshal(doc); - isInitialized = true; - } catch (JAXBException e) { - throw new APIMClientException("Error occurred while un-marshalling SiddhiExtensionConfig", e); - } - } - - private static Document convertToDocument(File file) throws APIMClientException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - return docBuilder.parse(file); - } catch (Exception e) { - throw new APIMClientException("Error occurred while parsing file 'apim-integration.xml' to a org.w3c.dom.Document", e); - } - } - - public SiddhiExtensionConfig getConfig() { - return config; - } - -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/OAuthApplication.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/OAuthApplication.java deleted file mode 100644 index 46c72e9e3..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/OAuthApplication.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.dto; - -public class OAuthApplication { - - private String client_id; - private String client_secret; - - public String getClientId() { - return client_id; - } - - public void setClientId(String clientId) { - this.client_id = clientId; - } - - public String getClientSecret() { - return client_secret; - } - - public void setClientSecret(String clientSecret) { - this.client_secret = clientSecret; - } - - @Override - public String toString() { - return "OAuthApplication {\n" + - " clientId: " + client_id + "\n" + - " clientSecret: " + client_secret + "\n" + - "}\n"; - } - -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/OperationRequest.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/OperationRequest.java deleted file mode 100644 index bd3d919e3..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/OperationRequest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.dto; - -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; - -import java.util.List; - -public class OperationRequest { - - private List deviceIdentifiers; - private Operation operation; - - public List getDeviceIdentifiers() { - return deviceIdentifiers; - } - - public void setDeviceIdentifiers(List deviceIdentifiers) { - this.deviceIdentifiers = deviceIdentifiers; - } - - public Operation getOperation() { - return operation; - } - - public void setOperation(Operation operation) { - this.operation = operation; - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/RegistrationProfile.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/RegistrationProfile.java deleted file mode 100644 index ecb0086de..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/dto/RegistrationProfile.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.dto; - -/** - * DTO class to be used when registering an ApiM application. - */ - -public class RegistrationProfile { - - private String applicationName; - private String tags[]; - private boolean isAllowedToAllDomains; - private String validityPeriod; - - public String getApplicationName() { - return applicationName; - } - - public void setApiApplicationName(String apiApplicationName) { - this.applicationName = apiApplicationName; - } - - public String[] getTags() { - return tags; - } - - public void setTags(String[] tags) { - this.tags = tags; - } - - public boolean isAllowedToAllDomains() { - return isAllowedToAllDomains; - } - - public void setIsAllowedToAllDomains(boolean isAllowedToAllDomains) { - this.isAllowedToAllDomains = isAllowedToAllDomains; - } - - public String getValidityPeriod() { - return validityPeriod; - } - - public void setValidityPeriod(String validityPeriod) { - this.validityPeriod = validityPeriod; - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/APIMClientException.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/APIMClientException.java deleted file mode 100644 index 98f3c460b..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/APIMClientException.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.exception; - -/** - * This holds api client exception. - */ -public class APIMClientException extends Exception { - - private static final long serialVersionUID = -3976392476319079281L; - private String responseReason; - private int responseStatus; - private String methodKey; - - APIMClientException(String methodKey, String reason, int status) { - super("Exception occurred while invoking " + methodKey + " status = " + status + " reason = " + reason); - this.methodKey = methodKey; - this.responseReason = reason; - this.responseStatus = status; - } - - APIMClientException(String message) { - super(message); - } - - public APIMClientException(String message, Exception e) { - super(message, e); - } - - public String getResponseReason() { - return responseReason; - } - - public int getResponseStatus() { - return responseStatus; - } - - public String getMethodKey() { - return methodKey; - } - -} \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/APIMClientOAuthException.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/APIMClientOAuthException.java deleted file mode 100644 index 731fa3c25..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/APIMClientOAuthException.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.exception; - -/** - * This holds api client exception. - */ -public class APIMClientOAuthException extends RuntimeException { - - private static final long serialVersionUID = -3976392476319079281L; - private String responseReason; - private int responseStatus; - private String methodKey; - - APIMClientOAuthException(String methodKey, String reason, int status) { - super("Exception occurred while invoking " + methodKey + " status = " + status + " reason = " + reason); - this.methodKey = methodKey; - this.responseReason = reason; - this.responseStatus = status; - } - - public APIMClientOAuthException(String message) { - super(message); - } - - public APIMClientOAuthException(String message, Exception e) { - super(message, e); - } - - public String getResponseReason() { - return responseReason; - } - - public int getResponseStatus() { - return responseStatus; - } - - public String getMethodKey() { - return methodKey; - } - -} \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/InvalidConfigurationStateException.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/InvalidConfigurationStateException.java deleted file mode 100644 index 2656fd74b..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/exception/InvalidConfigurationStateException.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.exception; - -/** - * This error is thrown when there is an issue with the client. - */ -public class InvalidConfigurationStateException extends RuntimeException { - - private static final long serialVersionUID = -3151279311329070397L; - - private String errorMessage; - private int errorCode; - - public InvalidConfigurationStateException(int errorCode, String message) { - super(message); - this.errorCode = errorCode; - } - - public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) { - super(message, cause); - this.errorCode = errorCode; - } - - public int getErrorCode() { - return errorCode; - } - - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public InvalidConfigurationStateException(String msg, Exception nestedEx) { - super(msg, nestedEx); - setErrorMessage(msg); - } - - public InvalidConfigurationStateException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public InvalidConfigurationStateException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public InvalidConfigurationStateException() { - super(); - } - - public InvalidConfigurationStateException(Throwable cause) { - super(cause); - } - -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/services/OperationService.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/services/OperationService.java deleted file mode 100644 index 9df62e75a..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/services/OperationService.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2018, 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.extension.siddhi.device.client.services; - -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.extension.siddhi.device.client.dto.OperationRequest; - -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -/** - * Add Operation REST resource. - */ -@Path("/devices") -public interface OperationService { - - @POST - @Path("/{type}/operations") - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - Activity addOperation(@PathParam("type") String type, OperationRequest operationRequest); - -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/utils/ClientUtils.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/utils/ClientUtils.java deleted file mode 100644 index f51d9619a..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/utils/ClientUtils.java +++ /dev/null @@ -1,223 +0,0 @@ -/* -* Copyright (c) 2018, 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.extension.siddhi.device.utils; - -import okhttp3.OkHttpClient; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.ServerConfiguration; - -import javax.net.ssl.*; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.*; -import java.security.*; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ClientUtils { - - private static final Log log = LogFactory.getLog(ClientUtils.class); - - private static final String KEY_STORE_TYPE = "JKS"; - /** - * Default truststore type of the client - */ - private static final String TRUST_STORE_TYPE = "JKS"; - /** - * Default keymanager type of the client - */ - private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type - /** - * Default trustmanager type of the client - */ - private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type - - private static final String SSLV3 = "SSLv3"; - - private static final String DEFAULT_HOST = "localhost"; - - private static final String DEFAULT_HOST_IP = "127.0.0.1"; - - - //This method is only used if the mb features are within DAS. - public static String replaceProperties(String text) { - String regex = "\\$\\{(.*?)\\}"; - Pattern pattern = Pattern.compile(regex); - Matcher matchPattern = pattern.matcher(text); - while (matchPattern.find()) { - String sysPropertyName = matchPattern.group(1); - String sysPropertyValue = System.getProperty(sysPropertyName); - if (sysPropertyValue != null && !sysPropertyName.isEmpty()) { - text = text.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue); - } - } - return text; - } - - public static OkHttpClient getSSLClient() { - - boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.getProperty("org.wso2" - + ".ignoreHostnameVerification")); - OkHttpClient okHttpClient; - final String proxyHost = System.getProperty("http.proxyHost"); - final String proxyPort = System.getProperty("http.proxyPort"); - final String nonProxyHostsValue = System.getProperty("http.nonProxyHosts"); - - final ProxySelector proxySelector = new ProxySelector() { - @Override - public List select(URI uri) { - List proxyList = new ArrayList<>(); - String host = uri.getHost(); - - if (!StringUtils.isEmpty(host)) { - if (host.startsWith(DEFAULT_HOST_IP) || host.startsWith(DEFAULT_HOST) || StringUtils - .isEmpty(nonProxyHostsValue) || StringUtils.contains(nonProxyHostsValue, host) || - StringUtils.isEmpty(proxyHost) || StringUtils.isEmpty(proxyPort)) { - proxyList.add(Proxy.NO_PROXY); - } else { - proxyList.add(new Proxy(Proxy.Type.HTTP, - new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)))); - } - } else { - log.error("Host is null. Host could not be empty or null"); - } - return proxyList; - } - - @Override - public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { - throw new UnsupportedOperationException("Not supported yet."); - } - }; - - X509TrustManager trustAllCerts = new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[0]; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - }; - if(isIgnoreHostnameVerification) { - okHttpClient = new OkHttpClient.Builder() - .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts) - .hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify(String s, SSLSession sslSession) { - return true; - } - }).proxySelector(proxySelector).build(); - return okHttpClient; - }else { - SSLSocketFactory trustedSSLSocketFactory = getTrustedSSLSocketFactory(); - okHttpClient = new OkHttpClient.Builder().sslSocketFactory(trustedSSLSocketFactory) - .proxySelector(proxySelector).build(); - return okHttpClient; - } - } - - private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() { - try { - TrustManager[] trustAllCerts = new TrustManager[]{ - new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { - } - } - }; - SSLContext sc = SSLContext.getInstance("SSL"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - return sc.getSocketFactory(); - } catch (KeyManagementException | NoSuchAlgorithmException e) { - return null; - } - - } - - private static SSLSocketFactory getTrustedSSLSocketFactory() { - try { - String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); - String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location"); - String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty( - "Security.TrustStore.Password"); - String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty( - "Security.TrustStore.Location"); - KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,KEY_STORE_TYPE); - KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword); - - return initSSLConnection(keyStore,keyStorePassword,trustStore); - } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException - |CertificateException | IOException | UnrecoverableKeyException e) { - log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e); - return null; - } - - } - - private static SSLSocketFactory initSSLConnection(KeyStore keyStore,String keyStorePassword,KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException, - KeyStoreException, KeyManagementException { - KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE); - keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE); - trustManagerFactory.init(trustStore); - - // Create and initialize SSLContext for HTTPS communication - SSLContext sslContext = SSLContext.getInstance(SSLV3); - sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); - SSLContext.setDefault(sslContext); - return sslContext.getSocketFactory(); - } - - - private static KeyStore loadKeyStore(String keyStorePath, String ksPassword,String type) - throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - InputStream fileInputStream = null; - try { - char[] keypassChar = ksPassword.toCharArray(); - KeyStore keyStore = KeyStore.getInstance(type); - fileInputStream = new FileInputStream(keyStorePath); - keyStore.load(fileInputStream, keypassChar); - return keyStore; - } finally { - if (fileInputStream != null) { - fileInputStream.close(); - } - } - } - - private static KeyStore loadTrustStore(String trustStorePath, String tsPassword) - throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { - return loadKeyStore(trustStorePath,tsPassword,TRUST_STORE_TYPE); - } -} \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/utils/DeviceUtils.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/utils/DeviceUtils.java deleted file mode 100644 index b7109c8b1..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/utils/DeviceUtils.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.extension.siddhi.device.utils; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; - -/** - * This class holds utility methods to retrieve data. - */ -public class DeviceUtils { - - private static Log log = LogFactory.getLog(DeviceUtils.class); - private static DeviceManagementProviderService deviceManagementProviderService; - private static GroupManagementProviderService groupManagementProviderService; - private static NotificationManagementService notificationManagementService; - private static JWTClientManagerService jwtClientManagerService; - - private DeviceUtils(){ - } - - public static DeviceManagementProviderService getDeviceManagementProviderService() { - if (deviceManagementProviderService != null) { - return deviceManagementProviderService; - } - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - deviceManagementProviderService = - (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); - if (deviceManagementProviderService == null) { - String msg = "Device Management service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return deviceManagementProviderService; - } - - public static GroupManagementProviderService getGroupManagementProviderService() { - if (groupManagementProviderService != null) { - return groupManagementProviderService; - } - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - groupManagementProviderService = - (GroupManagementProviderService) ctx.getOSGiService(GroupManagementProviderService.class, null); - if (groupManagementProviderService == null) { - String msg = "Group Management service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return groupManagementProviderService; - } - - public static NotificationManagementService getNotificationManagementService() { - if (notificationManagementService != null) { - return notificationManagementService; - } - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - notificationManagementService = - (NotificationManagementService) ctx.getOSGiService(NotificationManagementService.class, null); - if (notificationManagementService == null) { - String msg = "Notification Management service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return notificationManagementService; - } - - public static JWTClientManagerService getJWTClientManagerService() { - if (jwtClientManagerService != null) { - return jwtClientManagerService; - } - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - jwtClientManagerService = - (JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null); - if (jwtClientManagerService == null) { - String msg = "JWTClient Manager service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - return jwtClientManagerService; - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/resources/device.siddhiext b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/resources/device.siddhiext deleted file mode 100644 index 8b9d47d9f..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/resources/device.siddhiext +++ /dev/null @@ -1,26 +0,0 @@ -# -# Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# WSO2 Inc. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -isInGroup=org.wso2.extension.siddhi.device.IsInGroupFunctionExecutor -getDevicesOfUser=org.wso2.extension.siddhi.device.GetDevicesOfUserFunctionExecutor -hasDevicesOfUser=org.wso2.extension.siddhi.device.HasDevicesOfUserFunctionExecutor -getDevicesOfStatus=org.wso2.extension.siddhi.device.GetDevicesOfStatusFunctionExecutor -hasDevicesOfStatus=org.wso2.extension.siddhi.device.HasDevicesOfStatusFunctionExecutor -isEnrolled=org.wso2.extension.siddhi.device.IsEnrolledFunctionExecutor -addNotification=org.wso2.extension.siddhi.device.AddNotificationFunctionProcessor -addOperation=org.wso2.extension.siddhi.device.AddOperationFunctionProcessor \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/BaseDeviceManagementTest.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/BaseDeviceManagementTest.java deleted file mode 100644 index 76b80c7ac..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/BaseDeviceManagementTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.extension.siddhi.device; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.tomcat.jdbc.pool.PoolProperties; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.w3c.dom.Document; -import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; -import org.wso2.extension.siddhi.device.test.util.DataSourceConfig; -import org.wso2.extension.siddhi.device.test.util.TestUtils; - -import javax.sql.DataSource; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import java.io.File; -import java.sql.Connection; -import java.sql.Statement; - -public abstract class BaseDeviceManagementTest { - - private DataSource dataSource; - private static final Log log = LogFactory.getLog(BaseDeviceManagementTest.class); - - @BeforeSuite - public void setupDataSource() throws Exception { - this.initDataSource(); - this.initSQLScript(); - this.initializeCarbonContext(); - } - - protected void initDataSource() throws Exception { - this.dataSource = this.getDataSource(this.readDataSourceConfig()); - DeviceManagementDAOFactory.init(dataSource); - GroupManagementDAOFactory.init(dataSource); - OperationManagementDAOFactory.init(dataSource); - NotificationManagementDAOFactory.init(dataSource); - } - - @BeforeClass - public abstract void init() throws Exception; - - private DataSource getDataSource(DataSourceConfig config) { - PoolProperties properties = new PoolProperties(); - properties.setUrl(config.getUrl()); - properties.setDriverClassName(config.getDriverClassName()); - properties.setUsername(config.getUser()); - properties.setPassword(config.getPassword()); - return new org.apache.tomcat.jdbc.pool.DataSource(properties); - } - - private void initializeCarbonContext() { - - if (System.getProperty("carbon.home") == null) { - File file = new File("src/test/resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("../resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("../../resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - file = new File("../../../resources/carbon-home"); - if (file.exists()) { - System.setProperty("carbon.home", file.getAbsolutePath()); - } - } - - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants - .SUPER_TENANT_DOMAIN_NAME); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); - } - - private DataSourceConfig readDataSourceConfig() throws DeviceManagementException { - try { - File file = new File("src/test/resources/config/datasource/data-source-config.xml"); - Document doc = DeviceManagerUtil.convertToDocument(file); - JAXBContext testDBContext = JAXBContext.newInstance(DataSourceConfig.class); - Unmarshaller unmarshaller = testDBContext.createUnmarshaller(); - return (DataSourceConfig) unmarshaller.unmarshal(doc); - } catch (JAXBException e) { - throw new DeviceManagementException("Error occurred while reading data source configuration", e); - } - } - - private void initSQLScript() throws Exception { - Connection conn = null; - Statement stmt = null; - try { - conn = this.getDataSource().getConnection(); - stmt = conn.createStatement(); - stmt.executeUpdate("RUNSCRIPT FROM './src/test/resources/sql/h2.sql'"); - } finally { - TestUtils.cleanupResources(conn, stmt, null); - } - } - - protected DataSource getDataSource() { - return dataSource; - } - -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/ExtensionTestCase.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/ExtensionTestCase.java deleted file mode 100644 index 202aee5ef..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/ExtensionTestCase.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.device; - -import org.apache.log4j.Logger; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; -import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; -import org.wso2.carbon.device.mgt.core.authorization.DeviceAccessAuthorizationServiceImpl; -import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; -import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration; -import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; -import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; -import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; -import org.wso2.carbon.registry.core.config.RegistryContext; -import org.wso2.carbon.registry.core.exceptions.RegistryException; -import org.wso2.carbon.registry.core.internal.RegistryDataHolder; -import org.wso2.carbon.registry.core.jdbc.realm.InMemoryRealmService; -import org.wso2.carbon.registry.core.service.RegistryService; -import org.wso2.carbon.user.core.UserStoreException; -import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.extension.siddhi.device.test.util.SiddhiTestHelper; -import org.wso2.extension.siddhi.device.test.util.TestDataHolder; -import org.wso2.extension.siddhi.device.test.util.TestDeviceManagementService; -import org.wso2.extension.siddhi.device.utils.DeviceUtils; -import org.wso2.siddhi.core.ExecutionPlanRuntime; -import org.wso2.siddhi.core.SiddhiManager; -import org.wso2.siddhi.core.event.Event; -import org.wso2.siddhi.core.query.output.callback.QueryCallback; -import org.wso2.siddhi.core.stream.input.InputHandler; -import org.wso2.siddhi.core.util.EventPrinter; - -import java.io.InputStream; -import java.lang.reflect.Field; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS; -import static org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE; - -public class ExtensionTestCase extends BaseDeviceManagementTest { - private static final Logger log = Logger.getLogger(ExtensionTestCase.class); - - private AtomicInteger count = new AtomicInteger(0); - private volatile boolean eventArrived; - private GroupManagementProviderService groupManagementProviderService; - private DeviceManagementProviderService deviceManagementProviderService; - private static String DEVICE_TYPE = "Test"; - - private QueryCallback queryCallback = new QueryCallback() { - @Override - public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { - EventPrinter.print(timeStamp, inEvents, removeEvents); - for (Event ignored : inEvents) { - count.incrementAndGet(); - eventArrived = true; - } - } - }; - - @BeforeClass - @Override - public void init() throws Exception { - log.info("Initializing"); - groupManagementProviderService = new GroupManagementProviderServiceImpl(); - deviceManagementProviderService = new DeviceManagementProviderServiceImpl(); - - DeviceManagementServiceComponent.notifyStartupListeners(); - DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProviderService); - DeviceManagementDataHolder.getInstance().setRegistryService(getRegistryService()); - DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(new DeviceAccessAuthorizationServiceImpl()); - DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(groupManagementProviderService); - DeviceManagementDataHolder.getInstance().setDeviceTaskManagerService(null); - deviceManagementProviderService.registerDeviceType( - new TestDeviceManagementService(DEVICE_TYPE, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); - - Field deviceManagementProviderServiceField = DeviceUtils.class.getDeclaredField("deviceManagementProviderService"); - deviceManagementProviderServiceField.setAccessible(true); - deviceManagementProviderServiceField.set(null, deviceManagementProviderService); - - Field groupManagementProviderServiceField = DeviceUtils.class.getDeclaredField("groupManagementProviderService"); - groupManagementProviderServiceField.setAccessible(true); - groupManagementProviderServiceField.set(null, groupManagementProviderService); - } - - private RegistryService getRegistryService() throws RegistryException, UserStoreException, - DeviceManagementException { - RealmService realmService = new InMemoryRealmService(); - RegistryDataHolder.getInstance().setRealmService(realmService); - DeviceManagementDataHolder.getInstance().setRealmService(realmService); - realmService.getTenantManager().getSuperTenantDomain(); - DeviceConfigurationManager.getInstance().initConfig(); - - InputStream is = this.getClass().getClassLoader().getResourceAsStream("carbon-home/repository/conf/registry.xml"); - RegistryContext context = RegistryContext.getBaseInstance(is, realmService); - context.setSetup(true); - return context.getEmbeddedRegistryService(); - } - - @Test - public void createGroup() throws GroupManagementException, GroupAlreadyExistException { - groupManagementProviderService.createGroup(TestDataHolder.generateDummyGroupData(1), - DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); - groupManagementProviderService.createGroup(TestDataHolder.generateDummyGroupData(2), - DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS); - } - - @Test - public void enrollDevice() { - Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE); - try { - boolean enrollmentStatus = deviceManagementProviderService.enrollDevice(device); - Assert.assertTrue(enrollmentStatus); - } catch (DeviceManagementException e) { - String msg = "Error Occurred while enrolling device"; - Assert.fail(msg, e); - } - } - - @Test(dependsOnMethods = {"createGroup", "enrollDevice"}) - public void addDevices() throws GroupManagementException, DeviceNotFoundException { - DeviceCacheConfiguration configuration = new DeviceCacheConfiguration(); - configuration.setEnabled(false); - - DeviceConfigurationManager.getInstance().getDeviceManagementConfig().setDeviceCacheConfiguration(configuration); - List list = TestDataHolder.getDeviceIdentifiersList(DEVICE_TYPE); - DeviceGroup deviceGroup = groupManagementProviderService.getGroup(TestDataHolder.generateDummyGroupData(1).getName(), false); - Assert.assertNotNull(deviceGroup); - groupManagementProviderService.addDevices(deviceGroup.getGroupId(), list); - } - - @Test(dependsOnMethods = {"addDevices"}) - public void testIsEnrolledExtension() throws InterruptedException, GroupManagementException { - log.info("IsEnrolled TestCase"); - SiddhiManager siddhiManager = new SiddhiManager(); - - count.set(0); - eventArrived = false; - - String inStreamDefinition = "define stream inputStream (deviceId string, deviceType string);"; - String query = ("@info(name = 'query1') from inputStream[device:isEnrolled(deviceId, deviceType)] " + - "select deviceId insert into outputStream;"); - ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); - executionPlanRuntime.addCallback("query1", queryCallback); - - InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); - executionPlanRuntime.start(); - DeviceIdentifier deviceIdentifier = TestDataHolder.getDeviceIdentifiersList(DEVICE_TYPE).get(0); - inputHandler.send(new Object[]{deviceIdentifier.getId(), deviceIdentifier.getType()}); - inputHandler.send(new Object[]{"99999", deviceIdentifier.getType()}); - SiddhiTestHelper.waitForEvents(100, 1, count, 10000); - Assert.assertTrue(eventArrived); - Assert.assertEquals(1, count.get()); - executionPlanRuntime.shutdown(); - } - - @Test(dependsOnMethods = {"testIsEnrolledExtension"}) - public void testIsInGroupExtension() throws InterruptedException, GroupManagementException { - log.info("IsInGroup TestCase"); - SiddhiManager siddhiManager = new SiddhiManager(); - - count.set(0); - eventArrived = false; - - String inStreamDefinition = "define stream inputStream (groupId int, deviceId string, deviceType string);"; - String query = ("@info(name = 'query1') from inputStream[device:isInGroup(groupId, deviceId, deviceType)] " + - "select deviceId insert into outputStream;"); - ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); - executionPlanRuntime.addCallback("query1", queryCallback); - - InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); - executionPlanRuntime.start(); - DeviceIdentifier deviceIdentifier = TestDataHolder.getDeviceIdentifiersList(DEVICE_TYPE).get(0); - inputHandler.send(new Object[]{groupManagementProviderService.getGroup( - TestDataHolder.generateDummyGroupData(1).getName(), false).getGroupId(), deviceIdentifier.getId(), deviceIdentifier.getType()}); - inputHandler.send(new Object[]{groupManagementProviderService.getGroup( - TestDataHolder.generateDummyGroupData(2).getName(), false).getGroupId(), deviceIdentifier.getId(), deviceIdentifier.getType()}); - SiddhiTestHelper.waitForEvents(100, 1, count, 10000); - Assert.assertTrue(eventArrived); - Assert.assertEquals(1, count.get()); - executionPlanRuntime.shutdown(); - } - - @Test(dependsOnMethods = {"testIsInGroupExtension"}) - public void testGetDevicesOfUserFunctionExecutor() throws InterruptedException, GroupManagementException { - log.info("GetDevicesOfUser without status TestCase"); - SiddhiManager siddhiManager = new SiddhiManager(); - - count.set(0); - eventArrived = false; - - String inStreamDefinition = "define stream inputStream (user string, deviceType string);"; - String query = ("@info(name = 'query1') from inputStream[device:hasDevicesOfUser(user, deviceType)] " + - "select device:getDevicesOfUser(user, deviceType) as devices insert into outputStream;"); - ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); - executionPlanRuntime.addCallback("query1", queryCallback); - - InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); - executionPlanRuntime.start(); - Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE); - inputHandler.send(new Object[]{device.getEnrolmentInfo().getOwner(), device.getType()}); - SiddhiTestHelper.waitForEvents(100, 1, count, 10000); - Assert.assertTrue(eventArrived); - Assert.assertEquals(1, count.get()); - executionPlanRuntime.shutdown(); - } - - @Test(dependsOnMethods = {"testGetDevicesOfUserFunctionExecutor"}) - public void testGetDevicesOfUserWithStatusFunctionExecutor() throws InterruptedException, GroupManagementException { - log.info("GetDevicesOfUser with status TestCase"); - SiddhiManager siddhiManager = new SiddhiManager(); - - count.set(0); - eventArrived = false; - - String inStreamDefinition = "define stream inputStream (user string, deviceType string, status string);"; - String query = ("@info(name = 'query1') from inputStream[device:hasDevicesOfUser(user, deviceType, status)] " + - "select device:getDevicesOfUser(user, deviceType, status) as devices insert into outputStream;"); - ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); - executionPlanRuntime.addCallback("query1", queryCallback); - - InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); - executionPlanRuntime.start(); - Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE); - inputHandler.send(new Object[]{device.getEnrolmentInfo().getOwner(), device.getType(), - device.getEnrolmentInfo().getStatus().toString()}); - SiddhiTestHelper.waitForEvents(100, 1, count, 10000); - Assert.assertTrue(eventArrived); - Assert.assertEquals(1, count.get()); - executionPlanRuntime.shutdown(); - } - - @Test(dependsOnMethods = {"testGetDevicesOfUserWithStatusFunctionExecutor"}) - public void testGetDevicesOfStatusFunctionExecutor() throws InterruptedException, GroupManagementException { - log.info("GetDevicesOfStatus without deviceType TestCase"); - SiddhiManager siddhiManager = new SiddhiManager(); - - count.set(0); - eventArrived = false; - - String inStreamDefinition = "define stream inputStream (status string);"; - String query = ("@info(name = 'query1') from inputStream[device:hasDevicesOfStatus(status)] " + - "select device:getDevicesOfStatus(status) as devices insert into outputStream;"); - ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); - executionPlanRuntime.addCallback("query1", queryCallback); - - InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); - executionPlanRuntime.start(); - Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE); - inputHandler.send(new Object[]{device.getEnrolmentInfo().getStatus().toString()}); - SiddhiTestHelper.waitForEvents(100, 1, count, 10000); - Assert.assertTrue(eventArrived); - Assert.assertEquals(1, count.get()); - executionPlanRuntime.shutdown(); - } - - @Test(dependsOnMethods = {"testGetDevicesOfStatusFunctionExecutor"}) - public void testGetDevicesOfStatusWithTypeFunctionExecutor() throws InterruptedException, GroupManagementException { - log.info("GetDevicesOfStatus with deviceType TestCase"); - SiddhiManager siddhiManager = new SiddhiManager(); - - count.set(0); - eventArrived = false; - - String inStreamDefinition = "define stream inputStream (status string, deviceType string);"; - String query = ("@info(name = 'query1') from inputStream[device:hasDevicesOfStatus(status, deviceType)] " + - "select device:getDevicesOfStatus(status, deviceType) as devices insert into outputStream;"); - ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); - executionPlanRuntime.addCallback("query1", queryCallback); - - InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); - executionPlanRuntime.start(); - Device device = TestDataHolder.generateDummyDeviceData(DEVICE_TYPE); - inputHandler.send(new Object[]{device.getEnrolmentInfo().getStatus().toString(), device.getType()}); - SiddhiTestHelper.waitForEvents(100, 1, count, 10000); - Assert.assertTrue(eventArrived); - Assert.assertEquals(1, count.get()); - executionPlanRuntime.shutdown(); - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/DataSourceConfig.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/DataSourceConfig.java deleted file mode 100644 index f787d9b22..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/DataSourceConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.extension.siddhi.device.test.util; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "DataSourceConfig") -public class DataSourceConfig { - - private String url; - private String driverClassName; - private String user; - private String password; - - @Override public String toString() { - return "DataSourceConfig[" + - " Url ='" + url + '\'' + - ", DriverClassName ='" + driverClassName + '\'' + - ", UserName ='" + user + '\'' + - ", Password ='" + password + '\'' + - "]"; - } - - @XmlElement(name = "Url", nillable = false) - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - @XmlElement(name = "DriverClassName", nillable = false) - public String getDriverClassName() { - return driverClassName; - } - - public void setDriverClassName(String driverClassName) { - this.driverClassName = driverClassName; - } - - @XmlElement(name = "User", nillable = false) - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - @XmlElement(name = "Password", nillable = false) - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/SiddhiTestHelper.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/SiddhiTestHelper.java deleted file mode 100644 index 820cbf154..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/SiddhiTestHelper.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.device.test.util; - -import java.util.concurrent.atomic.AtomicInteger; - -public class SiddhiTestHelper { - public static void waitForEvents(long sleepTime, int expectedCount, AtomicInteger actualCount, long timeout) - throws InterruptedException { - long currentWaitTime = 0; - long startTime = System.currentTimeMillis(); - while ((actualCount.get() < expectedCount) && (currentWaitTime <= timeout)) { - Thread.sleep(sleepTime); - currentWaitTime = System.currentTimeMillis() - startTime; - } - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDataHolder.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDataHolder.java deleted file mode 100644 index 6b482abcb..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDataHolder.java +++ /dev/null @@ -1,70 +0,0 @@ -/* -* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.wso2.extension.siddhi.device.test.util; - -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.app.mgt.Application; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Properties; - -public class TestDataHolder { - - public final static String initialDeviceIdentifier = "12345"; - public final static String OWNER = "admin"; - - public static Device generateDummyDeviceData(String deviceType) { - Device device = new Device(); - EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); - enrolmentInfo.setDateOfEnrolment(new Date().getTime()); - enrolmentInfo.setDateOfLastUpdate(new Date().getTime()); - enrolmentInfo.setOwner(OWNER); - enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD); - enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE); - device.setEnrolmentInfo(enrolmentInfo); - device.setDescription("Test Description"); - device.setDeviceIdentifier(initialDeviceIdentifier); - device.setType(deviceType); - return device; - } - - public static DeviceGroup generateDummyGroupData(int testId) { - DeviceGroup deviceGroup = new DeviceGroup(); - deviceGroup.setName("Test" + testId); - deviceGroup.setDescription("Test description " + testId); - deviceGroup.setOwner(OWNER); - return deviceGroup; - } - - public static List getDeviceIdentifiersList(String deviceType){ - Device device = generateDummyDeviceData(deviceType); - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(device.getDeviceIdentifier()); - identifier.setType(deviceType); - - List list = new ArrayList<>(); - list.add(identifier); - - return list; - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDeviceManagementService.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDeviceManagementService.java deleted file mode 100644 index 883cdf71f..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDeviceManagementService.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.extension.siddhi.device.test.util; - -import org.wso2.carbon.device.mgt.common.DeviceManager; -import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; -import org.wso2.carbon.device.mgt.common.InitialOperationConfig; -import org.wso2.carbon.device.mgt.common.MonitoringOperation; -import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; -import org.wso2.carbon.device.mgt.common.ProvisioningConfig; -import org.wso2.carbon.device.mgt.common.StartupOperationConfig; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.general.GeneralConfig; -import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; -import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; -import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; -import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; -import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypePlatformDetails; - -import java.util.ArrayList; -import java.util.List; - -public class TestDeviceManagementService implements DeviceManagementService { - - private String providerType; - private String tenantDomain; - - public TestDeviceManagementService(String deviceType, String tenantDomain) { - providerType = deviceType; - this.tenantDomain = tenantDomain; - } - - @Override - public String getType() { - return providerType; - } - - @Override - public OperationMonitoringTaskConfig getOperationMonitoringConfig() { - OperationMonitoringTaskConfig taskConfig = new OperationMonitoringTaskConfig(); - taskConfig.setEnabled(true); - taskConfig.setFrequency(3000); - List monitoringOperations = new ArrayList<>(); - for (int i = 0; i < 5; i++) { - MonitoringOperation monitoringOperation = new MonitoringOperation(); - monitoringOperation.setTaskName("OPERATION-" + i); - monitoringOperation.setRecurrentTimes(i); - monitoringOperations.add(monitoringOperation); - } - taskConfig.setMonitoringOperation(monitoringOperations); - return taskConfig; - } - - @Override - public void init() throws DeviceManagementException { - - } - - @Override - public DeviceManager getDeviceManager() { - return new TestDeviceManager(); - } - - @Override - public ApplicationManager getApplicationManager() { - return null; - } - - @Override - public ProvisioningConfig getProvisioningConfig() { - return new ProvisioningConfig(tenantDomain, false); - } - - @Override - public PushNotificationConfig getPushNotificationConfig() { - return null; - } - - @Override - public PolicyMonitoringManager getPolicyMonitoringManager() { - return null; - } - - @Override - public InitialOperationConfig getInitialOperationConfig() { - return null; - } - - @Override - public StartupOperationConfig getStartupOperationConfig() { - return null; - } - - @Override - public PullNotificationSubscriber getPullNotificationSubscriber() { - return null; - } - - @Override - public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig() { - return null; - } - - @Override - public GeneralConfig getGeneralConfig() { - return null; - } - - @Override - public DeviceTypePlatformDetails getDeviceTypePlatformDetails() { return null; } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDeviceManager.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDeviceManager.java deleted file mode 100644 index 58ecf84e0..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestDeviceManager.java +++ /dev/null @@ -1,146 +0,0 @@ -/* -* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package org.wso2.extension.siddhi.device.test.util; - -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManager; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.FeatureManager; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.license.mgt.License; -import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; -import org.wso2.carbon.device.mgt.common.ui.policy.mgt.PolicyConfigurationManager; - -import java.util.List; - -public class TestDeviceManager implements DeviceManager { - - public TestDeviceManager() { - - } - - @Override - public FeatureManager getFeatureManager() { - return null; - } - - @Override - public PolicyConfigurationManager getPolicyUIConfigurationManager() { - return null; - } - - @Override - public boolean saveConfiguration(PlatformConfiguration configuration) - throws DeviceManagementException { - return false; - } - - @Override public PlatformConfiguration getConfiguration() throws DeviceManagementException { - return null; - } - - @Override - public boolean enrollDevice(Device device) throws DeviceManagementException { - return true; - } - - @Override - public boolean modifyEnrollment(Device device) throws DeviceManagementException { - return true; - } - - @Override - public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException { - return true; - } - - - @Override - public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { - return true; - } - - @Override - public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException { - return true; - } - - @Override - public boolean setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException { - return false; - } - - @Override - public List getAllDevices() throws DeviceManagementException { - return null; - } - - @Override - public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { - return null; - } - - @Override - public boolean updateDeviceProperties(DeviceIdentifier deviceIdentifier, List list) throws DeviceManagementException { - return false; - } - - @Override - public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) - throws DeviceManagementException { - return false; - } - - @Override - public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) - throws DeviceManagementException { - return false; - } - - @Override - public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException { - return false; - } - - @Override - public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, EnrolmentInfo.Status status) - throws DeviceManagementException { - return false; - } - - @Override - public License getLicense(String languageCode) throws LicenseManagementException { - return null; - } - - @Override - public void addLicense(License license) throws LicenseManagementException { - - } - - @Override - public boolean requireDeviceAuthorization() { - return false; - } - - @Override - public void deleteDevices(List deviceIdentifiers) throws DeviceManagementException { - //Does nothing since AndroidDeviceManager is not used instead DeviceTypeManager is used. - } - -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestUtils.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestUtils.java deleted file mode 100644 index 673b2b521..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/java/org/wso2/extension/siddhi/device/test/util/TestUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2014, 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.extension.siddhi.device.test.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -public class TestUtils { - - private static final Log log = LogFactory.getLog(TestUtils.class); - - public static void cleanupResources(Connection conn, Statement stmt, ResultSet rs) { - if (rs != null) { - try { - rs.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing result set", e); - } - } - if (stmt != null) { - try { - stmt.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing prepared statement", e); - } - } - if (conn != null) { - try { - conn.close(); - } catch (SQLException e) { - log.warn("Error occurred while closing database connection", e); - } - } - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/dbscripts/h2.sql b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/dbscripts/h2.sql deleted file mode 100644 index f6b31c78d..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/dbscripts/h2.sql +++ /dev/null @@ -1,429 +0,0 @@ -CREATE TABLE IF NOT EXISTS REG_CLUSTER_LOCK ( - REG_LOCK_NAME VARCHAR (20), - REG_LOCK_STATUS VARCHAR (20), - REG_LOCKED_TIME TIMESTAMP, - REG_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (REG_LOCK_NAME) -); - -CREATE TABLE IF NOT EXISTS REG_LOG ( - REG_LOG_ID INTEGER AUTO_INCREMENT, - REG_PATH VARCHAR (2000), - REG_USER_ID VARCHAR (31) NOT NULL, - REG_LOGGED_TIME TIMESTAMP NOT NULL, - REG_ACTION INTEGER NOT NULL, - REG_ACTION_DATA VARCHAR (500), - REG_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (REG_LOG_ID, REG_TENANT_ID) -); - -CREATE INDEX IF NOT EXISTS REG_LOG_IND_BY_REG_LOGTIME ON REG_LOG(REG_LOGGED_TIME, REG_TENANT_ID); - -CREATE TABLE IF NOT EXISTS REG_PATH( - REG_PATH_ID INTEGER NOT NULL AUTO_INCREMENT, - REG_PATH_VALUE VARCHAR(2000) NOT NULL, - REG_PATH_PARENT_ID INT, - REG_TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT PK_REG_PATH PRIMARY KEY(REG_PATH_ID, REG_TENANT_ID) -); -CREATE INDEX IF NOT EXISTS REG_PATH_IND_BY_NAME ON REG_PATH(REG_PATH_VALUE, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_PATH_IND_BY_PARENT_ID ON REG_PATH(REG_PATH_PARENT_ID, REG_TENANT_ID); - - -CREATE TABLE IF NOT EXISTS REG_CONTENT ( - REG_CONTENT_ID INTEGER NOT NULL AUTO_INCREMENT, - REG_CONTENT_DATA LONGBLOB, - REG_TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT PK_REG_CONTENT PRIMARY KEY(REG_CONTENT_ID, REG_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS REG_CONTENT_HISTORY ( - REG_CONTENT_ID INTEGER NOT NULL, - REG_CONTENT_DATA LONGBLOB, - REG_DELETED SMALLINT, - REG_TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT PK_REG_CONTENT_HISTORY PRIMARY KEY(REG_CONTENT_ID, REG_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS REG_RESOURCE ( - REG_PATH_ID INTEGER NOT NULL, - REG_NAME VARCHAR(256), - REG_VERSION INTEGER NOT NULL AUTO_INCREMENT, - REG_MEDIA_TYPE VARCHAR(500), - REG_CREATOR VARCHAR(31) NOT NULL, - REG_CREATED_TIME TIMESTAMP NOT NULL, - REG_LAST_UPDATOR VARCHAR(31), - REG_LAST_UPDATED_TIME TIMESTAMP NOT NULL, - REG_DESCRIPTION VARCHAR(1000), - REG_CONTENT_ID INTEGER, - REG_TENANT_ID INTEGER DEFAULT 0, - REG_UUID VARCHAR(100) NOT NULL, - CONSTRAINT PK_REG_RESOURCE PRIMARY KEY(REG_VERSION, REG_TENANT_ID) -); - -ALTER TABLE REG_RESOURCE ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); -ALTER TABLE REG_RESOURCE ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_FK_BY_CONTENT_ID FOREIGN KEY (REG_CONTENT_ID, REG_TENANT_ID) REFERENCES REG_CONTENT (REG_CONTENT_ID, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_NAME ON REG_RESOURCE(REG_NAME, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_PATH_ID_NAME ON REG_RESOURCE(REG_PATH_ID, REG_NAME, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_UUID ON REG_RESOURCE(REG_UUID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_TENANT ON REG_RESOURCE(REG_TENANT_ID, REG_UUID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_IND_BY_TYPE ON REG_RESOURCE(REG_TENANT_ID, REG_MEDIA_TYPE); - -CREATE TABLE IF NOT EXISTS REG_RESOURCE_HISTORY ( - REG_PATH_ID INTEGER NOT NULL, - REG_NAME VARCHAR(256), - REG_VERSION INTEGER NOT NULL, - REG_MEDIA_TYPE VARCHAR(500), - REG_CREATOR VARCHAR(31) NOT NULL, - REG_CREATED_TIME TIMESTAMP NOT NULL, - REG_LAST_UPDATOR VARCHAR(31), - REG_LAST_UPDATED_TIME TIMESTAMP NOT NULL, - REG_DESCRIPTION VARCHAR(1000), - REG_CONTENT_ID INTEGER, - REG_DELETED SMALLINT, - REG_TENANT_ID INTEGER DEFAULT 0, - REG_UUID VARCHAR(100) NOT NULL, - CONSTRAINT PK_REG_RESOURCE_HISTORY PRIMARY KEY(REG_VERSION, REG_TENANT_ID) -); - -ALTER TABLE REG_RESOURCE_HISTORY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_HIST_FK_BY_PATHID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); -ALTER TABLE REG_RESOURCE_HISTORY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_HIST_FK_BY_CONTENT_ID FOREIGN KEY (REG_CONTENT_ID, REG_TENANT_ID) REFERENCES REG_CONTENT_HISTORY (REG_CONTENT_ID, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_HISTORY_IND_BY_NAME ON REG_RESOURCE_HISTORY(REG_NAME, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_HISTORY_IND_BY_PATH_ID_NAME ON REG_RESOURCE(REG_PATH_ID, REG_NAME, REG_TENANT_ID); - -CREATE TABLE IF NOT EXISTS REG_COMMENT ( - REG_ID INTEGER NOT NULL AUTO_INCREMENT, - REG_COMMENT_TEXT VARCHAR(500) NOT NULL, - REG_USER_ID VARCHAR(31) NOT NULL, - REG_COMMENTED_TIME TIMESTAMP NOT NULL, - REG_TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT PK_REG_COMMENT PRIMARY KEY(REG_ID, REG_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS REG_RESOURCE_COMMENT ( - REG_COMMENT_ID INTEGER NOT NULL, - REG_VERSION INTEGER, - REG_PATH_ID INTEGER, - REG_RESOURCE_NAME VARCHAR(256), - REG_TENANT_ID INTEGER DEFAULT 0 -); - -ALTER TABLE REG_RESOURCE_COMMENT ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_COMMENT_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); -ALTER TABLE REG_RESOURCE_COMMENT ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_COMMENT_FK_BY_COMMENT_ID FOREIGN KEY (REG_COMMENT_ID, REG_TENANT_ID) REFERENCES REG_COMMENT (REG_ID, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_COMMENT_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_COMMENT(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_COMMENT_IND_BY_VERSION ON REG_RESOURCE_COMMENT(REG_VERSION, REG_TENANT_ID); - -CREATE TABLE IF NOT EXISTS REG_RATING ( - REG_ID INTEGER NOT NULL AUTO_INCREMENT, - REG_RATING INTEGER NOT NULL, - REG_USER_ID VARCHAR(31) NOT NULL, - REG_RATED_TIME TIMESTAMP NOT NULL, - REG_TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT PK_REG_RATING PRIMARY KEY(REG_ID, REG_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS REG_RESOURCE_RATING ( - REG_RATING_ID INTEGER NOT NULL, - REG_VERSION INTEGER, - REG_PATH_ID INTEGER, - REG_RESOURCE_NAME VARCHAR(256), - REG_TENANT_ID INTEGER DEFAULT 0 -); - -ALTER TABLE REG_RESOURCE_RATING ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_RATING_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); -ALTER TABLE REG_RESOURCE_RATING ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_RATING_FK_BY_RATING_ID FOREIGN KEY (REG_RATING_ID, REG_TENANT_ID) REFERENCES REG_RATING (REG_ID, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_RATING_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_RATING(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_RATING_IND_BY_VERSION ON REG_RESOURCE_RATING(REG_VERSION, REG_TENANT_ID); - - -CREATE TABLE IF NOT EXISTS REG_TAG ( - REG_ID INTEGER NOT NULL AUTO_INCREMENT, - REG_TAG_NAME VARCHAR(500) NOT NULL, - REG_USER_ID VARCHAR(31) NOT NULL, - REG_TAGGED_TIME TIMESTAMP NOT NULL, - REG_TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT PK_REG_TAG PRIMARY KEY(REG_ID, REG_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS REG_RESOURCE_TAG ( - REG_TAG_ID INTEGER NOT NULL, - REG_VERSION INTEGER, - REG_PATH_ID INTEGER, - REG_RESOURCE_NAME VARCHAR(256), - REG_TENANT_ID INTEGER DEFAULT 0 -); - -ALTER TABLE REG_RESOURCE_TAG ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_TAG_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); -ALTER TABLE REG_RESOURCE_TAG ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_TAG_FK_BY_TAG_ID FOREIGN KEY (REG_TAG_ID, REG_TENANT_ID) REFERENCES REG_TAG (REG_ID, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_TAG_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_TAG(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_TAG_IND_BY_VERSION ON REG_RESOURCE_TAG(REG_VERSION, REG_TENANT_ID); - -CREATE TABLE IF NOT EXISTS REG_PROPERTY ( - REG_ID INTEGER NOT NULL AUTO_INCREMENT, - REG_NAME VARCHAR(100) NOT NULL, - REG_VALUE VARCHAR(1000), - REG_TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT PK_REG_PROPERTY PRIMARY KEY(REG_ID, REG_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS REG_RESOURCE_PROPERTY ( - REG_PROPERTY_ID INTEGER NOT NULL, - REG_VERSION INTEGER, - REG_PATH_ID INTEGER, - REG_RESOURCE_NAME VARCHAR(256), - REG_TENANT_ID INTEGER DEFAULT 0 -); - -ALTER TABLE REG_RESOURCE_PROPERTY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_PROPERTY_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); -ALTER TABLE REG_RESOURCE_PROPERTY ADD CONSTRAINT IF NOT EXISTS REG_RESOURCE_PROPERTY_FK_BY_TAG_ID FOREIGN KEY (REG_PROPERTY_ID, REG_TENANT_ID) REFERENCES REG_PROPERTY (REG_ID, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_PROPERTY_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_RESOURCE_PROPERTY(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_RESOURCE_PROPERTY_IND_BY_VERSION ON REG_RESOURCE_PROPERTY(REG_VERSION, REG_TENANT_ID); - -CREATE TABLE IF NOT EXISTS REG_ASSOCIATION ( - REG_ASSOCIATION_ID INTEGER AUTO_INCREMENT, - REG_SOURCEPATH VARCHAR (2000) NOT NULL, - REG_TARGETPATH VARCHAR (2000) NOT NULL, - REG_ASSOCIATION_TYPE VARCHAR (2000) NOT NULL, - REG_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (REG_ASSOCIATION_ID, REG_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS REG_SNAPSHOT ( - REG_SNAPSHOT_ID INTEGER NOT NULL AUTO_INCREMENT, - REG_PATH_ID INTEGER NOT NULL, - REG_RESOURCE_NAME VARCHAR (256), - REG_RESOURCE_VIDS LONGBLOB NOT NULL, - REG_TENANT_ID INTEGER DEFAULT 0, - CONSTRAINT PK_REG_SNAPSHOT PRIMARY KEY(REG_SNAPSHOT_ID, REG_TENANT_ID) -); - -ALTER TABLE REG_SNAPSHOT ADD CONSTRAINT IF NOT EXISTS REG_SNAPSHOT_FK_BY_PATH_ID FOREIGN KEY (REG_PATH_ID, REG_TENANT_ID) REFERENCES REG_PATH (REG_PATH_ID, REG_TENANT_ID); -CREATE INDEX IF NOT EXISTS REG_SNAPSHOT_IND_BY_PATH_ID_AND_RESOURCE_NAME ON REG_SNAPSHOT(REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID); - --- ################################ --- USER MANAGER TABLES --- ################################ - -CREATE TABLE IF NOT EXISTS UM_TENANT ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_DOMAIN_NAME VARCHAR(255) NOT NULL, - UM_EMAIL VARCHAR(255), - UM_ACTIVE BOOLEAN DEFAULT FALSE, - UM_CREATED_DATE TIMESTAMP NOT NULL, - UM_USER_CONFIG LONGBLOB NOT NULL, - PRIMARY KEY (UM_ID), - UNIQUE(UM_DOMAIN_NAME)); - -CREATE TABLE IF NOT EXISTS UM_DOMAIN( - UM_DOMAIN_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_DOMAIN_NAME VARCHAR(255), - UM_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (UM_DOMAIN_ID, UM_TENANT_ID) -); - -CREATE INDEX IF NOT EXISTS INDEX_UM_TENANT_UM_DOMAIN_NAME ON UM_TENANT (UM_DOMAIN_NAME); - -CREATE TABLE IF NOT EXISTS UM_USER ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_USER_NAME VARCHAR(255) NOT NULL, - UM_USER_PASSWORD VARCHAR(255) NOT NULL, - UM_SALT_VALUE VARCHAR(31), - UM_REQUIRE_CHANGE BOOLEAN DEFAULT FALSE, - UM_CHANGED_TIME TIMESTAMP NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (UM_ID, UM_TENANT_ID), - UNIQUE(UM_USER_NAME, UM_TENANT_ID)); - -CREATE TABLE IF NOT EXISTS UM_SYSTEM_USER ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_USER_NAME VARCHAR(255) NOT NULL, - UM_USER_PASSWORD VARCHAR(255) NOT NULL, - UM_SALT_VALUE VARCHAR(31), - UM_REQUIRE_CHANGE BOOLEAN DEFAULT FALSE, - UM_CHANGED_TIME TIMESTAMP NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (UM_ID, UM_TENANT_ID), - UNIQUE(UM_USER_NAME, UM_TENANT_ID)); - -CREATE TABLE IF NOT EXISTS UM_USER_ATTRIBUTE ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_ATTR_NAME VARCHAR(255) NOT NULL, - UM_ATTR_VALUE VARCHAR(1024), - UM_PROFILE_ID VARCHAR(255), - UM_USER_ID INTEGER, - UM_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (UM_ID, UM_TENANT_ID), - FOREIGN KEY (UM_USER_ID, UM_TENANT_ID) REFERENCES UM_USER(UM_ID, UM_TENANT_ID)); - -CREATE INDEX IF NOT EXISTS UM_USER_ID_INDEX ON UM_USER_ATTRIBUTE(UM_USER_ID); - -CREATE TABLE IF NOT EXISTS UM_ROLE ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_ROLE_NAME VARCHAR(255) NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - UM_SHARED_ROLE BOOLEAN DEFAULT FALSE, - PRIMARY KEY (UM_ID, UM_TENANT_ID), - UNIQUE(UM_ROLE_NAME, UM_TENANT_ID)); - -CREATE TABLE IF NOT EXISTS UM_MODULE( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_MODULE_NAME VARCHAR(100), - UNIQUE(UM_MODULE_NAME), - PRIMARY KEY(UM_ID) -); - -CREATE TABLE IF NOT EXISTS UM_MODULE_ACTIONS( - UM_ACTION VARCHAR(255) NOT NULL, - UM_MODULE_ID INTEGER NOT NULL, - PRIMARY KEY(UM_ACTION, UM_MODULE_ID), - FOREIGN KEY (UM_MODULE_ID) REFERENCES UM_MODULE(UM_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS UM_PERMISSION ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_RESOURCE_ID VARCHAR(255) NOT NULL, - UM_ACTION VARCHAR(255) NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - UM_MODULE_ID INTEGER DEFAULT 0, - UNIQUE(UM_RESOURCE_ID,UM_ACTION, UM_TENANT_ID), - PRIMARY KEY (UM_ID, UM_TENANT_ID)); - -CREATE INDEX IF NOT EXISTS INDEX_UM_PERMISSION_UM_RESOURCE_ID_UM_ACTION ON UM_PERMISSION (UM_RESOURCE_ID, UM_ACTION, UM_TENANT_ID); - -CREATE TABLE IF NOT EXISTS UM_ROLE_PERMISSION ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_PERMISSION_ID INTEGER NOT NULL, - UM_ROLE_NAME VARCHAR(255) NOT NULL, - UM_IS_ALLOWED SMALLINT NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - UM_DOMAIN_ID INTEGER, - FOREIGN KEY (UM_PERMISSION_ID, UM_TENANT_ID) REFERENCES UM_PERMISSION(UM_ID, UM_TENANT_ID) ON DELETE CASCADE, - FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE, - PRIMARY KEY (UM_ID, UM_TENANT_ID)); - -CREATE TABLE IF NOT EXISTS UM_USER_PERMISSION ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_PERMISSION_ID INTEGER NOT NULL, - UM_USER_NAME VARCHAR(255) NOT NULL, - UM_IS_ALLOWED SMALLINT NOT NULL, - UNIQUE (UM_PERMISSION_ID, UM_USER_NAME, UM_TENANT_ID), - UM_TENANT_ID INTEGER DEFAULT 0, - FOREIGN KEY (UM_PERMISSION_ID, UM_TENANT_ID) REFERENCES UM_PERMISSION(UM_ID, UM_TENANT_ID) ON DELETE CASCADE, - PRIMARY KEY (UM_ID, UM_TENANT_ID)); - -CREATE TABLE IF NOT EXISTS UM_USER_ROLE ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_ROLE_ID INTEGER NOT NULL, - UM_USER_ID INTEGER NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - UNIQUE (UM_USER_ID, UM_ROLE_ID, UM_TENANT_ID), - FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_ROLE(UM_ID, UM_TENANT_ID), - FOREIGN KEY (UM_USER_ID, UM_TENANT_ID) REFERENCES UM_USER(UM_ID, UM_TENANT_ID), - PRIMARY KEY (UM_ID, UM_TENANT_ID)); - - -CREATE TABLE IF NOT EXISTS UM_SHARED_USER_ROLE( - UM_ROLE_ID INTEGER NOT NULL, - UM_USER_ID INTEGER NOT NULL, - UM_USER_TENANT_ID INTEGER NOT NULL, - UM_ROLE_TENANT_ID INTEGER NOT NULL, - UNIQUE(UM_USER_ID,UM_ROLE_ID,UM_USER_TENANT_ID, UM_ROLE_TENANT_ID), - FOREIGN KEY(UM_ROLE_ID,UM_ROLE_TENANT_ID) REFERENCES UM_ROLE(UM_ID,UM_TENANT_ID) ON DELETE CASCADE , - FOREIGN KEY(UM_USER_ID,UM_USER_TENANT_ID) REFERENCES UM_USER(UM_ID,UM_TENANT_ID) ON DELETE CASCADE -); - -CREATE TABLE IF NOT EXISTS UM_ACCOUNT_MAPPING( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_USER_NAME VARCHAR(255) NOT NULL, - UM_TENANT_ID INTEGER NOT NULL, - UM_USER_STORE_DOMAIN VARCHAR(100), - UM_ACC_LINK_ID INTEGER NOT NULL, - UNIQUE(UM_USER_NAME, UM_TENANT_ID, UM_USER_STORE_DOMAIN, UM_ACC_LINK_ID), - FOREIGN KEY (UM_TENANT_ID) REFERENCES UM_TENANT(UM_ID) ON DELETE CASCADE, - PRIMARY KEY (UM_ID) -); - - -CREATE TABLE IF NOT EXISTS UM_DIALECT( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_DIALECT_URI VARCHAR(255) NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - UNIQUE(UM_DIALECT_URI, UM_TENANT_ID), - PRIMARY KEY (UM_ID, UM_TENANT_ID) -); - - -CREATE TABLE IF NOT EXISTS UM_CLAIM( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_DIALECT_ID INTEGER NOT NULL, - UM_CLAIM_URI VARCHAR(255) NOT NULL, - UM_DISPLAY_TAG VARCHAR(255), - UM_DESCRIPTION VARCHAR(255), - UM_MAPPED_ATTRIBUTE_DOMAIN VARCHAR(255), - UM_MAPPED_ATTRIBUTE VARCHAR(255), - UM_REG_EX VARCHAR(255), - UM_SUPPORTED SMALLINT, - UM_REQUIRED SMALLINT, - UM_DISPLAY_ORDER INTEGER, - UM_CHECKED_ATTRIBUTE SMALLINT, - UM_READ_ONLY SMALLINT, - UM_TENANT_ID INTEGER DEFAULT 0, - UNIQUE(UM_DIALECT_ID, UM_CLAIM_URI,UM_MAPPED_ATTRIBUTE_DOMAIN, UM_TENANT_ID), - FOREIGN KEY(UM_DIALECT_ID, UM_TENANT_ID) REFERENCES UM_DIALECT(UM_ID, UM_TENANT_ID), - PRIMARY KEY (UM_ID, UM_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS UM_PROFILE_CONFIG( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_DIALECT_ID INTEGER, - UM_PROFILE_NAME VARCHAR(255), - UM_TENANT_ID INTEGER DEFAULT 0, - FOREIGN KEY(UM_DIALECT_ID, UM_TENANT_ID) REFERENCES UM_DIALECT(UM_ID, UM_TENANT_ID), - PRIMARY KEY (UM_ID, UM_TENANT_ID) -); - - -CREATE TABLE IF NOT EXISTS UM_HYBRID_ROLE( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_ROLE_NAME VARCHAR(255), - UM_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (UM_ID, UM_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS UM_HYBRID_USER_ROLE( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_USER_NAME VARCHAR(255), - UM_ROLE_ID INTEGER NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - UM_DOMAIN_ID INTEGER, - UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID,UM_DOMAIN_ID), - FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_HYBRID_ROLE(UM_ID, UM_TENANT_ID) ON DELETE CASCADE, - FOREIGN KEY (UM_DOMAIN_ID, UM_TENANT_ID) REFERENCES UM_DOMAIN(UM_DOMAIN_ID, UM_TENANT_ID) ON DELETE CASCADE, - PRIMARY KEY (UM_ID, UM_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS UM_HYBRID_REMEMBER_ME ( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_USER_NAME VARCHAR(255) NOT NULL, - UM_COOKIE_VALUE VARCHAR(1024), - UM_CREATED_TIME TIMESTAMP, - UM_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (UM_ID, UM_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS UM_SYSTEM_ROLE( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_ROLE_NAME VARCHAR(255), - UM_TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (UM_ID, UM_TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS UM_SYSTEM_USER_ROLE( - UM_ID INTEGER NOT NULL AUTO_INCREMENT, - UM_USER_NAME VARCHAR(255), - UM_ROLE_ID INTEGER NOT NULL, - UM_TENANT_ID INTEGER DEFAULT 0, - UNIQUE (UM_USER_NAME, UM_ROLE_ID, UM_TENANT_ID), - FOREIGN KEY (UM_ROLE_ID, UM_TENANT_ID) REFERENCES UM_SYSTEM_ROLE(UM_ID, UM_TENANT_ID), - PRIMARY KEY (UM_ID, UM_TENANT_ID) -); diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/axis2.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/axis2.xml deleted file mode 100644 index fc5047f29..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/axis2.xml +++ /dev/null @@ -1,723 +0,0 @@ - - - - - - - - - - - - - ${hotdeployment} - ${hotupdate} - optional - true - work/mtom - 4000 - - ${childfirstCL} - - - true - - - true - - - - false - - inmemory - - - - - - - services - - - axis2services - - - axis2modules - - - @product.name@-@product.version@ - - - @product.name@-@product.version@ - - - - - - - false - - - - - - false - - - true - - - repository/deployment/server/synapse-configs - - - . - - - . - - - WSO2 Carbon Server - - - - - - - ${jaxwsparam} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9763 - - - - - - - - - - - - 9443 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - HTTP/1.1 - chunked - - true - - - HTTP/1.1 - chunked - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - multicast - - - - - wso2.carbon.domain - - - - - - 45564 - - 100 - - 60 - - - - - - 127.0.0.1 - - - - - - 4000 - - - - - - - - - - - - - - - - - - 127.0.0.1 - 4000 - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/axis2_client.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/axis2_client.xml deleted file mode 100644 index 40f3e07c3..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/axis2_client.xml +++ /dev/null @@ -1,300 +0,0 @@ - - - - - - - true - false - false - - - 500 - - 15000 - - - false - - - - true - - - - - - false - - - admin - axis2 - - - - - - - - - - - - - - - - - - - - - - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 6071 - - - - - - - - - - - - - - - - - - - - - - HTTP/1.1 - chunked - 60000 - 60000 - - - HTTP/1.1 - chunked - 60000 - 60000 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/tenant-axis2.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/tenant-axis2.xml deleted file mode 100644 index 6f49f62ed..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/axis2/tenant-axis2.xml +++ /dev/null @@ -1,285 +0,0 @@ - - - - - - - - - true - true - optional - - - true - - - false - - - - true - - - - - - false - - - false - - - axis2services - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/carbon.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/carbon.xml deleted file mode 100644 index f24ee57be..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/carbon.xml +++ /dev/null @@ -1,656 +0,0 @@ - - - - - - - - - ${product.name} - - - ${product.key} - - - ${product.version} - - - - - - - - - local:/${carbon.context}/services/ - - - - - - - ${default.server.role} - - - - - - - org.wso2.carbon - - - / - - - - - - - - - 15 - - - - - - - - - 0 - - - - - 9999 - - 11111 - - - - - - 10389 - - 8000 - - - - - - 10500 - - - - - - - org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory - - - - - - - - - java - - - - - - - - - - false - - - false - - - 600 - - - - false - - - - - - - - 30 - - - - - - - - - 15 - - - - - - ${carbon.home}/repository/deployment/server/ - - - 15 - - - ${carbon.home}/repository/conf/axis2/axis2.xml - - - 30000 - - - ${carbon.home}/repository/deployment/client/ - - ${carbon.home}/repository/conf/axis2/axis2_client.xml - - true - - - - - - - - - - admin - Default Administrator Role - - - user - Default User Role - - - - - - - - - - - - ${carbon.home}/repository/resources/security/wso2carbon.jks - - JKS - - wso2carbon - - wso2carbon - - wso2carbon - - - - - - ${carbon.home}/repository/resources/security/client-truststore.jks - - JKS - - wso2carbon - - - - - - - - - - - - - - - - - - - UserManager - - - false - - - - - - - ${carbon.home}/tmp/work - - - - - - true - - - 10 - - - 30 - - - - - - 100 - - - - keystore - certificate - * - - org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor - - - - - jarZip - - org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor - - - - dbs - - org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor - - - - tools - - org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor - - - - toolsAny - - org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor - - - - - - - info - org.wso2.carbon.core.transports.util.InfoProcessor - - - wsdl - org.wso2.carbon.core.transports.util.Wsdl11Processor - - - wsdl2 - org.wso2.carbon.core.transports.util.Wsdl20Processor - - - xsd - org.wso2.carbon.core.transports.util.XsdProcessor - - - - - - false - false - true - svn - http://svnrepo.example.com/repos/ - username - password - true - - - - - - - - - - - - - - - ${require.carbon.servlet} - - - - - true - - - - - - - default repository - ${p2.repo.url} - - - - - - - - true - - - - - - true - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/cdm-config.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/cdm-config.xml deleted file mode 100644 index 9097a645c..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/cdm-config.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - jdbc/DM_DS - - - - - 1000 - 60000 - 60000 - true - - org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm.FCMBasedPushNotificationProvider - - org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider - org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.HTTPBasedPushNotificationProvider - org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider - - - - false - - - https://localhost:9443 - admin - admin - - - org.wso2.carbon.policy.mgt - true - 60000 - 5 - 8 - 20 - - - - Simple - - - - 20 - 20 - 20 - 20 - 20 - 20 - - - - true - - - - false - 600 - - 10000 - - - false - 86400 - - - false - false - - BYOD,COPE - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml deleted file mode 100644 index 897e33581..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/datasources/master-datasources.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader - - - - - - WSO2_CARBON_DB - The datasource used for registry and user manager - - jdbc/WSO2CarbonDB - - - - jdbc:h2:repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE;LOCK_TIMEOUT=60000 - wso2carbon - wso2carbon - org.h2.Driver - 50 - 60000 - true - SELECT 1 - 30000 - false - - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/bundle-config/README.txt b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/bundle-config/README.txt deleted file mode 100644 index ffa7c7926..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/bundle-config/README.txt +++ /dev/null @@ -1,12 +0,0 @@ -This directory supports adding third-pary config files to specific bundles during runtime. - -Explanation: Each OSGi bundle has its own classLoader. Some thirdpary libs read configs from classPath. This scenario fails in OSGi runtime, since OSGi runtime does not share a common classPath for individual bundles. Bundling config files during the bundle creation process itself will solve the issue. However it limits the ability to edit the configs during restarts. - -Here we are providing a workaround for such scenarios. The given config file will get resolved to a fragment bundle and will get attached to the specified host bundle. The host bundle name(symbolic name) is resolved by looking at the directory structure. Hence host bundle name should be directory name of the config file directory. - - -Example: The bundle with symbolic name, 'org.foo.bar' expects a config file named 'foobar.properties' from its classPath. - -create a directory named 'org.foo.bar' inside 'repository/conf/etc/bundle-config' - (this directory) and place the foobar.properties file. - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/carboncontext-osgi-services.properties b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/carboncontext-osgi-services.properties deleted file mode 100644 index f52d19400..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/carboncontext-osgi-services.properties +++ /dev/null @@ -1,3 +0,0 @@ -#osgi.service.1 = org.wso2.carbon.client.configcontext.provider.Axis2ClientConfigContextProvider -#osgi.service.2 = org.wso2.carbon.user.core.UserManager -#osgi.service.3 = org.wso2.carbon.user.api.UserRealmService \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/config-validation.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/config-validation.xml deleted file mode 100644 index 3b5b3484b..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/config-validation.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - 800 - 2047 - 2047 - 1024 - 4096 - 02:FB:AA:5F:20:64:49:4A:27:29:55:71:83:F7:46:CD - - - 256 - 512 - 256 - - - carbon.home - carbon.config.dir.path - axis2.home - - - Linux - Unix - Mac OS - Windows Server 2003 - Windows XP - Windows Vista - Windows 7 - Mac OS X - Windows Server 2008 - Windows Server 2008 R2 - AIX - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/jmx.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/jmx.xml deleted file mode 100644 index b2bb2ac7a..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/jmx.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - true - - - localhost - - - ${Ports.JMX.RMIRegistryPort} - - - ${Ports.JMX.RMIServerPort} - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/launch.ini b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/launch.ini deleted file mode 100644 index 8b9f5ad19..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/launch.ini +++ /dev/null @@ -1,258 +0,0 @@ -# Eclipse Runtime Configuration Overrides -# These properties are loaded prior to starting the framework and can also be used to override System Properties -# @null is a special value used to override and clear the framework's copy of a System Property prior to starting the framework -# "*" can be used together with @null to clear System Properties that match a prefix name. - -osgi.*=@null -org.osgi.*=@null -eclipse.*=@null - -osgi.parentClassloader=app -osgi.contextClassLoaderParent=app - -# When osgi.clean is set to "true", any cached data used by the OSGi framework -# will be wiped clean. This will clean the caches used to store bundle -# dependency resolution and eclipse extension registry data. Using this -# option will force OSGi framework to reinitialize these caches. -# The following setting is put in place to get rid of the problems -# faced when re-starting the system. Please note that, when this setting is -# true, if you manually start a bundle, it would not be available when -# you re-start the system. To avid this, copy the bundle jar to the plugins -# folder, before you re-start the system. -osgi.clean=true - -# Uncomment the following line to turn on Eclipse Equinox debugging. -# You may also edit the osgi-debug.options file and fine tune the debugging -# options to suite your needs. -#osgi.debug=./repository/conf/osgi-debug.options - -# Following system property allows us to control the public JDK packages exported through the system bundle. -org.osgi.framework.system.packages=javax.accessibility,\ -javax.activity,\ -javax.crypto,\ -javax.crypto.interfaces,\ -javax.crypto.spec,\ -javax.imageio,\ -javax.imageio.event,\ -javax.imageio.metadata,\ -javax.imageio.plugins.bmp,\ -javax.imageio.plugins.jpeg,\ -javax.imageio.spi,\ -javax.imageio.stream,\ -javax.jms,\ -javax.management,\ -javax.management.loading,\ -javax.management.modelmbean,\ -javax.management.monitor,\ -javax.management.openmbean,\ -javax.management.relation,\ -javax.management.remote,\ -javax.management.remote.rmi,\ -javax.management.timer,\ -javax.naming,\ -javax.naming.directory,\ -javax.naming.event,\ -javax.naming.ldap,\ -javax.naming.spi,\ -javax.net,\ -javax.net.ssl,\ -javax.print,\ -javax.print.attribute,\ -javax.print.attribute.standard,\ -javax.print.event,\ -javax.rmi,\ -javax.rmi.CORBA,\ -javax.rmi.ssl,\ -javax.script,\ -javax.security.auth,\ -javax.security.auth.callback,\ -javax.security.auth.kerberos,\ -javax.security.auth.login,\ -javax.security.auth.spi,\ -javax.security.auth.x500,\ -javax.security.cert,\ -javax.security.sasl,\ -javax.sound.midi,\ -javax.sound.midi.spi,\ -javax.sound.sampled,\ -javax.sound.sampled.spi,\ -javax.sql,\ -javax.sql.rowset,\ -javax.sql.rowset.serial,\ -javax.sql.rowset.spi,\ -javax.swing,\ -javax.swing.border,\ -javax.swing.colorchooser,\ -javax.swing.event,\ -javax.swing.filechooser,\ -javax.swing.plaf,\ -javax.swing.plaf.basic,\ -javax.swing.plaf.metal,\ -javax.swing.plaf.multi,\ -javax.swing.plaf.synth,\ -javax.swing.table,\ -javax.swing.text,\ -javax.swing.text.html,\ -javax.swing.text.html.parser,\ -javax.swing.text.rtf,\ -javax.swing.tree,\ -javax.swing.undo,\ -javax.transaction,\ -javax.transaction.xa,\ -javax.xml.namespace,\ -javax.xml.parsers,\ -javax.xml.stream,\ -javax.xml.stream.events,\ -javax.xml.stream.util,\ -javax.xml.transform,\ -javax.xml.transform.stream,\ -javax.xml.transform.dom,\ -javax.xml.transform.sax,\ -javax.xml,\ -javax.xml.validation,\ -javax.xml.datatype,\ -javax.xml.xpath,\ -javax.activation,\ -com.sun.activation.registries,\ -com.sun.activation.viewers,\ -org.ietf.jgss,\ -org.omg.CORBA,\ -org.omg.CORBA_2_3,\ -org.omg.CORBA_2_3.portable,\ -org.omg.CORBA.DynAnyPackage,\ -org.omg.CORBA.ORBPackage,\ -org.omg.CORBA.portable,\ -org.omg.CORBA.TypeCodePackage,\ -org.omg.CosNaming,\ -org.omg.CosNaming.NamingContextExtPackage,\ -org.omg.CosNaming.NamingContextPackage,\ -org.omg.Dynamic,\ -org.omg.DynamicAny,\ -org.omg.DynamicAny.DynAnyFactoryPackage,\ -org.omg.DynamicAny.DynAnyPackage,\ -org.omg.IOP,\ -org.omg.IOP.CodecFactoryPackage,\ -org.omg.IOP.CodecPackage,\ -org.omg.Messaging,\ -org.omg.PortableInterceptor,\ -org.omg.PortableInterceptor.ORBInitInfoPackage,\ -org.omg.PortableServer,\ -org.omg.PortableServer.CurrentPackage,\ -org.omg.PortableServer.POAManagerPackage,\ -org.omg.PortableServer.POAPackage,\ -org.omg.PortableServer.portable,\ -org.omg.PortableServer.ServantLocatorPackage,\ -org.omg.SendingContext,\ -org.omg.stub.java.rmi,\ -org.w3c.dom,\ -org.w3c.dom.bootstrap,\ -org.w3c.dom.css,\ -org.w3c.dom.events,\ -org.w3c.dom.html,\ -org.w3c.dom.ls,\ -org.w3c.dom.ranges,\ -org.w3c.dom.stylesheets,\ -org.w3c.dom.traversal,\ -org.w3c.dom.views ,\ -org.xml.sax,\ -org.xml.sax.ext,\ -org.xml.sax.helpers,\ -org.apache.xerces.xpointer,\ -org.apache.xerces.xni.grammars,\ -org.apache.xerces.impl.xs.util,\ -org.apache.xerces.jaxp.validation,\ -org.apache.xerces.impl.dtd.models,\ -org.apache.xerces.impl.xpath,\ -org.apache.xerces.dom3.as,\ -org.apache.xerces.impl.dv.xs,\ -org.apache.xerces.util,\ -org.apache.xerces.impl.xs.identity,\ -org.apache.xerces.impl.xs.opti,\ -org.apache.xerces.jaxp,\ -org.apache.xerces.impl.dv,\ -org.apache.xerces.xs.datatypes,\ -org.apache.xerces.dom.events,\ -org.apache.xerces.impl.msg,\ -org.apache.xerces.xni,\ -org.apache.xerces.impl.xs,\ -org.apache.xerces.impl,\ -org.apache.xerces.impl.io,\ -org.apache.xerces.xinclude,\ -org.apache.xerces.jaxp.datatype,\ -org.apache.xerces.parsers,\ -org.apache.xerces.impl.dv.util,\ -org.apache.xerces.xni.parser,\ -org.apache.xerces.impl.xs.traversers,\ -org.apache.xerces.impl.dv.dtd,\ -org.apache.xerces.xs,\ -org.apache.xerces.impl.dtd,\ -org.apache.xerces.impl.validation,\ -org.apache.xerces.impl.xs.models,\ -org.apache.xerces.impl.xpath.regex,\ -org.apache.xml.serialize,\ -org.apache.xerces.dom,\ -org.apache.xalan,\ -org.apache.xalan.xslt,\ -org.apache.xalan.templates,\ -org.apache.xalan.xsltc,\ -org.apache.xalan.xsltc.cmdline,\ -org.apache.xalan.xsltc.cmdline.getopt,\ -org.apache.xalan.xsltc.trax,\ -org.apache.xalan.xsltc.dom,\ -org.apache.xalan.xsltc.runtime,\ -org.apache.xalan.xsltc.runtime.output,\ -org.apache.xalan.xsltc.util,\ -org.apache.xalan.xsltc.compiler,\ -org.apache.xalan.xsltc.compiler.util,\ -org.apache.xalan.serialize,\ -org.apache.xalan.client,\ -org.apache.xalan.res,\ -org.apache.xalan.transformer,\ -org.apache.xalan.extensions,\ -org.apache.xalan.lib,\ -org.apache.xalan.lib.sql,\ -org.apache.xalan.processor,\ -org.apache.xalan.trace,\ -org.apache.xml.dtm,\ -org.apache.xml.dtm.ref,\ -org.apache.xml.dtm.ref.sax2dtm,\ -org.apache.xml.dtm.ref.dom2dtm,\ -org.apache.xml.utils,\ -org.apache.xml.utils.res,\ -org.apache.xml.res,\ -org.apache.xml.serializer,\ -org.apache.xml.serializer.utils,\ -org.apache.xpath,\ -org.apache.xpath.domapi,\ -org.apache.xpath.objects,\ -org.apache.xpath.patterns,\ -org.apache.xpath.jaxp,\ -org.apache.xpath.res,\ -org.apache.xpath.operations,\ -org.apache.xpath.functions,\ -org.apache.xpath.axes,\ -org.apache.xpath.compiler,\ -org.apache.xml.resolver,\ -org.apache.xml.resolver.tools,\ -org.apache.xml.resolver.helpers,\ -org.apache.xml.resolver.readers,\ -org.apache.xml.resolver.etc,\ -org.apache.xml.resolver.apps,\ -javax.xml.ws,\ -javax.xml.ws.handler,\ -javax.xml.ws.handler.soap,\ -javax.xml.ws.http,\ -javax.xml.ws.soap,\ -javax.xml.ws.spi,\ -javax.xml.ws.spi.http,\ -javax.xml.ws.wsaddressing,\ -javax.xml.bind,\ -javax.xml.bind.annotation,\ -javax.xml.bind.annotation.adapters,\ -javax.annotation,\ -javax.jws,\ -javax.jws.soap,\ -com.sun.xml.internal.messaging.saaj.soap.ver1_1,\ -com.sun.xml.internal.messaging.saaj.soap,\ -com.sun.tools.internal.ws.spi,\ -org.wso2.carbon.bootstrap diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/logging-bridge.properties b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/logging-bridge.properties deleted file mode 100644 index 7b63190ae..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/logging-bridge.properties +++ /dev/null @@ -1,65 +0,0 @@ -############################################################ -# Default Logging Configuration File -# -# You can use a different file by specifying a filename -# with the java.util.logging.config.file system property. -# For example java -Djava.util.logging.config.file=myfile -############################################################ - -############################################################ -# Global properties -# NOTE: this configuration file use to get the handler list, -# Properties(except level property) define for each handler -# may be not available because LogRecords handover to log4j -# appenders in runtime. -############################################################ - -# "handlers" specifies a comma separated list of log Handler -# classes. These handlers will be installed during VM startup. -# Note that these classes must be on the system classpath. -# By default we only configure a ConsoleHandler, which will only -# show messages at the INFO and above levels. -#handlers= java.util.logging.ConsoleHandler - -# To also add the FileHandler, use the following line instead. -#handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler -# Add org.wso2.carbon.bootstrap.logging.handlers.LogEventHandler to handlers if you need to push java logs to LOGEVENT appender - -handlers= org.wso2.carbon.bootstrap.logging.handlers.LoggingConsoleHandler, org.wso2.carbon.bootstrap.logging.handlers.LoggingFileHandler - -# Default global logging level. -# This specifies which kinds of events are logged across -# all loggers. For any given facility this global level -# can be overriden by a facility specific level -# Note that the ConsoleHandler also has a separate level -# setting to limit messages printed to the console. -.level= INFO - -############################################################ -# Handler specific properties. -# Describes specific configuration info for Handlers. -# - -############################################################ -# This FileHandler pushed LogRecords to a log4j FileAppander in runtime -org.wso2.carbon.bootstrap.logging.handlers.LoggingFileHandler.level = INFO -#org.wso2.carbon.bootstrap.logging.handlers.LoggingFileHandler.formatter = java.util.logging.SimpleFormatter - -# This ConsoleHandler pushed LogRecords to q log4j ConsoleAppander in runtime -org.wso2.carbon.bootstrap.logging.handlers.LoggingConsoleHandler.level = INFO -#org.wso2.carbon.bootstrap.logging.handlers.LoggingConsoleHandler.formatter = java.util.logging.SimpleFormatter - - -############################################################ -# Facility specific properties. -# Provides extra control for each logger. -############################################################ - -# For example, set the com.xyz.foo logger to only log SEVERE -# messages: -#com.xyz.foo.level = SEVERE -org.apache.coyote.level = SEVERE -org.apache.catalina.level = SEVERE -com.hazelcast.level = SEVERE - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/mime.mappings b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/mime.mappings deleted file mode 100755 index 97a5c5a5f..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/mime.mappings +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2005-2011 WSO2, Inc. (http://wso2.com) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# This file is to define the human readable media type for a mime type. -# Eg:- -# text/plain txt text -application/wsdl+xml WSDL -application/x-xsd+xml Schema -application/policy+xml Policy -application/vnd.wso2-service+xml Service -application/vnd.wso2-hyperlink Hyperlink -application/vnd.wso2.endpoint Endpoint -application/vnd.wso2-api+xml API -application/vnd.wso2-uri+xml URI diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/mime.types b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/mime.types deleted file mode 100644 index 21c386da0..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/mime.types +++ /dev/null @@ -1,734 +0,0 @@ -# -# Copyright 2005-2009 WSO2, Inc. (http://wso2.com) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# Media type for wsdl files. This is not defined in the original mime.types file. -chemical/x-alchemy alc -application/andrew-inset ez -application/wsdl+xml wsdl -application/vnd.sun.wadl+xml wadl -application/activemessage -application/applefile -application/atomicmail -application/batch-SMTP -application/beep+xml -application/cals-1840 -application/commonground -application/cu-seeme cu -application/cybercash -application/dca-rft -application/dec-dx -application/docbook+xml -application/dsptype tsp -application/dvcs -application/edi-consent -application/edi-x12 -application/edifact -application/eshop -application/font-tdpfr -application/futuresplash spl -application/ghostview -application/hta hta -application/http -application/hyperstudio -application/iges -application/index -application/index.cmd -application/index.obj -application/index.response -application/index.vnd -application/iotp -application/ipp -application/isup -application/java-archive jar -application/java-serialized-object ser -application/java-vm class -application/mac-binhex40 hqx -application/mac-compactpro cpt -application/macwriteii -application/marc -application/mathematica nb -application/mathematica-old -application/msaccess mdb -application/msword doc dot -application/news-message-id -application/news-transmission -application/ocsp-request -application/ocsp-response -application/octet-stream bin -application/oda oda -application/ogg ogg -application/parityfec -application/pdf pdf -application/pgp-encrypted -application/pgp-keys key -application/pgp-signature pgp -application/pics-rules prf -application/pkcs10 -application/pkcs7-mime -application/pkcs7-signature -application/pkix-cert -application/pkix-crl -application/pkixcmp -application/policy+xml -application/postscript ps ai eps -application/prs.alvestrand.titrax-sheet -application/prs.cww -application/prs.nprend -application/qsig -application/rar rar -application/rdf+xml rdf -application/remote-printing -application/riscos -application/rss+xml rss -application/rtf -application/sdp -application/set-payment -application/set-payment-initiation -application/set-registration -application/set-registration-initiation -application/sgml -application/sgml-open-catalog -application/sieve -application/slate -application/smil smi smil -application/timestamp-query -application/timestamp-reply -application/vemmi -application/whoispp-query -application/whoispp-response -application/wita -application/wordperfect wpd -application/wordperfect5.1 wp5 -application/x400-bp -application/xhtml+xml xhtml xht -application/xml xml xsl xslt jrxml -application/xml-dtd -application/xml-external-parsed-entity -application/zip zip -application/vnd.3M.Post-it-Notes -application/vnd.accpac.simply.aso -application/vnd.accpac.simply.imp -application/vnd.acucobol -application/vnd.aether.imp -application/vnd.anser-web-certificate-issue-initiation -application/vnd.anser-web-funds-transfer-initiation -application/vnd.audiograph -application/vnd.bmi -application/vnd.businessobjects -application/vnd.canon-cpdl -application/vnd.canon-lips -application/vnd.cinderella cdy -application/vnd.claymore -application/vnd.commerce-battelle -application/vnd.commonspace -application/vnd.comsocaller -application/vnd.contact.cmsg -application/vnd.cosmocaller -application/vnd.ctc-posml -application/vnd.cups-postscript -application/vnd.cups-raster -application/vnd.cups-raw -application/vnd.cybank -application/vnd.dna -application/vnd.dpgraph -application/vnd.dxr -application/vnd.ecdis-update -application/vnd.ecowin.chart -application/vnd.ecowin.filerequest -application/vnd.ecowin.fileupdate -application/vnd.ecowin.series -application/vnd.ecowin.seriesrequest -application/vnd.ecowin.seriesupdate -application/vnd.enliven -application/vnd.epson.esf -application/vnd.epson.msf -application/vnd.epson.quickanime -application/vnd.epson.salt -application/vnd.epson.ssf -application/vnd.ericsson.quickcall -application/vnd.eudora.data -application/vnd.fdf -application/vnd.ffsns -application/vnd.flographit -application/vnd.framemaker -application/vnd.fsc.weblaunch -application/vnd.fujitsu.oasys -application/vnd.fujitsu.oasys2 -application/vnd.fujitsu.oasys3 -application/vnd.fujitsu.oasysgp -application/vnd.fujitsu.oasysprs -application/vnd.fujixerox.ddd -application/vnd.fujixerox.docuworks -application/vnd.fujixerox.docuworks.binder -application/vnd.fut-misnet -application/vnd.grafeq -application/vnd.groove-account -application/vnd.groove-identity-message -application/vnd.groove-injector -application/vnd.groove-tool-message -application/vnd.groove-tool-template -application/vnd.groove-vcard -application/vnd.hhe.lesson-player -application/vnd.hp-HPGL -application/vnd.hp-PCL -application/vnd.hp-PCLXL -application/vnd.hp-hpid -application/vnd.hp-hps -application/vnd.httphone -application/vnd.hzn-3d-crossword -application/vnd.ibm.MiniPay -application/vnd.ibm.afplinedata -application/vnd.ibm.modcap -application/vnd.informix-visionary -application/vnd.intercon.formnet -application/vnd.intertrust.digibox -application/vnd.intertrust.nncp -application/vnd.intu.qbo -application/vnd.intu.qfx -application/vnd.irepository.package+xml -application/vnd.is-xpr -application/vnd.japannet-directory-service -application/vnd.japannet-jpnstore-wakeup -application/vnd.japannet-payment-wakeup -application/vnd.japannet-registration -application/vnd.japannet-registration-wakeup -application/vnd.japannet-setstore-wakeup -application/vnd.japannet-verification -application/vnd.japannet-verification-wakeup -application/vnd.koan -application/vnd.lotus-1-2-3 -application/vnd.lotus-approach -application/vnd.lotus-freelance -application/vnd.lotus-notes -application/vnd.lotus-organizer -application/vnd.lotus-screencam -application/vnd.lotus-wordpro -application/vnd.mcd -application/vnd.mediastation.cdkey -application/vnd.meridian-slingshot -application/vnd.mif -application/vnd.minisoft-hp3000-save -application/vnd.mitsubishi.misty-guard.trustweb -application/vnd.mobius.daf -application/vnd.mobius.dis -application/vnd.mobius.msl -application/vnd.mobius.plc -application/vnd.mobius.txf -application/vnd.motorola.flexsuite -application/vnd.motorola.flexsuite.adsi -application/vnd.motorola.flexsuite.fis -application/vnd.motorola.flexsuite.gotap -application/vnd.motorola.flexsuite.kmr -application/vnd.motorola.flexsuite.ttc -application/vnd.motorola.flexsuite.wem -application/vnd.mozilla.xul+xml xul -application/vnd.ms-artgalry -application/vnd.ms-asf -application/vnd.ms-excel xls xlb xlt -application/vnd.ms-lrm -application/vnd.ms-pki.seccat cat -application/vnd.ms-pki.stl stl -application/vnd.ms-powerpoint ppt pps -application/vnd.ms-project -application/vnd.ms-tnef -application/vnd.ms-works -application/vnd.mseq -application/vnd.msign -application/vnd.music-niff -application/vnd.musician -application/vnd.netfpx -application/vnd.noblenet-directory -application/vnd.noblenet-sealer -application/vnd.noblenet-web -application/vnd.novadigm.EDM -application/vnd.novadigm.EDX -application/vnd.novadigm.EXT -application/vnd.oasis.opendocument.chart odc -application/vnd.oasis.opendocument.database odb -application/vnd.oasis.opendocument.formula odf -application/vnd.oasis.opendocument.graphics odg -application/vnd.oasis.opendocument.graphics-template otg -application/vnd.oasis.opendocument.image odi -application/vnd.oasis.opendocument.presentation odp -application/vnd.oasis.opendocument.presentation-template otp -application/vnd.oasis.opendocument.spreadsheet ods -application/vnd.oasis.opendocument.spreadsheet-template ots -application/vnd.oasis.opendocument.text odt -application/vnd.oasis.opendocument.text-master odm -application/vnd.oasis.opendocument.text-template ott -application/vnd.oasis.opendocument.text-web oth -application/vnd.osa.netdeploy -application/vnd.palm -application/vnd.pg.format -application/vnd.pg.osasli -application/vnd.powerbuilder6 -application/vnd.powerbuilder6-s -application/vnd.powerbuilder7 -application/vnd.powerbuilder7-s -application/vnd.powerbuilder75 -application/vnd.powerbuilder75-s -application/vnd.previewsystems.box -application/vnd.publishare-delta-tree -application/vnd.pvi.ptid1 -application/vnd.pwg-xhtml-print+xml -application/vnd.rapid -application/vnd.rim.cod cod -application/vnd.s3sms -application/vnd.seemail -application/vnd.shana.informed.formdata -application/vnd.shana.informed.formtemplate -application/vnd.shana.informed.interchange -application/vnd.shana.informed.package -application/vnd.smaf mmf -application/vnd.sss-cod -application/vnd.sss-dtf -application/vnd.sss-ntf -application/vnd.stardivision.calc sdc -application/vnd.stardivision.draw sda -application/vnd.stardivision.impress sdd sdp -application/vnd.stardivision.math smf -application/vnd.stardivision.writer sdw vor -application/vnd.stardivision.writer-global sgl -application/vnd.street-stream -application/vnd.sun.xml.calc sxc -application/vnd.sun.xml.calc.template stc -application/vnd.sun.xml.draw sxd -application/vnd.sun.xml.draw.template std -application/vnd.sun.xml.impress sxi -application/vnd.sun.xml.impress.template sti -application/vnd.sun.xml.math sxm -application/vnd.sun.xml.writer sxw -application/vnd.sun.xml.writer.global sxg -application/vnd.sun.xml.writer.template stw -application/vnd.svd -application/vnd.swiftview-ics -application/vnd.symbian.install sis -application/vnd.triscape.mxs -application/vnd.trueapp -application/vnd.truedoc -application/vnd.tve-trigger -application/vnd.ufdl -application/vnd.uplanet.alert -application/vnd.uplanet.alert-wbxml -application/vnd.uplanet.bearer-choice -application/vnd.uplanet.bearer-choice-wbxml -application/vnd.uplanet.cacheop -application/vnd.uplanet.cacheop-wbxml -application/vnd.uplanet.channel -application/vnd.uplanet.channel-wbxml -application/vnd.uplanet.list -application/vnd.uplanet.list-wbxml -application/vnd.uplanet.listcmd -application/vnd.uplanet.listcmd-wbxml -application/vnd.uplanet.signal -application/vnd.vcx -application/vnd.vectorworks -application/vnd.vidsoft.vidconference -application/vnd.visio vsd -application/vnd.vividence.scriptfile -application/vnd.wap.sic -application/vnd.wap.slc -application/vnd.wap.wbxml wbxml -application/vnd.wap.wmlc wmlc -application/vnd.wap.wmlscriptc wmlsc -application/vnd.webturbo -application/vnd.wrq-hp3000-labelled -application/vnd.wso2.bpel+xml bpel -application/vnd.wso2.bpmn+xml bpmn -application/vnd.wso2.endpoint -application/vnd.wso2.governance-archive gar -application/vnd.wso2-hyperlink -application/vnd.wso2.registry-ext-type+xml rxt -application/vnd.wso2-service+xml -application/vnd.wso2.xpdl+xml xpdl -application/vnd.wt.stf -application/vnd.xara -application/vnd.xfdl -application/vnd.yellowriver-custom-menu -application/x-123 wk -application/x-abiword abw -application/x-apple-diskimage dmg -application/x-bcpio bcpio -application/x-bittorrent torrent -application/x-cdf cdf -application/x-cdlink vcd -application/x-chess-pgn pgn -application/x-core -application/x-cpio cpio -application/x-csh csh -application/x-debian-package deb udeb -application/x-director dcr dir dxr -application/x-dms dms -application/x-doom wad -application/x-dvi dvi -application/x-executable -application/x-flac flac -application/x-font pfa pfb gsf pcf pcf.Z -application/x-freemind mm -application/x-futuresplash spl -application/x-gnumeric gnumeric -application/x-go-sgf sgf -application/x-graphing-calculator gcf -application/x-gtar gtar tgz taz -application/x-hdf hdf -application/x-httpd-php phtml pht php -application/x-httpd-php-source phps -application/x-httpd-php3 php3 -application/x-httpd-php3-preprocessed php3p -application/x-httpd-php4 php4 -application/x-httpd-eruby rhtml -application/x-ica ica -application/x-internet-signup ins isp -application/x-iphone iii -application/x-iso9660-image iso -application/x-java-applet -application/x-java-bean -application/x-java-jnlp-file jnlp -application/x-javascript js -application/x-jmol jmz -application/x-kchart chrt -application/x-kdelnk -application/x-killustrator kil -application/x-koan skp skd skt skm -application/x-kpresenter kpr kpt -application/x-kspread ksp -application/x-kword kwd kwt -application/x-latex latex -application/x-lha lha -application/x-lzh lzh -application/x-lzx lzx -application/x-maker frm maker frame fm fb book fbdoc -application/x-mif mif -application/x-ms-wmd wmd -application/x-ms-wmz wmz -application/x-msdos-program com exe bat dll -application/x-msi msi -application/x-netcdf nc -application/x-ns-proxy-autoconfig pac -application/x-nwc nwc -application/x-object o -application/x-oz-application oza -application/x-pkcs7-certreqresp p7r -application/x-pkcs7-crl crl -application/x-python-code pyc pyo -application/x-quicktimeplayer qtl -application/x-redhat-package-manager rpm -application/x-rx -application/x-sh sh -application/x-shar shar -application/x-shellscript -application/x-shockwave-flash swf swfl -application/x-stuffit sit -application/x-sv4cpio sv4cpio -application/x-sv4crc sv4crc -application/x-tar tar -application/x-tcl tcl -application/x-tex-gf gf -application/x-tex-pk pk -application/x-texinfo texinfo texi -application/x-trash ~ % bak old sik -application/x-troff t tr roff -application/x-troff-man man -application/x-troff-me me -application/x-troff-ms ms -application/x-ustar ustar -application/x-videolan -application/x-wais-source src -application/x-wingz wz -application/x-x509-ca-cert crt -application/x-xcf xcf -application/x-xfig fig -application/x-xpinstall xpi -application/x-xsd+xml xsd - -audio/32kadpcm -audio/basic au snd -audio/g.722.1 -audio/l16 -audio/midi mid midi kar -audio/mp4a-latm -audio/mpa-robust -audio/mpeg mpga mpega mp2 mp3 m4a -audio/mpegurl m3u -audio/parityfec -audio/prs.sid sid -audio/telephone-event -audio/tone -audio/vnd.cisco.nse -audio/vnd.cns.anp1 -audio/vnd.cns.inf1 -audio/vnd.digital-winds -audio/vnd.everad.plj -audio/vnd.lucent.voice -audio/vnd.nortel.vbk -audio/vnd.nuera.ecelp4800 -audio/vnd.nuera.ecelp7470 -audio/vnd.nuera.ecelp9600 -audio/vnd.octel.sbc -audio/vnd.qcelp -audio/vnd.rhetorex.32kadpcm -audio/vnd.vmx.cvsd -audio/x-aiff aif aiff aifc -audio/x-gsm gsm -audio/x-mpegurl m3u -audio/x-ms-wma wma -audio/x-ms-wax wax -audio/x-pn-realaudio-plugin -audio/x-pn-realaudio ra rm ram -audio/x-realaudio ra -audio/x-scpls pls -audio/x-sd2 sd2 -audio/x-wav wav - -chemical/x-alchemy alc -chemical/x-cache cac cache -chemical/x-cache-csf csf -chemical/x-cactvs-binary cbin cascii ctab -chemical/x-cdx cdx -chemical/x-cerius cer -chemical/x-chem3d c3d -chemical/x-chemdraw chm -chemical/x-cif cif -chemical/x-cmdf cmdf -chemical/x-cml cml -chemical/x-compass cpa -chemical/x-crossfire bsd -chemical/x-csml csml csm -chemical/x-ctx ctx -chemical/x-cxf cxf cef -#chemical/x-daylight-smiles smi -chemical/x-embl-dl-nucleotide emb embl -chemical/x-galactic-spc spc -chemical/x-gamess-input inp gam gamin -chemical/x-gaussian-checkpoint fch fchk -chemical/x-gaussian-cube cub -chemical/x-gaussian-input gau gjc gjf -chemical/x-gaussian-log gal -chemical/x-gcg8-sequence gcg -chemical/x-genbank gen -chemical/x-hin hin -chemical/x-isostar istr ist -chemical/x-jcamp-dx jdx dx -chemical/x-kinemage kin -chemical/x-macmolecule mcm -chemical/x-macromodel-input mmd mmod -chemical/x-mdl-molfile mol -chemical/x-mdl-rdfile rd -chemical/x-mdl-rxnfile rxn -chemical/x-mdl-sdfile sd sdf -chemical/x-mdl-tgf tgf -#chemical/x-mif mif -chemical/x-mmcif mcif -chemical/x-mol2 mol2 -chemical/x-molconn-Z b -chemical/x-mopac-graph gpt -chemical/x-mopac-input mop mopcrt mpc dat zmt -chemical/x-mopac-out moo -chemical/x-mopac-vib mvb -chemical/x-ncbi-asn1 asn -chemical/x-ncbi-asn1-ascii prt ent -chemical/x-ncbi-asn1-binary val aso -chemical/x-ncbi-asn1-spec asn -chemical/x-pdb pdb ent -chemical/x-rosdal ros -chemical/x-swissprot sw -chemical/x-vamas-iso14976 vms -chemical/x-vmd vmd -chemical/x-xtel xtel -chemical/x-xyz xyz - -image/cgm -image/g3fax -image/gif gif -image/ief ief -image/jpeg jpeg jpg jpe -image/naplps -image/pcx pcx -image/png png -image/prs.btif -image/prs.pti -image/svg+xml svg svgz -image/tiff tiff tif -image/vnd.cns.inf2 -image/vnd.djvu djvu djv -image/vnd.dwg -image/vnd.dxf -image/vnd.fastbidsheet -image/vnd.fpx -image/vnd.fst -image/vnd.fujixerox.edmics-mmr -image/vnd.fujixerox.edmics-rlc -image/vnd.mix -image/vnd.net-fpx -image/vnd.svf -image/vnd.wap.wbmp wbmp -image/vnd.xiff -image/x-cmu-raster ras -image/x-coreldraw cdr -image/x-coreldrawpattern pat -image/x-coreldrawtemplate cdt -image/x-corelphotopaint cpt -image/x-icon ico -image/x-jg art -image/x-jng jng -image/x-ms-bmp bmp -image/x-photoshop psd -image/x-portable-anymap pnm -image/x-portable-bitmap pbm -image/x-portable-graymap pgm -image/x-portable-pixmap ppm -image/x-rgb rgb -image/x-xbitmap xbm -image/x-xpixmap xpm -image/x-xwindowdump xwd - -inode/chardevice -inode/blockdevice -inode/directory-locked -inode/directory -inode/fifo -inode/socket - -message/delivery-status -message/disposition-notification -message/external-body -message/http -message/s-http -message/news -message/partial -message/rfc822 - -model/iges igs iges -model/mesh msh mesh silo -model/vnd.dwf -model/vnd.flatland.3dml -model/vnd.gdl -model/vnd.gs-gdl -model/vnd.gtw -model/vnd.mts -model/vnd.vtu -model/vrml wrl vrml - -multipart/alternative -multipart/appledouble -multipart/byteranges -multipart/digest -multipart/encrypted -multipart/form-data -multipart/header-set -multipart/mixed -multipart/parallel -multipart/related -multipart/report -multipart/signed -multipart/voice-message - -text/calendar ics icz -text/comma-separated-values csv -text/css css -text/directory -text/english -text/enriched -text/h323 323 -text/html html htm shtml -text/iuls uls -text/mathml mml -text/parityfec -text/plain asc txt text diff pot sql -text/prs.lines.tag -text/rfc822-headers -text/richtext rtx -text/rtf rtf -text/scriptlet sct wsc -text/t140 -text/texmacs tm ts -text/tab-separated-values tsv -text/uri-list -text/vnd.abc -text/vnd.curl -text/vnd.DMClientScript -text/vnd.flatland.3dml -text/vnd.fly -text/vnd.fmi.flexstor -text/vnd.in3d.3dml -text/vnd.in3d.spot -text/vnd.IPTC.NewsML -text/vnd.IPTC.NITF -text/vnd.latex-z -text/vnd.motorola.reflex -text/vnd.ms-mediapackage -text/vnd.sun.j2me.app-descriptor jad -text/vnd.wap.si -text/vnd.wap.sl -text/vnd.wap.wml wml -text/vnd.wap.wmlscript wmls -text/x-bibtex bib -text/x-boo boo -text/x-c++hdr h++ hpp hxx hh -text/x-c++src c++ cpp cxx cc -text/x-chdr h -text/x-component htc -text/x-crontab -text/x-csh csh -text/x-csrc c -text/x-dsrc d -text/x-haskell hs -text/x-java java -text/x-literate-haskell lhs -text/x-makefile -text/x-moc moc -text/x-pascal p pas -text/x-pcs-gcd gcd -text/x-perl pl pm -text/x-python py -text/x-server-parsed-html -text/x-setext etx -text/x-sh sh -text/x-tcl tcl tk -text/x-tex tex ltx sty cls -text/x-vcalendar vcs -text/x-vcard vcf - -video/dl dl -video/dv dif dv -video/fli fli -video/gl gl -video/mpeg mpeg mpg mpe -video/mp4 mp4 -video/quicktime qt mov -video/mp4v-es -video/parityfec -video/pointer -video/vnd.fvt -video/vnd.motorola.video -video/vnd.motorola.videop -video/vnd.mpegurl mxu -video/vnd.mts -video/vnd.nokia.interleaved-multimedia -video/vnd.vivo -video/x-la-asf lsf lsx -video/x-mng mng -video/x-ms-asf asf asx -video/x-ms-wm wm -video/x-ms-wmv wmv -video/x-ms-wmx wmx -video/x-ms-wvx wvx -video/x-msvideo avi -video/x-sgi-movie movie - -x-conference/x-cooltalk ice - -x-world/x-vrml vrm vrml wrl diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/osgi-debug.options b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/osgi-debug.options deleted file mode 100644 index 32ffd8739..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/etc/osgi-debug.options +++ /dev/null @@ -1,95 +0,0 @@ -#### Debugging options for org.eclipse.osgi - -# Turn on general debugging for org.eclipse.osgi -org.eclipse.osgi/debug=true -# Prints out class loading debug information -org.eclipse.osgi/debug/loader=false -# Prints out event (FrameworkEvent/BundleEvent/ServiceEvent) and listener debug information -org.eclipse.osgi/debug/events=false -# Prints out OSGi service debug information (registration/getting/ungetting etc.) -org.eclipse.osgi/debug/services=false -# Prints out bundle manifest parsing debug information -org.eclipse.osgi/debug/manifest=false -# Prints out LDAP filter debug information -org.eclipse.osgi/debug/filter=false -# Prints out security (PermissionAdmin service) debug information -org.eclipse.osgi/debug/security=false -# Prints out start level service debug information -org.eclipse.osgi/debug/startlevel=true -# Prints out package admin service debug information -org.eclipse.osgi/debug/packageadmin=false -# Prints out timing information for bundle activation -org.eclipse.osgi/debug/bundleTime=false -# Debug the loading of message bundles -org.eclipse.osgi/debug/messageBundles=false - -# Eclipse adaptor options -org.eclipse.osgi/eclipseadaptor/debug = false -org.eclipse.osgi/eclipseadaptor/debug/location = false -org.eclipse.osgi/eclipseadaptor/debug/platformadmin=false -org.eclipse.osgi/eclipseadaptor/debug/platformadmin/resolver=false -org.eclipse.osgi/eclipseadaptor/converter/debug = false - -### OSGi resolver options -# Turns on debugging for the resolver -org.eclipse.osgi/resolver/debug = false -# Prints out wiring information after the resolver has completed the resolve process -org.eclipse.osgi/resolver/wiring = false -# Prints out Import-Package information -org.eclipse.osgi/resolver/imports = false -# Prints out Require-Bundle information -org.eclipse.osgi/resolver/requires = false -# Prints out package grouping information form the "uses" clause -org.eclipse.osgi/resolver/grouping = false -# Prints out cycle information -org.eclipse.osgi/resolver/cycles = false -# Prints out Eclipse-GenericRequire information -org.eclipse.osgi/resolver/generics = false - -#### Profile settings -org.eclipse.osgi/profile/startup = false -org.eclipse.osgi/profile/benchmark = false -org.eclipse.osgi/profile/debug = true - -# Override the default implemenation -org.eclipse.osgi/profile/impl = org.eclipse.osgi.internal.profile.DefaultProfileLogger - -# Append all profile messages to the filename specified -org.eclipse.osgi/defaultprofile/logfilename = - -# Output all profile log messages synchronously to the jvm console. -# By default, all log messages are cached until the log buffer is -# requested. -org.eclipse.osgi/defaultprofile/logsynchronously = false - -# Specify the size of the default profile implementation log buffer. -org.eclipse.osgi/defaultprofile/buffersize = 256 - -#### Monitoring settings -# monitor class loading -org.eclipse.osgi/monitor/classes=false - -# monitor bundle activation -org.eclipse.osgi/monitor/activation=false - -# monitor resource bundle (*.properties) loading -org.eclipse.osgi/monitor/resources=false - - -#### Trace settings -# trace class loading - snapshot the execution stack when a class is loaded -org.eclipse.osgi/trace/classLoading=false - -# trace location - file in which execution traces are written -org.eclipse.osgi/trace/filename=runtime.traces - -# trace filters - Java properties file defining which classes should -# be traced (if trace/classLoading is true) -# File format: -# plugins= -# packages= -# Note that there may be many 'plugins' and 'packages' lines in one file. -org.eclipse.osgi/trace/filters=trace.properties - -# trace bundle activation - snapshot the execution stack when a bundle is activated -org.eclipse.osgi/trace/activation=false diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/log4j.properties b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/log4j.properties deleted file mode 100644 index 9cff0ddf7..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/log4j.properties +++ /dev/null @@ -1,165 +0,0 @@ -# -# Copyright 2009 WSO2, Inc. (http://wso2.com) -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -# -# This is the log4j configuration file used by WSO2 Carbon -# -# IMPORTANT : Please do not remove or change the names of any -# of the Appenders defined here. The layout pattern & log file -# can be changed using the WSO2 Carbon Management Console, and those -# settings will override the settings in this file. -# - -log4j.rootLogger=INFO, CARBON_CONSOLE, CARBON_LOGFILE, CARBON_MEMORY, CARBON_SYS_LOG - -log4j.logger.AUDIT_LOG=INFO, AUDIT_LOGFILE -log4j.logger.org.apache.axis2.wsdl.codegen.writer.PrettyPrinter=ERROR, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.axis2.clustering=INFO, CARBON_CONSOLE, CARBON_LOGFILE -log4j.logger.org.apache=INFO, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.catalina=WARN -log4j.logger.org.apache.tomcat=WARN -log4j.logger.org.wso2.carbon.apacheds=WARN -log4j.logger.org.apache.directory.server.ldap=ERROR -log4j.logger.org.apache.directory.server.core.event=WARN -log4j.logger.com.atomikos=INFO,ATOMIKOS -log4j.logger.org.quartz=WARN -log4j.logger.org.apache.jackrabbit.webdav=WARN -log4j.logger.org.apache.juddi=ERROR -log4j.logger.org.apache.commons.digester.Digester=WARN -log4j.logger.org.apache.jasper.compiler.TldLocationsCache=WARN -log4j.logger.org.apache.qpid=WARN -log4j.logger.org.apache.qpid.server.Main=INFO -log4j.logger.qpid.message=WARN -log4j.logger.qpid.message.broker.listening=INFO -log4j.logger.org.apache.tiles=WARN -log4j.logger.org.apache.commons.httpclient=ERROR -log4j.logger.org.apache.coyote=WARN -log4j.logger.org.apache.solr=ERROR -log4j.logger.me.prettyprint.cassandra.hector.TimingLogger=ERROR -log4j.logger.org.wso2=INFO -log4j.logger.org.apache.axis2.enterprise=FATAL, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.opensaml.xml=WARN, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.directory.shared.ldap=WARN, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.directory.server.ldap.handlers=WARN, CARBON_LOGFILE, CARBON_MEMORY -#Following are to remove false error messages from startup (IS) -log4j.logger.org.apache.directory.shared.ldap.entry.DefaultServerAttribute=FATAL, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.directory.server.core.DefaultDirectoryService=ERROR, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.directory.shared.ldap.ldif.LdifReader=ERROR, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.directory.server.ldap.LdapProtocolHandler=ERROR, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.directory.server.core=ERROR, CARBON_LOGFILE, CARBON_MEMORY -log4j.logger.org.apache.directory.server.ldap.LdapSession=ERROR, CARBON_LOGFILE, CARBON_MEMORY -#Hive Related Log configurations -log4j.logger.DataNucleus=ERROR -log4j.logger.Datastore=ERROR -log4j.logger.Datastore.Schema=ERROR -log4j.logger.JPOX.Datastore=ERROR -log4j.logger.JPOX.Plugin=ERROR -log4j.logger.JPOX.MetaData=ERROR -log4j.logger.JPOX.Query=ERROR -log4j.logger.JPOX.General=ERROR -log4j.logger.JPOX.Enhancer=ERROR -log4j.logger.org.apache.hadoop.hive=WARN -log4j.logger.hive=WARN -log4j.logger.ExecMapper=WARN -log4j.logger.ExecReducer=WARN -log4j.logger.net.sf.ehcache.config.ConfigurationFactory=ERROR - -log4j.logger.trace.messages=TRACE,CARBON_TRACE_LOGFILE - -log4j.additivity.org.apache.axis2.clustering=false -log4j.additivity.com.atomikos=false -log4j.additivity.org.apache=false - -# CARBON_CONSOLE is set to be a ConsoleAppender using a PatternLayout. -log4j.appender.CARBON_CONSOLE=org.wso2.carbon.utils.logging.appenders.CarbonConsoleAppender -log4j.appender.CARBON_CONSOLE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout -# ConversionPattern will be overridden by the configuration setting in the DB -log4j.appender.CARBON_CONSOLE.layout.ConversionPattern=[%d] %P%5p {%c} - %x %m%n -log4j.appender.CARBON_CONSOLE.layout.TenantPattern=%U%@%D[%T] -log4j.appender.CARBON_CONSOLE.threshold=DEBUG - -# CARBON_MEMORY is set to be a MemoryAppender using a PatternLayout. -log4j.appender.CARBON_MEMORY=org.wso2.carbon.utils.logging.appenders.MemoryAppender -log4j.appender.CARBON_MEMORY.layout=org.apache.log4j.PatternLayout -log4j.appender.CARBON_MEMORY.bufferSize=200 -# ConversionPattern will be overridden by the configuration setting in the DB -#log4j.appender.CARBON_MEMORY.layout.ConversionPattern=[%d] %5p - %x %m {%c}%n -log4j.appender.CARBON_MEMORY.layout.ConversionPattern=[%d] %5p {%c} - %x %m %n -log4j.appender.CARBON_MEMORY.threshold=DEBUG - - -# CARBON_LOGFILE is set to be a DailyRollingFileAppender using a PatternLayout. -log4j.appender.CARBON_LOGFILE=org.wso2.carbon.utils.logging.appenders.CarbonDailyRollingFileAppender -# Log file will be overridden by the configuration setting in the DB -# This path should be relative to WSO2 Carbon Home -log4j.appender.CARBON_LOGFILE.File=${carbon.home}/repository/logs/${instance.log}/wso2carbon${instance.log}.log -log4j.appender.CARBON_LOGFILE.Append=true -log4j.appender.CARBON_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout -# ConversionPattern will be overridden by the configuration setting in the DB -log4j.appender.CARBON_LOGFILE.layout.ConversionPattern=TID: [%T] [%S] [%d] %P%5p {%c} - %x %m %n -log4j.appender.CARBON_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S] -log4j.appender.CARBON_LOGFILE.threshold=DEBUG - -log4j.appender.CARBON_SYS_LOG = org.apache.log4j.net.SyslogAppender -log4j.appender.CARBON_SYS_LOG.layout=org.apache.log4j.PatternLayout -log4j.appender.CARBON_SYS_LOG.layout.ConversionPattern=[%d] %5p {%c} - %x %m %n -log4j.appender.CARBON_SYS_LOG.SyslogHost=localhost -log4j.appender.CARBON_SYS_LOG.Facility=USER -log4j.appender.CARBON_SYS_LOG.threshold=DEBUG - -# LOGEVENT is set to be a LogEventAppender using a PatternLayout to send logs to LOGEVENT -log4j.appender.LOGEVENT=org.wso2.carbon.logging.service.appender.LogEventAppender -log4j.appender.LOGEVENT.url=tcp://10.100.3.103:7611 -log4j.appender.LOGEVENT.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout -log4j.appender.LOGEVENT.columnList=%T,%S,%A,%d,%c,%p,%m,%H,%I,%Stacktrace -log4j.appender.LOGEVENT.userName=admin -log4j.appender.LOGEVENT.password=admin -#log4j.appender.LOGEVENT.password=secretAlias:Log4j.Appender.LOGEVENT.Password - -# Appender config to CARBON_TRACE_LOGFILE -log4j.appender.CARBON_TRACE_LOGFILE=org.apache.log4j.DailyRollingFileAppender -log4j.appender.CARBON_TRACE_LOGFILE.File=${carbon.home}/repository/logs/${instance.log}/wso2carbon-trace-messages${instance.log}.log -log4j.appender.CARBON_TRACE_LOGFILE.Append=true -log4j.appender.CARBON_TRACE_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout -log4j.appender.CARBON_TRACE_LOGFILE.layout.ConversionPattern=[%d] %P%5p {%c} - %x %m %n -log4j.appender.CARBON_TRACE_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S] -log4j.appender.CARBON_TRACE_LOGFILE.threshold=TRACE -log4j.additivity.trace.messages=false - -# Appender config to AUDIT_LOGFILE -log4j.appender.AUDIT_LOGFILE=org.apache.log4j.DailyRollingFileAppender -log4j.appender.AUDIT_LOGFILE.File=${carbon.home}/repository/logs/audit.log -log4j.appender.AUDIT_LOGFILE.Append=true -log4j.appender.AUDIT_LOGFILE.layout=org.wso2.carbon.utils.logging.TenantAwarePatternLayout -log4j.appender.AUDIT_LOGFILE.layout.ConversionPattern=[%d] %P%5p {%c}- %x %m %n -log4j.appender.AUDIT_LOGFILE.layout.TenantPattern=%U%@%D [%T] [%S] -log4j.appender.AUDIT_LOGFILE.threshold=INFO -log4j.additivity.AUDIT_LOG=false - -# Appender config to send Atomikos transaction logs to new log file tm.out. -log4j.appender.ATOMIKOS = org.apache.log4j.RollingFileAppender -log4j.appender.ATOMIKOS.File = repository/logs/tm.out -log4j.appender.ATOMIKOS.Append = true -log4j.appender.ATOMIKOS.layout = org.apache.log4j.PatternLayout -log4j.appender.ATOMIKOS.layout.ConversionPattern=%p %t %c - %m%n - -# This file is used to override the default logger settings, and is used to remove unwanted logs from Shindig appearing on the console. - -# Specification of Handler used by Console Logger -handlers=java.util.logging.ConsoleHandler - -# Replacing default INFO level with SEVERE -java.util.logging.ConsoleHandler.level=SEVERE diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/registry.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/registry.xml deleted file mode 100644 index c16502090..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/registry.xml +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - wso2registry - false - true - / - - - jdbc:h2:./target/databasetest/CARBON_TEST - - org.h2.Driver - 80 - 60000 - 5 - - - - - - - - - - - - false - - - - true - true - true - true - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/security/authenticators.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/security/authenticators.xml deleted file mode 100644 index 01cd4c98c..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/security/authenticators.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - 5 - - - - - 10 - - /carbon/admin/login.jsp - carbonServer - https://localhost:9443/samlsso - urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/carbon/META-INF/context.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/carbon/META-INF/context.xml deleted file mode 100644 index 04f622e3e..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/carbon/META-INF/context.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - WEB-INF/web.xml - - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/carbon/WEB-INF/web.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/carbon/WEB-INF/web.xml deleted file mode 100644 index 52f88eb30..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/carbon/WEB-INF/web.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - - bridgeservlet - Carbon Bridge Servlet - Carbon Bridge Servlet - org.wso2.carbon.tomcat.ext.servlet.DelegationServlet - - 1 - - - bridgeservlet - /* - - - - bridgeservlet - *.jsp - - - - - CharsetFilter - org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter - - requestEncoding - UTF-8 - - - - - CharsetFilter - /* - - - - 15 - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/catalina-server.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/catalina-server.xml deleted file mode 100644 index 834792930..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/catalina-server.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/tomcat-users.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/tomcat-users.xml deleted file mode 100644 index 7ef7dbb0a..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/tomcat-users.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/web.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/web.xml deleted file mode 100644 index 765865b47..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/tomcat/web.xml +++ /dev/null @@ -1,1220 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - default - org.apache.catalina.servlets.DefaultServlet - - debug - 0 - - - sendfileSize - -1 - - - listings - false - - 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jsp - org.apache.jasper.servlet.JspServlet - - fork - false - - - xpoweredBy - false - - 3 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jsp - *.jsp - - - - jsp - *.jspx - - - - default - / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 30 - - - - - - - - - - - - abs - audio/x-mpeg - - - ai - application/postscript - - - aif - audio/x-aiff - - - aifc - audio/x-aiff - - - aiff - audio/x-aiff - - - aim - application/x-aim - - - art - image/x-jg - - - asf - video/x-ms-asf - - - asx - video/x-ms-asf - - - au - audio/basic - - - avi - video/x-msvideo - - - avx - video/x-rad-screenplay - - - bcpio - application/x-bcpio - - - bin - application/octet-stream - - - bmp - image/bmp - - - body - text/html - - - cdf - application/x-cdf - - - cer - application/x-x509-ca-cert - - - class - application/java - - - cpio - application/x-cpio - - - csh - application/x-csh - - - css - text/css - - - dib - image/bmp - - - doc - application/msword - - - dtd - application/xml-dtd - - - dv - video/x-dv - - - dvi - application/x-dvi - - - eps - application/postscript - - - etx - text/x-setext - - - exe - application/octet-stream - - - gif - image/gif - - - gtar - application/x-gtar - - - gz - application/x-gzip - - - hdf - application/x-hdf - - - hqx - application/mac-binhex40 - - - htc - text/x-component - - - htm - text/html - - - html - text/html - - - ief - image/ief - - - jad - text/vnd.sun.j2me.app-descriptor - - - jar - application/java-archive - - - java - text/plain - - - jnlp - application/x-java-jnlp-file - - - jpe - image/jpeg - - - jpeg - image/jpeg - - - jpg - image/jpeg - - - js - application/javascript - - - jsf - text/plain - - - jspf - text/plain - - - kar - audio/x-midi - - - latex - application/x-latex - - - m3u - audio/x-mpegurl - - - mac - image/x-macpaint - - - man - application/x-troff-man - - - mathml - application/mathml+xml - - - me - application/x-troff-me - - - mid - audio/x-midi - - - midi - audio/x-midi - - - mif - application/x-mif - - - mov - video/quicktime - - - movie - video/x-sgi-movie - - - mp1 - audio/x-mpeg - - - mp2 - audio/x-mpeg - - - mp3 - audio/x-mpeg - - - mp4 - video/mp4 - - - mpa - audio/x-mpeg - - - mpe - video/mpeg - - - mpeg - video/mpeg - - - mpega - audio/x-mpeg - - - mpg - video/mpeg - - - mpv2 - video/mpeg2 - - - ms - application/x-wais-source - - - nc - application/x-netcdf - - - oda - application/oda - - - - odb - application/vnd.oasis.opendocument.database - - - - odc - application/vnd.oasis.opendocument.chart - - - - odf - application/vnd.oasis.opendocument.formula - - - - odg - application/vnd.oasis.opendocument.graphics - - - - odi - application/vnd.oasis.opendocument.image - - - - odm - application/vnd.oasis.opendocument.text-master - - - - odp - application/vnd.oasis.opendocument.presentation - - - - ods - application/vnd.oasis.opendocument.spreadsheet - - - - odt - application/vnd.oasis.opendocument.text - - - - otg - application/vnd.oasis.opendocument.graphics-template - - - - oth - application/vnd.oasis.opendocument.text-web - - - - otp - application/vnd.oasis.opendocument.presentation-template - - - - ots - application/vnd.oasis.opendocument.spreadsheet-template - - - - ott - application/vnd.oasis.opendocument.text-template - - - - ogx - application/ogg - - - ogv - video/ogg - - - oga - audio/ogg - - - ogg - audio/ogg - - - spx - audio/ogg - - - flac - audio/flac - - - anx - application/annodex - - - axa - audio/annodex - - - axv - video/annodex - - - xspf - application/xspf+xml - - - pbm - image/x-portable-bitmap - - - pct - image/pict - - - pdf - application/pdf - - - pgm - image/x-portable-graymap - - - pic - image/pict - - - pict - image/pict - - - pls - audio/x-scpls - - - png - image/png - - - pnm - image/x-portable-anymap - - - pnt - image/x-macpaint - - - ppm - image/x-portable-pixmap - - - ppt - application/vnd.ms-powerpoint - - - pps - application/vnd.ms-powerpoint - - - ps - application/postscript - - - psd - image/x-photoshop - - - qt - video/quicktime - - - qti - image/x-quicktime - - - qtif - image/x-quicktime - - - ras - image/x-cmu-raster - - - rdf - application/rdf+xml - - - rgb - image/x-rgb - - - rm - application/vnd.rn-realmedia - - - roff - application/x-troff - - - rtf - application/rtf - - - rtx - text/richtext - - - sh - application/x-sh - - - shar - application/x-shar - - - - smf - audio/x-midi - - - sit - application/x-stuffit - - - snd - audio/basic - - - src - application/x-wais-source - - - sv4cpio - application/x-sv4cpio - - - sv4crc - application/x-sv4crc - - - svg - image/svg+xml - - - svgz - image/svg+xml - - - swf - application/x-shockwave-flash - - - t - application/x-troff - - - tar - application/x-tar - - - tcl - application/x-tcl - - - tex - application/x-tex - - - texi - application/x-texinfo - - - texinfo - application/x-texinfo - - - tif - image/tiff - - - tiff - image/tiff - - - tr - application/x-troff - - - tsv - text/tab-separated-values - - - txt - text/plain - - - ulw - audio/basic - - - ustar - application/x-ustar - - - vxml - application/voicexml+xml - - - xbm - image/x-xbitmap - - - xht - application/xhtml+xml - - - xhtml - application/xhtml+xml - - - xls - application/vnd.ms-excel - - - xml - application/xml - - - xpm - image/x-xpixmap - - - xsl - application/xml - - - xslt - application/xslt+xml - - - xul - application/vnd.mozilla.xul+xml - - - xwd - image/x-xwindowdump - - - vsd - application/x-visio - - - wav - audio/x-wav - - - - wbmp - image/vnd.wap.wbmp - - - - wml - text/vnd.wap.wml - - - - wmlc - application/vnd.wap.wmlc - - - - wmls - text/vnd.wap.wmlscript - - - - wmlscriptc - application/vnd.wap.wmlscriptc - - - wmv - video/x-ms-wmv - - - wrl - x-world/x-vrml - - - wspolicy - application/wspolicy+xml - - - Z - application/x-compress - - - z - application/x-compress - - - zip - application/zip - - - - - - - - - - - - - - - - - - index.html - index.htm - index.jsp - - - \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/user-mgt.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/user-mgt.xml deleted file mode 100644 index 7be83118a..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/carbon-home/repository/conf/user-mgt.xml +++ /dev/null @@ -1,380 +0,0 @@ - - - - - - true - admin - - admin - admin - - everyone - jdbc/WSO2CarbonDB - - - - - - - org.wso2.carbon.user.core.tenant.JDBCTenantManager - false - 100 - false - default - SHA-256 - true - true - true - false - ^[\S]{5,30}$ - Password length should be between 5 to 30 characters - - ^[\S]{5,30}$ - [a-zA-Z0-9._-|//]{3,30}$ - ^[\S]{3,30}$ - ^[^~!#$;%^*+={}\\|\\\\<>,\'\"]{3,30}$ - ^[\S]{3,30}$ - true - 100 - 100 - false - false - true - , - true - - - - - - - - - - - - - - - - - - - /permission - true - true - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/config/datasource/data-source-config.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/config/datasource/data-source-config.xml deleted file mode 100644 index 93253751a..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/config/datasource/data-source-config.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - jdbc:h2:mem:cdm-test-db;DB_CLOSE_ON_EXIT=FALSE;MVCC=true - org.h2.Driver - wso2carbon - wso2carbon - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/log4j.properties b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/log4j.properties deleted file mode 100644 index 96c79e944..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/log4j.properties +++ /dev/null @@ -1,36 +0,0 @@ -# -# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# WSO2 Inc. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - - -# For the general syntax of property based configuration files see the -# documenation of org.apache.log4j.PropertyConfigurator. - -# The root category uses the appender called A1. Since no priority is -# specified, the root category assumes the default priority for root -# which is DEBUG in log4j. The root category is the only category that -# has a default priority. All other categories need not be assigned a -# priority in which case they inherit their priority from the -# hierarchy. - -#log4j.rootLogger=DEBUG, stdout -log4j.rootLogger=INFO, stdout - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%m%n -#log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c %x - %m%n diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/sql/h2.sql b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/sql/h2.sql deleted file mode 100644 index f8c7785e0..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/sql/h2.sql +++ /dev/null @@ -1,574 +0,0 @@ -CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( - ID INT AUTO_INCREMENT NOT NULL, - NAME VARCHAR(300) NULL DEFAULT NULL, - DEVICE_TYPE_META VARCHAR(20000) NULL DEFAULT NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, - PROVIDER_TENANT_ID INTEGER DEFAULT 0, - SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS DM_GROUP ( - ID INTEGER AUTO_INCREMENT NOT NULL, - GROUP_NAME VARCHAR(100) DEFAULT NULL, - STATUS VARCHAR(50) DEFAULT NULL, - DESCRIPTION TEXT DEFAULT NULL, - OWNER VARCHAR(255) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS DM_ROLE_GROUP_MAP ( - ID INTEGER AUTO_INCREMENT NOT NULL, - GROUP_ID INTEGER DEFAULT NULL, - ROLE VARCHAR(45) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID), - CONSTRAINT fk_DM_ROLE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) - REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE ( - ID INTEGER auto_increment NOT NULL, - DESCRIPTION TEXT DEFAULT NULL, - NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INT(11) DEFAULT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID), - CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID) - REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT uk_DM_DEVICE UNIQUE (NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_PROPERTIES ( - DEVICE_TYPE_NAME VARCHAR(300) NOT NULL, - DEVICE_IDENTIFICATION VARCHAR(300) NOT NULL, - PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID VARCHAR(100), - PRIMARY KEY (DEVICE_TYPE_NAME, DEVICE_IDENTIFICATION, PROPERTY_NAME, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS GROUP_PROPERTIES ( - GROUP_ID INTEGER NOT NULL, - PROPERTY_NAME VARCHAR(100) DEFAULT 0, - PROPERTY_VALUE VARCHAR(100) DEFAULT NULL, - TENANT_ID VARCHAR(100), - PRIMARY KEY (GROUP_ID, PROPERTY_NAME, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER DEFAULT NULL, - GROUP_ID INTEGER DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID), - CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) - REFERENCES DM_GROUP (ID) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS DM_OPERATION ( - ID INTEGER AUTO_INCREMENT NOT NULL, - TYPE VARCHAR(50) NOT NULL, - CREATED_TIMESTAMP TIMESTAMP NOT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, - OPERATION_CODE VARCHAR(1000) NOT NULL, - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS DM_CONFIG_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - OPERATION_CONFIG BLOB DEFAULT NULL, - ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_COMMAND_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED BOOLEAN NOT NULL DEFAULT FALSE, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_command FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_POLICY_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION ( - OPERATION_ID INTEGER NOT NULL, - ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS BLOB DEFAULT NULL, - PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_profile FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, - OWNER VARCHAR(255) NOT NULL, - OWNERSHIP VARCHAR(45) DEFAULT NULL, - STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL, - DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL, - TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT uk_dm_device_enrolment UNIQUE (DEVICE_ID, OWNER, OWNERSHIP, TENANT_ID) -); - -CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( - ID INTEGER AUTO_INCREMENT NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - STATUS VARCHAR(50) NULL, - PUSH_NOTIFICATION_STATUS VARCHAR(50) NULL, - CREATED_TIMESTAMP INT NOT NULL, - UPDATED_TIMESTAMP INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES - DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_mapping_operation FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( - ID INTEGER AUTO_INCREMENT NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NOT NULL, - EN_OP_MAP_ID INTEGER NOT NULL, - OPERATION_RESPONSE LONGBLOB DEFAULT NULL, - RECEIVED_TIMESTAMP TIMESTAMP NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES - DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES - DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_dm_en_op_map_response FOREIGN KEY (EN_OP_MAP_ID) REFERENCES - DM_ENROLMENT_OP_MAPPING (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); - --- POLICY RELATED TABLES -- - -CREATE TABLE IF NOT EXISTS DM_PROFILE ( - ID INT NOT NULL AUTO_INCREMENT , - PROFILE_NAME VARCHAR(45) NOT NULL , - TENANT_ID INT NOT NULL , - DEVICE_TYPE VARCHAR(300) NOT NULL , - CREATED_TIME DATETIME NOT NULL , - UPDATED_TIME DATETIME NOT NULL , - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS DM_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - NAME VARCHAR(45) DEFAULT NULL , - DESCRIPTION VARCHAR(1000) NULL, - TENANT_ID INT(11) NOT NULL , - PROFILE_ID INT(11) NOT NULL , - OWNERSHIP_TYPE VARCHAR(45) NULL, - COMPLIANCE VARCHAR(100) NULL, - PRIORITY INT NOT NULL, - ACTIVE INT(2) NOT NULL, - UPDATED INT(1) NULL, - PRIMARY KEY (ID) , - CONSTRAINT FK_DM_PROFILE_DM_POLICY - FOREIGN KEY (PROFILE_ID ) - REFERENCES DM_PROFILE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - DEVICE_ID INT(11) NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, - DEVICE BLOB NOT NULL, - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , - CONSTRAINT FK_POLICY_DEVICE_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_DEVICE_DEVICE_POLICY - FOREIGN KEY (DEVICE_ID ) - REFERENCES DM_DEVICE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( - ID INT(11) NOT NULL , - DEVICE_TYPE VARCHAR(300) NOT NULL , - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , - CONSTRAINT FK_DEVICE_TYPE_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( - ID INT(11) NOT NULL AUTO_INCREMENT, - PROFILE_ID INT(11) NOT NULL, - FEATURE_CODE VARCHAR(100) NOT NULL, - DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INT(11) NOT NULL , - CONTENT BLOB NULL DEFAULT NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES - FOREIGN KEY (PROFILE_ID) - REFERENCES DM_PROFILE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( - ID INT(11) NOT NULL AUTO_INCREMENT , - ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INT(11) NOT NULL , - PRIMARY KEY (ID) , - CONSTRAINT FK_ROLE_POLICY_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( - ID INT NOT NULL AUTO_INCREMENT , - POLICY_ID INT NOT NULL , - USERNAME VARCHAR(45) NOT NULL , - PRIMARY KEY (ID) , - CONSTRAINT DM_POLICY_USER_POLICY - FOREIGN KEY (POLICY_ID ) - REFERENCES DM_POLICY (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( - ID INT NOT NULL AUTO_INCREMENT , - DEVICE_ID INT NOT NULL , - ENROLMENT_ID INT(11) NOT NULL, - POLICY_ID INT NOT NULL , - POLICY_CONTENT BLOB NULL , - TENANT_ID INT NOT NULL, - APPLIED TINYINT(1) NULL , - CREATED_TIME TIMESTAMP NULL , - UPDATED_TIME TIMESTAMP NULL , - APPLIED_TIME TIMESTAMP NULL , - PRIMARY KEY (ID) , - CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED - FOREIGN KEY (DEVICE_ID ) - REFERENCES DM_DEVICE (ID ) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_CRITERIA ( - ID INT NOT NULL AUTO_INCREMENT, - TENANT_ID INT NOT NULL, - NAME VARCHAR(50) NULL, - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( - ID INT NOT NULL AUTO_INCREMENT, - CRITERIA_ID INT NOT NULL, - POLICY_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_CRITERIA_POLICY_CRITERIA - FOREIGN KEY (CRITERIA_ID) - REFERENCES DM_CRITERIA (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_POLICY_POLICY_CRITERIA - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( - ID INT NOT NULL AUTO_INCREMENT, - POLICY_CRITERION_ID INT NOT NULL, - PROP_KEY VARCHAR(45) NULL, - PROP_VALUE VARCHAR(100) NULL, - CONTENT BLOB NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES - FOREIGN KEY (POLICY_CRITERION_ID) - REFERENCES DM_POLICY_CRITERIA (ID) - ON DELETE CASCADE - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( - ID INT NOT NULL AUTO_INCREMENT, - DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT(11) NOT NULL, - POLICY_ID INT NOT NULL, - TENANT_ID INT NOT NULL, - STATUS INT NULL, - LAST_SUCCESS_TIME TIMESTAMP NULL, - LAST_REQUESTED_TIME TIMESTAMP NULL, - LAST_FAILED_TIME TIMESTAMP NULL, - ATTEMPTS INT NULL, - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( - ID INT NOT NULL AUTO_INCREMENT, - POLICY_ID INT NOT NULL, - DEVICE_TYPE VARCHAR(300) NOT NULL , - TENANT_ID INT(11) NOT NULL, - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( - ID INT NOT NULL AUTO_INCREMENT, - COMPLIANCE_STATUS_ID INT NOT NULL, - TENANT_ID INT NOT NULL, - FEATURE_CODE VARCHAR(100) NOT NULL, - STATUS INT NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS - FOREIGN KEY (COMPLIANCE_STATUS_ID) - REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_APPLICATION ( - ID INTEGER AUTO_INCREMENT NOT NULL, - NAME VARCHAR(150) NOT NULL, - APP_IDENTIFIER VARCHAR(150) NOT NULL, - PLATFORM VARCHAR(50) DEFAULT NULL, - CATEGORY VARCHAR(50) NULL, - VERSION VARCHAR(50) NULL, - TYPE VARCHAR(50) NULL, - LOCATION_URL VARCHAR(100) DEFAULT NULL, - IMAGE_URL VARCHAR(100) DEFAULT NULL, - APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, - IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID) -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - APPLICATION_ID INTEGER NOT NULL, - APP_PROPERTIES BLOB NULL, - MEMORY_USAGE INTEGER(10) NULL, - IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT fk_dm_application - FOREIGN KEY (APPLICATION_ID) - REFERENCES DM_APPLICATION (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_DM_APP_MAP_DM_ENROL - FOREIGN KEY (ENROLMENT_ID) - REFERENCES DM_ENROLMENT (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - --- POLICY RELATED TABLES FINISHED -- - --- NOTIFICATION TABLE -- -CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( - NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INTEGER NOT NULL, - OPERATION_ID INTEGER NULL, - TENANT_ID INTEGER NOT NULL, - STATUS VARCHAR(10) NULL, - DESCRIPTION VARCHAR(1000) NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, - PRIMARY KEY (NOTIFICATION_ID), - CONSTRAINT fk_dm_device_notification FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); --- NOTIFICATION TABLE END -- - -CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INT NULL, - ENROLMENT_ID INT NOT NULL, - KEY_FIELD VARCHAR(45) NULL, - VALUE_FIELD VARCHAR(1000) NULL, - PRIMARY KEY (ID), - CONSTRAINT DM_DEVICE_INFO_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT DM_DEVICE_INFO_DEVICE_ENROLLMENT - FOREIGN KEY (ENROLMENT_ID) - REFERENCES DM_ENROLMENT (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( - ID INTEGER AUTO_INCREMENT NOT NULL, - DEVICE_ID INT NULL, - ENROLMENT_ID INT NOT NULL, - LATITUDE DOUBLE NULL, - LONGITUDE DOUBLE NULL, - STREET1 VARCHAR(255) NULL, - STREET2 VARCHAR(45) NULL, - CITY VARCHAR(45) NULL, - ZIP VARCHAR(10) NULL, - STATE VARCHAR(45) NULL, - COUNTRY VARCHAR(45) NULL, - GEO_HASH VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT DM_DEVICE_LOCATION_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT DM_DEVICE_LOCATION_DM_ENROLLMENT - FOREIGN KEY (ENROLMENT_ID) - REFERENCES DM_ENROLMENT (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); -CREATE INDEX DM_DEVICE_LOCATION_GEO_hashx ON DM_DEVICE_LOCATION(GEO_HASH ASC); - -CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( - ID INT NOT NULL AUTO_INCREMENT, - DEVICE_ID INT NOT NULL, - ENROLMENT_ID INT NOT NULL, - DEVICE_MODEL VARCHAR(45) NULL, - VENDOR VARCHAR(45) NULL, - OS_VERSION VARCHAR(45) NULL, - OS_BUILD_DATE VARCHAR(100) NULL, - BATTERY_LEVEL DECIMAL(4) NULL, - INTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, - INTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, - EXTERNAL_TOTAL_MEMORY DECIMAL(30,3) NULL, - EXTERNAL_AVAILABLE_MEMORY DECIMAL(30,3) NULL, - CONNECTION_TYPE VARCHAR(50) NULL, - SSID VARCHAR(45) NULL, - CPU_USAGE DECIMAL(5) NULL, - TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, - AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INT(1) NULL, - UPDATE_TIMESTAMP BIGINT(15) NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE - FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_DM_ENROLMENT_DEVICE_DETAILS - FOREIGN KEY (ENROLMENT_ID) - REFERENCES DM_ENROLMENT (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); - --- POLICY AND DEVICE GROUP MAPPING -- -CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( - ID INT NOT NULL AUTO_INCREMENT, - DEVICE_GROUP_ID INT NOT NULL, - POLICY_ID INT NOT NULL, - TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_DM_DEVICE_GROUP_POLICY - FOREIGN KEY (DEVICE_GROUP_ID) - REFERENCES DM_GROUP (ID) - ON DELETE CASCADE - ON UPDATE CASCADE , - CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE CASCADE - ON UPDATE CASCADE -); --- END OF POLICY AND DEVICE GROUP MAPPING -- - --- DASHBOARD RELATED VIEWS -- -CREATE VIEW POLICY_COMPLIANCE_INFO AS -SELECT -DEVICE_INFO.DEVICE_ID, -DEVICE_INFO.DEVICE_IDENTIFICATION, -DEVICE_INFO.PLATFORM, -DEVICE_INFO.OWNERSHIP, -DEVICE_INFO.CONNECTIVITY_STATUS, -IFNULL(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID, -IFNULL(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS IS_COMPLIANT, -DEVICE_INFO.TENANT_ID -FROM -(SELECT -DM_DEVICE.ID AS DEVICE_ID, -DM_DEVICE.DEVICE_IDENTIFICATION, -DM_DEVICE_TYPE.NAME AS PLATFORM, -DM_ENROLMENT.OWNERSHIP, -DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, -DM_DEVICE.TENANT_ID -FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT -WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO -LEFT JOIN -(SELECT -DEVICE_ID, -POLICY_ID, -STATUS AS IS_COMPLIANT -FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO -ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID -ORDER BY DEVICE_INFO.DEVICE_ID; - -CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS -SELECT -DM_DEVICE.ID AS DEVICE_ID, -DM_DEVICE.DEVICE_IDENTIFICATION, -DM_DEVICE_DETAIL.DEVICE_MODEL, -DM_DEVICE_DETAIL.VENDOR, -DM_DEVICE_DETAIL.OS_VERSION, -DM_ENROLMENT.OWNERSHIP, -DM_ENROLMENT.OWNER, -DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, -DM_POLICY_COMPLIANCE_STATUS.POLICY_ID, -DM_DEVICE_TYPE.NAME AS PLATFORM, -DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE, -DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT, -DM_DEVICE.TENANT_ID -FROM -DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL -WHERE -DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND -DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND -DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND -DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND -DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID -ORDER BY TENANT_ID, DEVICE_ID; - --- END OF DASHBOARD RELATED VIEWS -- diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/testng.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/testng.xml deleted file mode 100644 index 2f25f2a58..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/testng.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/user-test/user-mgt-registry-test.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/user-test/user-mgt-registry-test.xml deleted file mode 100644 index d7468d13c..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/test/resources/user-test/user-mgt-registry-test.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - - true - admin - - admin - admin - - everyone - false - 500 - jdbc:h2:target/databasetest/CARBON_TEST - org.h2.Driver - 50 - 60000 - 5 - - - [\S]{5,30}$ - [\\S]{5,30} - SELECT * FROM UM_USER WHERE UM_USER_NAME=? AND UM_TENANT_ID=? - - - - - - - - - - - - - - - - SHA-256 - true - false - false - wso2.com - true - 100 - - - INSERT INTO UM_ROLE (UM_ROLE_NAME, UM_TENANT_ID) VALUES (?, ?) - - - - - - - - - - - - - - - - - org.wso2.carbon.user.core.tenant.JDBCTenantManager - - - true - - - - login - manage-configuration - manage-security - upload-services - manage-services - manage-lc-configuration - manage-mediation - monitor-system - delegate-identity - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/pom.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/pom.xml deleted file mode 100644 index 76e1148e8..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/pom.xml +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt-plugins - siddhi-extensions - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.extension.siddhi.execution.json - bundle - WSO2 Siddhi Execution Extension - Json - http://wso2.org - - - - org.wso2.siddhi - siddhi-core - - - org.wso2.siddhi - siddhi-query-api - - - log4j - log4j - - - org.json.wso2 - json - - - org.testng - testng - test - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${wso2.maven.compiler.source} - ${wso2.maven.compiler.target} - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - - org.wso2.extension.siddhi.execution.json, - org.wso2.extension.siddhi.execution.json.* - - - org.json;version="${orbit.version.json.range}", - org.wso2.siddhi.core.*, - org.wso2.siddhi.query.api.*, - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - file:src/test/resources/log4j.properties - - - src/test/resources/testng.xml - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/java/org/wso2/extension/siddhi/execution/json/GetArrayFunctionExtension.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/java/org/wso2/extension/siddhi/execution/json/GetArrayFunctionExtension.java deleted file mode 100644 index 08712416e..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/java/org/wso2/extension/siddhi/execution/json/GetArrayFunctionExtension.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.execution.json; - -import org.json.JSONArray; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.executor.function.FunctionExecutor; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -/** - * getArray(elements..) - * Returns json array of elements as a string - * Accept Type(s): (STRING|INT|DOUBLE|FLOAT|OBJECT ..) - * Return Type(s): (STRING) - */ -public class GetArrayFunctionExtension extends FunctionExecutor { - - private Attribute.Type returnType = Attribute.Type.STRING; - - @Override - protected void init(ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length <= 0) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to json:getArray() function," + " required one or more, but found " - + attributeExpressionExecutors.length); - } - Attribute.Type inputType = attributeExpressionExecutors[0].getReturnType(); - for (int i = 1; i < attributeExpressionExecutors.length; i++) { - if (attributeExpressionExecutors[0].getReturnType() != inputType) { - throw new ExecutionPlanValidationException( - "Parameter types are inconsistent. All parameters should be same"); - } - } - } - - @Override - protected Object execute(Object[] data) { - - JSONArray jsonArray = new JSONArray(); - for (Object obj : data) { - jsonArray.put(obj); - } - return jsonArray.toString(); - } - - @Override - protected Object execute(Object data) { - return execute(new Object[]{data}); - } - - @Override - public void start() { - //Nothing to start - } - - @Override - public void stop() { - //Nothing to stop - } - - @Override - public Attribute.Type getReturnType() { - return returnType; - } - - @Override - public Object[] currentState() { - return null; //No need to maintain a state. - } - - @Override - public void restoreState(Object[] state) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/java/org/wso2/extension/siddhi/execution/json/GetPropertyFunctionExtension.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/java/org/wso2/extension/siddhi/execution/json/GetPropertyFunctionExtension.java deleted file mode 100644 index 6bb8ddd72..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/java/org/wso2/extension/siddhi/execution/json/GetPropertyFunctionExtension.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.execution.json; - -import org.json.JSONException; -import org.json.JSONObject; -import org.wso2.siddhi.core.config.ExecutionPlanContext; -import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; -import org.wso2.siddhi.core.executor.ExpressionExecutor; -import org.wso2.siddhi.core.executor.function.FunctionExecutor; -import org.wso2.siddhi.query.api.definition.Attribute; -import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; - -/** - * getProperty(json , propertyName) - * Returns the vale of the property from the given json json - * Accept Type(s): (STRING, STRING) - * Return Type(s): (STRING|INT|DOUBLE|FLOAT|OBJECT) - */ -public class GetPropertyFunctionExtension extends FunctionExecutor { - - private Attribute.Type returnType = Attribute.Type.STRING; - - @Override - protected void init(ExpressionExecutor[] attributeExpressionExecutors, - ExecutionPlanContext executionPlanContext) { - if (attributeExpressionExecutors.length != 2) { - throw new ExecutionPlanValidationException( - "Invalid no of arguments passed to json:getProperty() function," + " required 2, but found " - + attributeExpressionExecutors.length); - } - if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the first argument of json:getProperty() function, required " - + Attribute.Type.STRING + ", but found " + attributeExpressionExecutors[0].getReturnType() - .toString()); - } - if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { - throw new ExecutionPlanValidationException( - "Invalid parameter type found for the second argument of json:getProperty() function, required " - + Attribute.Type.STRING + ", but found " - + attributeExpressionExecutors[1].getReturnType().toString()); - } - } - - @Override - protected Object execute(Object[] data) { - if (data[0] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to json:getProperty() function." + - " First argument cannot be null"); - } - if (data[1] == null) { - throw new ExecutionPlanRuntimeException("Invalid input given to json:getProperty() function. " + - "Second argument cannot be null"); - } - String jsonString = (String) data[0]; - String property = (String) data[1]; - Object jsonObject; - try { - jsonObject = new JSONObject(jsonString).get(property); - return jsonObject == null ? null : jsonObject.toString(); - } catch (JSONException e) { - throw new ExecutionPlanRuntimeException("Cannot parse JSON String in json:getPeroperty() function. " + e); - } - } - - @Override - protected Object execute(Object data) { - return null; //Since the getProperty function takes in 2 parameters, this method does not get called. - // Hence,not implemented. - } - - @Override - public void start() { - //Nothing to start - } - - @Override - public void stop() { - //Nothing to stop - } - - @Override - public Attribute.Type getReturnType() { - return returnType; - } - - @Override - public Object[] currentState() { - return null; //No need to maintain a state. - } - - @Override - public void restoreState(Object[] state) { - //Since there's no need to maintain a state, nothing needs to be done here. - } -} - - diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/resources/json.siddhiext b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/resources/json.siddhiext deleted file mode 100644 index fa4336f4a..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/main/resources/json.siddhiext +++ /dev/null @@ -1,20 +0,0 @@ -# -# Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# WSO2 Inc. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -getProperty=org.wso2.extension.siddhi.execution.json.GetPropertyFunctionExtension -getArray=org.wso2.extension.siddhi.execution.json.GetArrayFunctionExtension \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/java/org/wso2/extension/siddhi/execution/json/ExtensionTestCase.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/java/org/wso2/extension/siddhi/execution/json/ExtensionTestCase.java deleted file mode 100644 index 761336a2d..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/java/org/wso2/extension/siddhi/execution/json/ExtensionTestCase.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.execution.json; - -import org.apache.log4j.Logger; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.siddhi.core.ExecutionPlanRuntime; -import org.wso2.siddhi.core.SiddhiManager; -import org.wso2.siddhi.core.event.Event; -import org.wso2.siddhi.core.query.output.callback.QueryCallback; -import org.wso2.siddhi.core.stream.input.InputHandler; -import org.wso2.siddhi.core.util.EventPrinter; -import org.wso2.extension.siddhi.execution.json.test.util.SiddhiTestHelper; - -import java.util.concurrent.atomic.AtomicInteger; - -public class ExtensionTestCase { - static final Logger log = Logger.getLogger(ExtensionTestCase.class); - private AtomicInteger count = new AtomicInteger(0); - private volatile boolean eventArrived; - - @BeforeClass - public void init() { - count.set(0); - eventArrived = false; - } - - @Test - public void testGetPropertyFunctionExtension() throws InterruptedException { - log.info("GetPropertyFunctionExtension TestCase"); - SiddhiManager siddhiManager = new SiddhiManager(); - - String inStreamDefinition = "define stream inputStream (payload string, id string, volume long);"; - String query = ("@info(name = 'query1') from inputStream select id, json:getProperty(payload, 'latitude') " - + "as latitude insert into outputStream;"); - ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); - - executionPlanRuntime.addCallback("query1", new QueryCallback() { - @Override - public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { - EventPrinter.print(timeStamp, inEvents, removeEvents); - for (Event event : inEvents) { - count.incrementAndGet(); - if (count.get() == 1) { - Assert.assertEquals("1.5", event.getData(1)); - eventArrived = true; - } - if (count.get() == 2) { - Assert.assertEquals("67.5", event.getData(1)); - eventArrived = true; - } - if (count.get() == 3) { - Assert.assertEquals("7.5", event.getData(1)); - eventArrived = true; - } - } - } - }); - - InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); - executionPlanRuntime.start(); - inputHandler.send(new Object[]{"{'latitude' : 1.5, 'longitude' : 78.5}","IBM",100l}); - inputHandler.send(new Object[]{"{'latitude' : 67.5, 'longitude' : 34.9}","WSO2", 200l}); - inputHandler.send(new Object[]{"{'latitude' : 7.5, 'longitude' : 44.9}", "XYZ", 200l}); - SiddhiTestHelper.waitForEvents(100, 3, count, 60000); - Assert.assertEquals(3, count.get()); - Assert.assertTrue(eventArrived); - executionPlanRuntime.shutdown(); - } - - @Test(dependsOnMethods = {"testGetPropertyFunctionExtension"}) - public void testGetArrayFunctionExtension() throws InterruptedException { - count.set(0); - eventArrived = false; - log.info("GetArrayFunctionExtension TestCase"); - SiddhiManager siddhiManager = new SiddhiManager(); - - String inStreamDefinition = "define stream inputStream (arg1 string, arg2 string);"; - String query = ("@info(name = 'query1') from inputStream select json:getArray(arg1, arg2) " - + "as array insert into outputStream;"); - - ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inStreamDefinition + query); - - executionPlanRuntime.addCallback("query1", new QueryCallback() { - @Override - public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { - EventPrinter.print(timeStamp, inEvents, removeEvents); - for (Event event : inEvents) { - count.incrementAndGet(); - if (count.get() == 1) { - eventArrived = true; - } - } - } - }); - - InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); - executionPlanRuntime.start(); - inputHandler.send(new Object[]{"Arg1","Arg2"}); - SiddhiTestHelper.waitForEvents(100, 1, count, 60000); - Assert.assertEquals(1, count.get()); - Assert.assertTrue(eventArrived); - executionPlanRuntime.shutdown(); - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/java/org/wso2/extension/siddhi/execution/json/test/util/SiddhiTestHelper.java b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/java/org/wso2/extension/siddhi/execution/json/test/util/SiddhiTestHelper.java deleted file mode 100644 index 9cfd6c307..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/java/org/wso2/extension/siddhi/execution/json/test/util/SiddhiTestHelper.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.extension.siddhi.execution.json.test.util; - -import java.util.concurrent.atomic.AtomicInteger; - -public class SiddhiTestHelper { - public static void waitForEvents(long sleepTime, int expectedCount, AtomicInteger actualCount, long timeout) throws InterruptedException { - long currentWaitTime = 0; - long startTime = System.currentTimeMillis(); - while ((actualCount.get() < expectedCount) && (currentWaitTime <= timeout)) { - Thread.sleep(sleepTime); - currentWaitTime = System.currentTimeMillis() - startTime; - } - } -} diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/resources/log4j.properties b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/resources/log4j.properties deleted file mode 100644 index 96c79e944..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/resources/log4j.properties +++ /dev/null @@ -1,36 +0,0 @@ -# -# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# WSO2 Inc. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - - -# For the general syntax of property based configuration files see the -# documenation of org.apache.log4j.PropertyConfigurator. - -# The root category uses the appender called A1. Since no priority is -# specified, the root category assumes the default priority for root -# which is DEBUG in log4j. The root category is the only category that -# has a default priority. All other categories need not be assigned a -# priority in which case they inherit their priority from the -# hierarchy. - -#log4j.rootLogger=DEBUG, stdout -log4j.rootLogger=INFO, stdout - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%m%n -#log4j.appender.stdout.layout.ConversionPattern=[%t] %-5p %c %x - %m%n diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/resources/testng.xml b/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/resources/testng.xml deleted file mode 100644 index 80918d253..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/src/test/resources/testng.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/pom.xml b/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/pom.xml deleted file mode 100644 index 6c1f686ea..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt-plugins - siddhi-extensions - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.gpl.siddhi.extension.geo.script - pom - GPL Siddhi Extension - Geo Script - http://wso2.org - - - - - maven-assembly-plugin - 2.5.5 - - ${project.artifactId}-${carbon.devicemgt.plugins.version} - false - - src/assembly/src.xml - - - - - create-archive - package - - single - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/assembly/src.xml b/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/assembly/src.xml deleted file mode 100644 index c6ab9a0bb..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/assembly/src.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - src - - zip - - false - ${basedir}/src - - - ${basedir}/src/main/resources/scripts - / - true - - - \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/org.wso2.gpl.siddhi.extension.geo.feature/pom.xml b/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/org.wso2.gpl.siddhi.extension.geo.feature/pom.xml deleted file mode 100644 index 539fbaae1..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/org.wso2.gpl.siddhi.extension.geo.feature/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - org.wso2.gpl.siddhi.extensions - siddhi-extension-gpl-geo-parent - 3.2.0 - ../pom.xml - - 4.0.0 - org.wso2.gpl.siddhi.extension.geo.feature - - pom - WSO2 GPL Carbon - Siddhi Geo Extension Feature - http://wso2.org - - - - org.wso2.orbit.org.geotools - gt-geojson - - - - - - - org.wso2.maven - carbon-p2-plugin - 1.5.4 - - - p2-feature-generation - package - - p2-feature-gen - - - org.wso2.gpl.siddhi.extension.geo - ../etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:true - - - - org.wso2.orbit.org.geotools:gt-geojson:${gt-geojson.version} - - - - - - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/org.wso2.orbit.org.geotools.gt-geojson/pom.xml b/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/org.wso2.orbit.org.geotools.gt-geojson/pom.xml deleted file mode 100644 index dc71eafad..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/org.wso2.orbit.org.geotools.gt-geojson/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - - 4.0.0 - - org.wso2.orbit.org.geotools - gt-geojson - 13.6.0.wso2v1 - - gt-geojson.wso2 - bundle - - This bundle will represent Stanford NLP Library. - - http://wso2.org - - - - GNU General Public License version 3 (GPLv3) - http://www.gnu.org/licenses/gpl-3.0.txt - - - - - - org.geotools - gt-geojson - ${geotools.version} - true - - - - - 13.6 - 13.6.0.wso2v1 - UTF-8 - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - - com.vividsolutions.*;version="1.13", - org.jdom.*;version="1.1.3", - javax.media.*;version="1.1.3", - org.geotools.*;-split-package:=merge-last;version="${geotools.export.version}" - - - !org.geotools.*, - org.json.simple.* - - - *;resolution:=optional - - - - - - - - - - geomajas-nexus - http://apps.geomajas.org/nexus/content/groups/public/ - - true - daily - ignore - - - - - - - wso2.gpl.releases - WSO2 GPL Maven Repository - http://maven.wso2.org/nexus/content/repositories/wso2gpl/ - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/pom.xml b/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/pom.xml deleted file mode 100644 index 707f05a5e..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/gpl-siddhi-geo-extention/pom.xml +++ /dev/null @@ -1,340 +0,0 @@ - - - - - - - org.wso2 - wso2 - 1 - - - 4.0.0 - - org.wso2.gpl.siddhi.extensions - siddhi-extension-gpl-geo-parent - 3.2.0 - pom - Siddhi Extension - Geo - WSO2 Siddhi Geo Extension - http://wso2.org - - - org.wso2.orbit.org.geotools.gt-geojson - org.wso2.gpl.siddhi.extension.geo.feature - - - - - GNU General Public License version 3 (GPLv3) - http://www.gnu.org/licenses/gpl-3.0.txt - - - - - https://github.com/wso2-gpl/siddhi-extensions.git - scm:git:https://github.com/wso2-gpl/siddhi-extensions.git - scm:git:https://github.com/wso2-gpl/siddhi-extensions.git - HEAD - - - - - - log4j - log4j - ${log4j.version} - - - - javax.mail - mail - - - javax.jms - jms - - - com.sun.jdmk - jmxtools - - - com.sun.jmx - jmxri - - - - - junit - junit - ${junit.version} - test - - - org.mvel - mvel2 - ${mvel2.version} - compile - - - org.antlr - antlr-runtime - ${antlr.runtime.version} - compile - - - org.wso2.orbit.edu.stanford.nlp - stanford-nlp - ${stanford-nlp.version} - - - com.google.code.gson - gson - ${gson.version} - - - org.wso2.orbit.org.geotools - gt-geojson - ${geotools.version} - - - org.wso2.orbit.com.github.lucarosellini.rJava - r-java - ${rjava.version} - - - org.wso2.orbit.org.jpmml - pmml-model - ${jpmml.model.version} - - - org.wso2.orbit.org.jpmml - pmml-manager - ${jpmml.manager.version} - - - org.wso2.orbit.org.jpmml - pmml-schema - ${jpmml.model.version} - - - org.wso2.orbit.org.jpmml - pmml-evaluator - ${jpmml.model.version} - - - commons-logging - commons-logging - ${commons.logging.version} - - - org.wso2.orbit.joda-time - joda-time - ${joda.time.version} - - - - org.wso2.siddhi - siddhi-query-api - ${siddhi.version} - - - org.wso2.siddhi - siddhi-query-compiler - ${siddhi.version} - - - org.wso2.siddhi - siddhi-core - ${siddhi.version} - compile - - - - - - - - org.apache.maven.wagon - wagon-ssh - 2.1 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - - org.apache.maven.plugins - maven-surefire-plugin - 2.4.3 - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8 - - - org.apache.felix - maven-bundle-plugin - true - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - **/*TestCase.java - - brief - false - once - -ea -Xmx1g - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - - - - 13.6.0.wso2v1 - 3.1.1 - 4.10 - 1.2.14 - 2.0.19 - 3.4 - 2.2.4 - 0.9.7.wso2v1 - 13.6.0.wso2v1 - 3.6.0.wso2v1 - 1.1.16.wso2v1 - 1.1.16.wso2v1 - 1.1.1 - 2.8.2.wso2v1 - UTF-8 - - - - - Architecture - architecture-request@wso2.org - architecture-request@wso2.org - architecture@wso2.org - http://wso2.markmail.org/search/?q=list%3Aorg.wso2.architecture+siddhi - - - - - - - wso2-nexus - WSO2 internal Repository - http://maven.wso2.org/nexus/content/groups/wso2-public/ - - true - daily - ignore - - - - wso2.releases - WSO2 internal Repository - http://maven.wso2.org/nexus/content/repositories/releases/ - - true - daily - ignore - - - - osgeo - Open Source Geospatial Foundation Repository - http://download.osgeo.org/webdav/geotools/ - - - - true - - opengeo - OpenGeo Maven Repository - http://repo.opengeo.org - - - - - - wso2.gpl.releases - WSO2 GPL Maven Repository - http://maven.wso2.org/nexus/content/repositories/wso2gpl/ - - - wso2.gpl.snapshots - WSO2 GPL Maven Snapshot Repository - http://maven.wso2.org/nexus/content/repositories/wso2gpl-snapshots/ - - - - diff --git a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/siddhi-geo-extention-deployer.xml b/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/siddhi-geo-extention-deployer.xml deleted file mode 100644 index 9da80c933..000000000 --- a/components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/src/main/resources/scripts/siddhi-geo-extention-deployer.xml +++ /dev/null @@ -1,199 +0,0 @@ - - - - - org.wso2 - wso2 - 1 - - - - gpl-siddhi-geo-extention - - - 4.0.0 - org.wso2.iot.devicemgt-plugins - analytics-scripts - 3.2.0 - pom - Executing Analytics Scripts - http://wso2.org - - - - - org.wso2.maven - carbon-p2-plugin - 1.5.4 - - - 2-p2-repo-generation - package - - p2-repo-gen - - - file:${basedir}/p2-repo - file:${basedir}/p2-repo - true - true - - - org.wso2.extension.siddhi.gpl.execution.geo:siddhi-gpl-execution-geo-feature:${siddhi-gpl-execution-geo-feature.version} - - - org.wso2.gpl.siddhi.extensions:org.wso2.gpl.siddhi.extension.geo.feature:${org.wso2.iot.devicemgt-plugins.gpl.siddhi.extensions.version} - - - - - - default-feature-install - package - - p2-profile-gen - - - analytics-default - file:${basedir}/p2-repo - file:${basedir}/p2-repo - ${basedir}/../../components - false - - - siddhi-gpl-execution-geo.feature.group - ${siddhi-gpl-execution-geo-feature.version} - - - org.wso2.gpl.siddhi.extension.geo.feature.group - ${org.wso2.iot.devicemgt-plugins.gpl.siddhi.extensions.version} - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.6 - - - default-feature-install - package - - - - - - - - run - - - - - - - - - - wso2.releases - WSO2 internal Repository - http://maven.wso2.org/nexus/content/repositories/releases/ - - true - daily - ignore - - - - wso2.snapshots - Apache Snapshot Repository - http://maven.wso2.org/nexus/content/repositories/snapshots/ - - true - daily - - - false - - - - wso2-nexus - WSO2 internal Repository - http://maven.wso2.org/nexus/content/groups/wso2-public/ - - true - daily - ignore - - - - - - - - - wso2-nexus - WSO2 internal Repository - http://maven.wso2.org/nexus/content/groups/wso2-public/ - - true - daily - ignore - - - - wso2.releases - WSO2 internal Repository - http://maven.wso2.org/nexus/content/repositories/releases/ - - true - daily - ignore - - - - wso2.snapshots - WSO2 Snapshot Repository - http://maven.wso2.org/nexus/content/repositories/snapshots/ - - true - daily - - - false - - - - - 3.2.0 - 3.2.0 - - \ No newline at end of file diff --git a/components/extensions/siddhi-extensions/pom.xml b/components/extensions/siddhi-extensions/pom.xml deleted file mode 100644 index a28f2c5b3..000000000 --- a/components/extensions/siddhi-extensions/pom.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - org.wso2.carbon.devicemgt-plugins - extensions - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - siddhi-extensions - pom - WSO2 Carbon - Siddhi Extension - http://wso2.org - - - org.wso2.extension.siddhi.device - org.wso2.extension.siddhi.execution.json - org.wso2.gpl.siddhi.extension.geo.script - - - - - - - org.apache.felix - maven-scr-plugin - ${maven.scr.version} - - - generate-scr-scrdescriptor - - scr - - - - - - - - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/pom.xml deleted file mode 100644 index 06b18a00d..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/pom.xml +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - android-plugin - org.wso2.carbon.devicemgt-plugins - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.device.mgt.mobile.android.addons - bundle - WSO2 Carbon - Mobile Device Management Android Addons Impl - WSO2 Carbon - Mobile Device Management Android Addons Implementation - https://entgra.io/ - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - ${carbon.devicemgt.plugins.version} - Device Management Mobile Android addons Impl Bundle - - com.google.gson.* - - - org.wso2.carbon.device.mgt.mobile.android.addons.* - - - - - - - - - - javax.servlet - servlet-api - provided - - - org.apache.cxf - cxf-rt-frontend-jaxws - provided - - - org.apache.cxf - cxf-rt-frontend-jaxrs - provided - - - org.apache.cxf - cxf-rt-transports-http - provided - - - org.hibernate - hibernate-validator - - - org.wso2.carbon - org.wso2.carbon.logging - - - com.google.code.gson - gson - - - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml index 74529af69..89151b896 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml @@ -49,6 +49,44 @@ api#device-mgt#android#v1.0 + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + @@ -61,7 +99,7 @@ org.apache.maven.plugins maven-antrun-plugin - 1.8 + 1.7 compile @@ -80,6 +118,54 @@ + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + + + + + + + client + + test + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + test + + java + + + + @@ -90,32 +176,6 @@ org.apache.cxf cxf-rt-frontend-jaxws - - - asm - asm - - - neethi - org.apache.neethi - - - wsdl4j - wsdl4j - - - xml-resolver - xml-resolver - - - xmlschema-core - org.apache.ws.xmlschema - - - stax2-api - org.codehaus.woodstox - - org.apache.cxf @@ -134,12 +194,6 @@ org.wso2.carbon org.wso2.carbon.utils provided - - - commons-lang - commons-lang.wso2 - - org.wso2.carbon @@ -159,16 +213,36 @@ provided - commons-httpclient.wso2 - commons-httpclient + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core provided - commons-logging - commons-logging + org.slf4j + slf4j-api + + org.wso2.carbon.devicemgt + org.wso2.carbon.policy.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.policy.mgt.core + provided + + + org.wso2.carbon.devicemgt-plugins + org.wso2.carbon.device.mgt.mobile.android + provided + + + commons-httpclient.wso2 + commons-httpclient + provided + com.google.code.gson gson @@ -182,42 +256,12 @@ org.slf4j slf4j-api - - commons-logging - commons-logging - - - neethi - org.wso2.orbit.org.apache.neethi - - - httpcore - org.apache.httpcomponents - - - geronimo-javamail_1.4_spec - org.apache.geronimo.specs - org.wso2.carbon.analytics org.wso2.carbon.analytics.api provided - - - asm - org.ow2.asm - - - objenesis - org.objenesis - - - guava - com.google.guava - - io.swagger @@ -241,28 +285,13 @@ org.slf4j slf4j-api - - guava - com.google.guava - - - com.google.apis - google-api-services-androidenterprise - - - guava - com.google.guava - - - jackson-core - com.fasterxml.jackson.core - - + javax.servlet + servlet-api + provided - org.hibernate hibernate-validator @@ -270,130 +299,60 @@ javax.ws.rs javax.ws.rs-api - provided - + + org.testng + testng + test + + + org.powermock + powermock-module-testng + test + + + org.powermock + powermock-api-mockito + test + + + com.h2database.wso2 + h2-database-engine + test + + + org.wso2.carbon + org.wso2.carbon.queuing + test + + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + test + + + commons-dbcp.wso2 + commons-dbcp + test + + + commons-pool.wso2 + commons-pool + test + + + org.wso2.carbon + javax.cache.wso2 + test + + + javassist + javassist + test + org.codehaus.jackson jackson-core-asl - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.application.mgt.common - provided - - - commons-logging - commons-logging - - - neethi - org.apache.neethi.wso2 - - - wsdl4j - wsdl4j.wso2 - - - geronimo-stax-api_1.0_spec - org.apache.geronimo.specs.wso2 - - - org.wso2.securevault - org.wso2.securevault - - - axis2-client - org.apache.axis2.wso2 - - - - - org.apache.httpcomponents - httpclient - - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.common - provided - - - google-api-services-androidenterprise - com.google.apis - - - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.addons - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.core - provided - - - org.wso2.carbon.feature.mgt.core - org.wso2.carbon - - - commons-lang3 - org.apache.commons - - - annotations - com.google.code.findbugs - - - stax2-api - org.codehaus.woodstox - - - jaxb-impl - com.sun.xml.bind - - - jackson-datatype-joda - com.fasterxml.jackson.datatype - - - - - org.wso2.carbon.devicemgt - org.wso2.carbon.policy.mgt.common - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.policy.mgt.core - provided - - - commons-logging - commons-logging - - - axis2-client - org.apache.axis2.wso2 - - - neethi - org.wso2.orbit.org.apache.neethi - - - wsdl4j - wsdl4j.wso2 - - - XmlSchema - org.apache.ws.commons.schema.wso2 - - - axiom-api - org.apache.ws.commons.axiom - - - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/AndroidEnterpriseAPI.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/AndroidEnterpriseAPI.java deleted file mode 100644 index d48c79523..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/AndroidEnterpriseAPI.java +++ /dev/null @@ -1,1376 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.mobile.android.api; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Extension; -import io.swagger.annotations.ExtensionProperty; -import io.swagger.annotations.Info; -import io.swagger.annotations.ResponseHeader; -import io.swagger.annotations.SwaggerDefinition; -import io.swagger.annotations.Tag; -import org.wso2.carbon.apimgt.annotations.api.Scope; -import org.wso2.carbon.apimgt.annotations.api.Scopes; -import org.wso2.carbon.device.application.mgt.common.dto.ApplicationPolicyDTO; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStoreCluster; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStorePage; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStorePageLinks; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseInstallPolicy; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseManagedConfig; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -@SwaggerDefinition( - info = @Info( - version = "1.0.0", - title = "", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = "name", value = "Android Enterprise Service"), - @ExtensionProperty(name = "context", value = "/api/device-mgt/android/v1.0/enterprise"), - }) - } - ), - tags = { - @Tag(name = "android,device_management", description = "Android Device Management Service") - } -) - -@Api(value = "Android Enterprise Service") -@Path("/enterprise") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -@Scopes( - scopes = { - @Scope( - name = "Manage Enterprise User", - description = "Managing Enterprise users in the system", - key = "perm:enterprise:modify", - permissions = {"/device-mgt/enterprise/user/modify"} - ), - @Scope( - name = "View Enterprise User", - description = "View enterprise users in the system", - key = "perm:enterprise:view", - permissions = {"/device-mgt/enterprise/user/view"} - ) - } -) -public interface AndroidEnterpriseAPI { - - @POST - @Path("/user") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Add User", - notes = "Add a new user to enterprise system.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully added new user", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding new user.") - }) - Response addUser(@ApiParam( - name = "user", - value = "Enterprise user and device data.") EnterpriseUser enterpriseUser); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @POST - @Path("/available-app") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Add User", - notes = "Add a new user to enterprise system.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully added new user", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding new user.") - }) - Response updateUser(@ApiParam( - name = "device", - value = "Enterprise user and device data.") EnterpriseInstallPolicy device); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @GET - @Path("/store-url") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting Details of a Device Type", - notes = "Get the details of a device by searching via the device type and the tenant domain.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Created. \n Successfully added new user", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding new user.") - }) - Response getStoreUrl( - @ApiParam( - name = "approveApps", - value = "Boolean flag indicating whether to permanently delete the device.") - @QueryParam("approveApps") boolean approveApps, - - @ApiParam( - name = "searchEnabled", - value = "Boolean flag indicating whether to permanently delete the device.") - @QueryParam("searchEnabled") boolean searchEnabled, - - @ApiParam( - name = "isPrivateAppsEnabled", - value = "Boolean flag indicating whether to permanently delete the device.") - @QueryParam("isPrivateAppsEnabled") boolean isPrivateAppsEnabled, - - @ApiParam( - name = "isWebAppEnabled", - value = "Boolean flag indicating whether to permanently delete the device.") - @QueryParam("isWebAppEnabled") boolean isWebAppEnabled, - - @ApiParam( - name = "isOrganizeAppPageVisible", - value = "Boolean flag indicating whether to permanently delete the device.") - @QueryParam("isOrganizeAppPageVisible") boolean isOrganizeAppPageVisible, - - @ApiParam( - name = "isManagedConfigEnabled", - value = "Boolean flag indicating whether to permanently delete the device.") - @QueryParam("isManagedConfigEnabled") boolean isManagedConfigEnabled, - - @ApiParam(name = "host", - value = "Boolean flag indicating whether to permanently delete the device.", - required = true) @QueryParam("host") String host); - - @GET - @Path("/products/sync") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting Details of a Device Type", - notes = "Get the details of a device by searching via the device type and the tenant domain.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Created. \n Successfully added new user", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding new user.") - }) - Response syncApps(); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @POST - @Path("/store-layout/page") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Add New Page", - notes = "Add a new page to enterprise system.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully added new page", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding new page.") - }) - Response addPage(@ApiParam( - name = "page", - value = "Enterprise page.") EnterpriseStorePage page); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - - @PUT - @Path("/store-layout/page") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "PUT", - value = "Update New Page", - notes = "Update a new page to enterprise system.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully update page", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while updating new page.") - }) - Response updatePage(@ApiParam( - name = "page", - value = "Enterprise page.") - EnterpriseStorePage page); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @DELETE - @Path("/store-layout/page/{id}") - @Consumes(MediaType.WILDCARD) - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "DELETE", - value = "Deleting Details of a Device Type", - notes = "Deleting the details of a device by searching via the device type and the tenant domain.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Created. \n Successfully Delete new user", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while Deleting new user.") - }) - Response deletePage(@ApiParam( - name = "id", - value = "The unique page id") - @PathParam("id") String id); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - - @GET - @Path("/store-layout/page") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Deleting Details of a Device Type", - notes = "Deleting the details of a device by searching via the device type and the tenant domain.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Created. \n Successfully get new user", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while getting new user.") - }) - Response getPages(); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - - @PUT - @Path("/store-layout/home-page/{id}") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "PUT", - value = "Update Home Page", - notes = "Update the home page", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully updated home page", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while updating home page.") - }) - Response setHome(@ApiParam( - name = "id", - value = "The unique page id") - @PathParam("id") String id); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - - @GET - @Path("/store-layout/home-page") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Get Home Page", - notes = "Get a home page", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 200, message = "Created. \n Successfully update home page", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while updating home page.") - }) - Response getHome(); - - //###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @POST - @Path("/store-layout/cluster") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Add New Cluster", - notes = "Add a new cluster to enterprise system.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully added new cluster", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding new cluster.") - }) - Response addCluster(@ApiParam( - name = "storeCluster", - value = "Enterprise cluster.") EnterpriseStoreCluster storeCluster); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - - @PUT - @Path("/store-layout/cluster") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "PUT", - value = "Update cluster", - notes = "Update cluster.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully updated cluster", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while updating cluster.") - }) - Response updatePage(@ApiParam( - name = "storeCluster", - value = "Enterprise page.") - EnterpriseStoreCluster storeCluster); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @DELETE - @Path("/store-layout/cluster/{clusterId}/page/{pageId}") - @Consumes(MediaType.WILDCARD) - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "DELETE", - value = "Deleting Details of a cluster", - notes = "Deleting the details of a cluster.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Created. \n Successfully Deleted cluster", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while Deleting cluster.") - }) - Response deleteCluster(@ApiParam( - name = "clusterId", - value = "The unique cluster id") - @PathParam("clusterId") String clusterId, - @ApiParam( - name = "pageId", - value = "The unique page pageId") - @PathParam("pageId") String pageId); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - - @GET - @Path("/store-layout/page/{id}/clusters") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Deleting Details of a cluster", - notes = "Deleting the details of a cluster.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Created. \n Successfully fetched cluster", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while getting cluster.") - }) - Response getClustersInPage( - @ApiParam( - name = "pageId", - value = "The unique page pageId") - @PathParam("id") String pageId); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @PUT - @Path("/store-layout/page-link") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Add New Cluster", - notes = "Add a new cluster to enterprise system.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully added new cluster", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding new cluster.") - }) - Response updateLinks(@ApiParam( - name = "links", - value = "Enterprise page links.") EnterpriseStorePageLinks links); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @GET - @Path("/managed-configs/package/{packageName}") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting managed configs", - notes = "Getting managed configs.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:view") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Created. \n Successfully fetched managed configs", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while getting managed configs.") - }) - Response getConfig(@ApiParam( - name = "packageName", - value = "The package name") - @PathParam("packageName") String packageName); - - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @POST - @Path("/managed-configs") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Add New config", - notes = "Add a new config to enterprise system.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 201, message = "Created. \n Successfully added new config", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding new config.") - }) - - Response addManagedConfigs(@ApiParam( - name = "managedConfig", - value = "Enterprise managed conf.") AndroidEnterpriseManagedConfig managedConfig); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @PUT - @Path("/managed-configs") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "PUT", - value = "Update config", - notes = "Update config to enterprise system.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 200, message = "Created. \n Successfully updated new config", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while updating new config.") - }) - - Response updateManagedConfigs(@ApiParam( - name = "managedConfig", - value = "Enterprise managed conf.") AndroidEnterpriseManagedConfig managedConfig); - - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @DELETE - @Path("/managed-configs/mcm/{mcmId}") - @Consumes(MediaType.WILDCARD) - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "DELETE", - value = "Deleting Details of a config", - notes = "Deleting the details of a config.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Created. \n Successfully deleted config", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while deleting config.") - }) - Response deleteManagedConfigs(@ApiParam( - name = "mcmId", - value = "The mcm Id") - @PathParam("mcmId") String packageName); - - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @POST - @Path("/change-app") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Update apps in device", - notes = "Update apps in device.", - tags = "Android Enterprise Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses( - value = { - @ApiResponse(code = 200, message = "Created. \n Successfully updated new config", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while updating new config.") - }) - Response updateUser(@ApiParam( - name = "applicationPolicyDTO", - value = "Enterprise managed conf.") ApplicationPolicyDTO applicationPolicyDTO); - -//###################################################################################################################### -//###################################################################################################################### -//###################################################################################################################### - - @GET - @Path("/wipe-device") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting managed configs", - notes = "Getting managed configs.", - tags = "Device Type Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:enterprise:modify") - }) - } - ) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Created. \n Successfully fetched managed configs", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The URL of the added policy."), - @ResponseHeader( - name = "Content-Type", - description = "The content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.") - }), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while getting managed configs.") - }) - Response wipeEnterprise(); - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/AndroidEnterpriseAPIImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/AndroidEnterpriseAPIImpl.java deleted file mode 100644 index 1a7a5a84d..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/AndroidEnterpriseAPIImpl.java +++ /dev/null @@ -1,1101 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.api.impl; - -import com.google.api.client.http.HttpStatusCodes; -import com.google.api.services.androidenterprise.model.ProductsListResponse; -import com.google.api.services.androidenterprise.model.StoreCluster; -import com.google.api.services.androidenterprise.model.StoreLayout; -import com.google.api.services.androidenterprise.model.StoreLayoutClustersListResponse; -import com.google.api.services.androidenterprise.model.StoreLayoutPagesListResponse; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.application.mgt.common.dto.ApplicationPolicyDTO; -import org.wso2.carbon.device.application.mgt.common.dto.ApplicationReleaseDTO; -import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; -import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; -import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; -import org.wso2.carbon.device.mgt.mobile.android.api.AndroidEnterpriseAPI; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseConfigs; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStoreCluster; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStorePackages; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStorePage; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStorePageLinks; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseTokenUrl; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.GoogleAppSyncResponse; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseApp; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseInstallPolicy; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.TokenWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseManagedConfig; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseServiceException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.NotFoundException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.UnexpectedServerErrorException; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidDeviceUtils; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidEnterpriseUtils; -import org.wso2.carbon.device.mgt.mobile.android.api.invoker.GoogleAPIInvoker; -import org.wso2.carbon.policy.mgt.common.FeatureManagementException; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -@Path("/enterprise") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class AndroidEnterpriseAPIImpl implements AndroidEnterpriseAPI { - private static final Log log = LogFactory.getLog(AndroidEnterpriseAPIImpl.class); - - @Override - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - @POST - @Path("/user") - public Response addUser(EnterpriseUser enterpriseUser) { - if (enterpriseUser == null) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build()) - .build(); - } else if (enterpriseUser.getEmmDeviceIdentifier() == null || enterpriseUser.getEmmDeviceIdentifier().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("EMM ID is incorrect").build()) - .build(); - } else if (enterpriseUser.getAndroidPlayDeviceId() == null || enterpriseUser.getAndroidPlayDeviceId().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Google Play ID is incorrect").build()) - .build(); - } - - String token; - try { - token = insertUser(enterpriseUser); - if (token == null) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching token").build()) - .build(); - } - - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving user").build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while adding user"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - return Response.status(Response.Status.OK).entity(token).build(); - } - - public String insertUser(EnterpriseUser enterpriseUser) - throws EnterpriseServiceException, AndroidDeviceMgtPluginException { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - String token; - boolean deviceIdExist = false; - - String googleUserId; - List androidEnterpriseUsers = AndroidAPIUtils.getAndroidPluginService() - .getEnterpriseUser(CarbonContext.getThreadLocalCarbonContext().getUsername()); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - if (androidEnterpriseUsers != null && !androidEnterpriseUsers.isEmpty()) { - googleUserId = androidEnterpriseUsers.get(0).getGoogleUserId(); - // If this device is also present, only need to provide a token for this request. - for (AndroidEnterpriseUser enterprise : androidEnterpriseUsers) { - if (enterprise.getEmmDeviceId() != null - && enterprise.getEmmDeviceId().equals(enterpriseUser.getAndroidPlayDeviceId())) { - deviceIdExist = true; - } - } - } else { - googleUserId = googleAPIInvoker.insertUser(enterpriseConfigs.getEnterpriseId(), CarbonContext - .getThreadLocalCarbonContext() - .getUsername()); - } - // Fetching an auth token from Google EMM API - token = googleAPIInvoker.getToken(enterpriseConfigs.getEnterpriseId(), googleUserId); - - if (!deviceIdExist) { - AndroidEnterpriseUser androidEnterpriseUser = new AndroidEnterpriseUser(); - androidEnterpriseUser.setEmmUsername(CarbonContext.getThreadLocalCarbonContext().getUsername()); - androidEnterpriseUser.setTenantId(CarbonContext.getThreadLocalCarbonContext().getTenantId()); - androidEnterpriseUser.setAndroidPlayDeviceId(enterpriseUser.getAndroidPlayDeviceId()); - androidEnterpriseUser.setEnterpriseId(enterpriseConfigs.getEnterpriseId()); - androidEnterpriseUser.setEmmDeviceId(enterpriseUser.getEmmDeviceIdentifier()); - androidEnterpriseUser.setGoogleUserId(googleUserId); - - AndroidAPIUtils.getAndroidPluginService().addEnterpriseUser(androidEnterpriseUser); - } - - return token; - - } - - @Override - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - @POST - @Path("/available-app") - public Response updateUser(EnterpriseInstallPolicy device) { - - boolean sentToDevice = false; - - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - List enterpriseUserInstances = AndroidAPIUtils.getAndroidPluginService() - .getEnterpriseUser(device.getUsername()); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - for (AndroidEnterpriseUser userDetail : enterpriseUserInstances) { - if (userDetail.getEnterpriseId() != null && !userDetail.getEnterpriseId().isEmpty() && userDetail - .getEmmUsername() != null && userDetail.getEmmUsername().equals(device.getUsername()) - && device.getAndroidId().equals(userDetail.getAndroidPlayDeviceId())) { - googleAPIInvoker.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(), - AndroidEnterpriseUtils.convertToDeviceInstance(device)); - sentToDevice = true; - } - } - - } catch (EnterpriseServiceException e) { - String errorMessage = "App install failed. No user found for name " + device.getUsername(); - log.error(errorMessage); - return Response.status(Response.Status.NOT_FOUND).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND) - .setMessage(errorMessage).build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while updating user"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - if (sentToDevice) { - return Response.status(Response.Status.OK).build(); - } else { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Could not install on the device of user " - + device.getUsername()).build()).build(); - } - } - - @Override - @GET - @Path("/store-url") - public Response getStoreUrl(@QueryParam("approveApps") boolean approveApps, - @QueryParam("searchEnabled") boolean searchEnabled, - @QueryParam("isPrivateAppsEnabled") boolean isPrivateAppsEnabled, - @QueryParam("isWebAppEnabled") boolean isWebAppEnabled, - @QueryParam("isOrganizeAppPageVisible") boolean isOrganizeAppPageVisible, - @QueryParam("isManagedConfigEnabled") boolean isManagedConfigEnabled, - @QueryParam("host") String host) { - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - EnterpriseTokenUrl enterpriseTokenUrl = new EnterpriseTokenUrl(); - if (enterpriseConfigs == null || enterpriseConfigs.getEnterpriseId() == null) { - return Response.status(Response.Status.NOT_FOUND).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Not configured for AFW").build()).build(); - } - enterpriseTokenUrl.setEnterpriseId(enterpriseConfigs.getEnterpriseId()); - enterpriseTokenUrl.setApproveApps(approveApps); - enterpriseTokenUrl.setSearchEnabled(searchEnabled); - enterpriseTokenUrl.setPrivateAppsEnabled(isPrivateAppsEnabled); - enterpriseTokenUrl.setWebAppEnabled(isWebAppEnabled); - enterpriseTokenUrl.setOrganizeAppPageVisible(isOrganizeAppPageVisible); - enterpriseTokenUrl.setParentHost(host); - enterpriseTokenUrl.setManagedConfigEnabled(isManagedConfigEnabled); - - String token = googleAPIInvoker.getAdministratorWebToken(enterpriseTokenUrl); - TokenWrapper tokenWrapper = new TokenWrapper(); - tokenWrapper.setToken(token); - return Response.status(Response.Status.OK).entity(tokenWrapper).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when calling get web token").build()) - .build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while getting store url"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @Override - @GET - @Path("/products/sync") - public Response syncApps() { - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - ProductsListResponse productsListResponse = googleAPIInvoker - .listProduct(enterpriseConfigs.getEnterpriseId(), null); - AndroidEnterpriseUtils.persistApp(productsListResponse); - - int total = productsListResponse.getProduct().size() - + recursiveSync(googleAPIInvoker, enterpriseConfigs.getEnterpriseId(), productsListResponse); - GoogleAppSyncResponse appSyncResponse = new GoogleAppSyncResponse(); - appSyncResponse.setTotalApps(total); - return Response.status(Response.Status.OK).entity(appSyncResponse).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when calling sync").build()) - .build(); - } catch (ApplicationManagementException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when persisting app").build()) - .build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while syncing apps"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - private int recursiveSync(GoogleAPIInvoker googleAPIInvoker, String enterpriseId, ProductsListResponse - productsListResponse) throws EnterpriseServiceException, ApplicationManagementException { - // Are there more pages - if (productsListResponse == null || productsListResponse.getTokenPagination() == null - || productsListResponse.getTokenPagination().getNextPageToken() == null) { - return 0; - } - - // Get next page - ProductsListResponse productsListResponseNext = googleAPIInvoker.listProduct(enterpriseId, - productsListResponse.getTokenPagination().getNextPageToken()); - AndroidEnterpriseUtils.persistApp(productsListResponseNext); - if (productsListResponseNext != null && productsListResponseNext.getTokenPagination() != null && - productsListResponseNext.getTokenPagination().getNextPageToken() != null) { - return recursiveSync(googleAPIInvoker, enterpriseId, productsListResponseNext) - + productsListResponseNext.getProduct().size(); - } else { - return productsListResponseNext.getProduct().size(); - } - } - - @POST - @Path("/store-layout/page") - @Override - public Response addPage(EnterpriseStorePage page) { - if (page == null || page.getPageName() == null) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build()) - .build(); - } - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - String id = googleAPIInvoker.insertPage(enterpriseConfigs.getEnterpriseId(), page); - page.setPageId(id); - return Response.status(Response.Status.OK).entity(page).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when inserting page " - + page.getPageName()).build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when inserting page " - + page.getPageName() + " , due to an error with ESA").build() ).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while adding page"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @PUT - @Path("/store-layout/page") - @Override - public Response updatePage(EnterpriseStorePage page) { - if (page == null || page.getPageName() == null || page.getPageId() == null) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build()) - .build(); - } - - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - String id = googleAPIInvoker.updatePage(enterpriseConfigs.getEnterpriseId(), page); - page.setPageId(id); - return Response.status(Response.Status.OK).entity(page).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating page " - + page.getPageName()).build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating page " - + page.getPageName() + " , due to an error with ESA").build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while updating page"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @DELETE - @Path("/store-layout/page/{id}") - @Consumes(MediaType.WILDCARD) - @Override - public Response deletePage(@PathParam("id") String id) { - if (id == null || id.isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Page Id cannot be empty").build()) - .build(); - } - - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - googleAPIInvoker.deletePage(enterpriseConfigs.getEnterpriseId(), id); - return Response.status(Response.Status.OK).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when deleting page " - + id).build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating page " - + id + " , Due to an error with ESA").build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while deleting page"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @GET - @Path("/store-layout/page") - @Override - public Response getPages() { - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - StoreLayoutPagesListResponse pages = googleAPIInvoker.listPages(enterpriseConfigs.getEnterpriseId()); - return Response.status(Response.Status.OK).entity(pages).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching all pages").build()) - .build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching page " - + " , Due to an error with ESA").build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while getting pages"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - - @PUT - @Path("/store-layout/home-page/{id}") - @Override - public Response setHome(@PathParam("id") String id) { - if (id == null || id.isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Id cannot be empty").build()) - .build(); - } - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - StoreLayout layout = googleAPIInvoker.setStoreLayout(enterpriseConfigs.getEnterpriseId(), id); - return Response.status(Response.Status.OK).entity(layout).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when inserting home page " - + id).build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when inserting home page " - + id + " , due to an error with ESA").build() ).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while setting home"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @GET - @Path("/store-layout/home-page") - @Override - public Response getHome() { - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - StoreLayout layout = googleAPIInvoker.getStoreLayout(enterpriseConfigs.getEnterpriseId()); - return Response.status(Response.Status.OK).entity(layout).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching home page").build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching home page.").build() ) - .build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while getting home"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/store-layout/cluster") - @Override - public Response addCluster(EnterpriseStoreCluster storeCluster) { - if (storeCluster == null) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build()) - .build(); - } else if (storeCluster.getName() == null || storeCluster.getName().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster name cannot be empty").build()).build(); - } else if (storeCluster.getProducts() == null || storeCluster.getProducts().size() < 0) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Products cannot be empty").build()).build(); - } else if (storeCluster.getOrderInPage() == null || storeCluster.getOrderInPage().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster order cannot be empty").build()).build(); - } - - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - String id = googleAPIInvoker.insertCluster(enterpriseConfigs.getEnterpriseId(), storeCluster); - storeCluster.setClusterId(id); - return Response.status(Response.Status.OK).entity(storeCluster).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating cluster " - + storeCluster.getName()).build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating cluster " - + storeCluster.getName() + " , due to an error with ESA").build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while adding cluster"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @PUT - @Path("/store-layout/cluster") - @Override - public Response updatePage(EnterpriseStoreCluster storeCluster) { - if (storeCluster == null) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build()) - .build(); - } else if (storeCluster.getName() == null || storeCluster.getName().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster name cannot be empty").build()).build(); - } else if (storeCluster.getProducts() == null || storeCluster.getProducts().size() < 0) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Products cannot be empty").build()).build(); - } else if (storeCluster.getOrderInPage() == null || storeCluster.getOrderInPage().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster order cannot be empty").build()).build(); - } - - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - String id = googleAPIInvoker.updateCluster(enterpriseConfigs.getEnterpriseId(), storeCluster); - storeCluster.setClusterId(id); - return Response.status(Response.Status.OK).entity(storeCluster).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating cluster " - + storeCluster.getName()).build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when updating cluster " - + storeCluster.getName() + " , due to an error with ESA").build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while updating cluster"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @DELETE - @Path("/store-layout/cluster/{clusterId}/page/{pageId}") - @Consumes(MediaType.WILDCARD) - @Override - public Response deleteCluster( @PathParam("clusterId") String clusterId, @PathParam("pageId") String pageId) { - if (clusterId == null || clusterId.isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Cluster id cannot be empty").build()).build(); - } else if (pageId == null || pageId.isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Page id cannot be empty").build()).build(); - } - - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - googleAPIInvoker.deleteCluster(enterpriseConfigs.getEnterpriseId(), pageId, clusterId); - return Response.status(Response.Status.OK).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when deleting cluster " - + clusterId).build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when deleting cluster " - + clusterId + " , due to an error with ESA").build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while deleting cluster"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @GET - @Path("/store-layout/page/{pageId}/clusters") - @Override - public Response getClustersInPage(@PathParam("pageId") String pageId) { - if (pageId == null || pageId.isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Page id cannot be empty").build()).build(); - } - - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - StoreLayoutClustersListResponse response = googleAPIInvoker.getClusters(enterpriseConfigs.getEnterpriseId(), pageId); - if (response == null || response.getCluster() == null) { - return Response.status(Response.Status.NOT_FOUND).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Page id cannot be found").build()).build(); - } - List clusters = new ArrayList<>(); - for (StoreCluster cluster : response.getCluster()) { - EnterpriseStoreCluster storeCluster = new EnterpriseStoreCluster(); - storeCluster.setClusterId(cluster.getId()); - storeCluster.setName(cluster.getName().get(0).getText()); - storeCluster.setOrderInPage(cluster.getOrderInPage()); - - - List productIds = new ArrayList<>(); - for (String productId : cluster.getProductId()) { - String trimmedPackage = productId.replaceFirst("app:", ""); - productIds.add(trimmedPackage); - } - ApplicationManager appManager = AndroidAPIUtils.getAppManagerService(); - List packageDetails = appManager.getReleaseByPackageNames(productIds); - - - List enterpriseStorePackages = new ArrayList<>(); - for (String productId : cluster.getProductId()) { - String trimmedPackage = productId.replaceFirst("app:", ""); - - EnterpriseStorePackages storePackages = new EnterpriseStorePackages(); - storePackages.setPackageId(productId); - for (ApplicationReleaseDTO releaseDTO : packageDetails) { - if (releaseDTO.getPackageName().equalsIgnoreCase(trimmedPackage)) { - storePackages.setIconUrl(releaseDTO.getIconName()); - break; - } - } - - enterpriseStorePackages.add(storePackages); - } - storeCluster.setProducts(enterpriseStorePackages); - clusters.add(storeCluster); - - } - return Response.status(Response.Status.OK).entity(clusters).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching clusters in pageId " - + pageId).build()).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching clusters in pageId " - + pageId + " , due to an error with ESA").build()).build(); - } catch (ApplicationManagementException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching all details in PageId " - + pageId).build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while getting clusters in page"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @PUT - @Path("/store-layout/page-link") - @Override - public Response updateLinks(EnterpriseStorePageLinks link) { - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - googleAPIInvoker.addLinks(enterpriseConfigs.getEnterpriseId(), - link.getPageId(), link.getLinks()); - return Response.status(Response.Status.OK).build(); - } catch (IOException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching all pages").build()) - .build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when fetching page " - + " , Due to an error with ESA").build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while updating links"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - @Override - @Produces(MediaType.APPLICATION_JSON) - @GET - @Path("/managed-configs/package/{packageName}") - public Response getConfig(@PathParam("packageName") String packageName) { - if (packageName== null || packageName.isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Package name is incorrect").build()).build(); - } - - AndroidEnterpriseManagedConfig managedConfig; - try { - managedConfig = AndroidAPIUtils.getAndroidPluginService().getConfigByPackageName(packageName); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs").build()).build(); - } - return Response.status(Response.Status.OK).entity(managedConfig).build(); - } - - @Override - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - @POST - @Path("/managed-configs") - public Response addManagedConfigs(AndroidEnterpriseManagedConfig managedConfig) { - if (managedConfig == null) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build()) - .build(); - } else if (managedConfig.getPackageName() == null || managedConfig.getPackageName().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Package name is incorrect").build()).build(); - } else if (managedConfig.getProfileName() == null || managedConfig.getProfileName().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Profile name is incorrect").build()).build(); - } - - try { - AndroidAPIUtils.getAndroidPluginService().addConfig(managedConfig); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs for " - + managedConfig.getPackageName()).build()).build(); - } - return Response.status(Response.Status.CREATED).build(); - } - - @Override - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - @PUT - @Path("/managed-configs") - public Response updateManagedConfigs(AndroidEnterpriseManagedConfig managedConfig) { - if (managedConfig == null) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Message body is empty or incorrect").build()) - .build(); - } else if (managedConfig.getProfileName() == null || managedConfig.getProfileName().isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Profile name is incorrect").build()).build(); - } - - try { - AndroidAPIUtils.getAndroidPluginService().updateMobileDevice(managedConfig); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs").build()).build(); - } - return Response.status(Response.Status.CREATED).build(); - } - - @Override - @DELETE - @Path("/managed-configs/mcm/{mcmId}") - @Consumes(MediaType.WILDCARD) - public Response deleteManagedConfigs(@PathParam("mcmId") String mcmId) { - if (mcmId == null || mcmId.isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("MCM Id is incorrect").build()).build(); - } - - try { - AndroidAPIUtils.getAndroidPluginService().deleteMobileDevice(mcmId); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs").build()).build(); - } - return Response.status(Response.Status.OK).build(); - } - - - @Override - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - @POST - @Path("/change-app") - public Response updateUser(ApplicationPolicyDTO applicationPolicyDTO) { - - boolean sentToDevice = false; - - - for (DeviceIdentifier deviceIdentifier : applicationPolicyDTO.getDeviceIdentifierList()) { - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - - AndroidEnterpriseUser userDetail = AndroidAPIUtils.getAndroidPluginService() - .getEnterpriseUserByDevice(deviceIdentifier.getId()); - if (userDetail != null && userDetail.getEnterpriseId() != null && !userDetail.getEnterpriseId() - .isEmpty() && userDetail.getEmmUsername() != null) { - - if (applicationPolicyDTO.getAction().equals(AndroidConstants.ApplicationInstall.INSTALL)) { - if (applicationPolicyDTO.getPolicy() == null) { - ProfileFeature feature = AndroidDeviceUtils.getEnrollmentFeature(deviceIdentifier); - EnterpriseInstallPolicy enterpriseInstallPolicy = AndroidEnterpriseUtils - .getDeviceAppPolicy(null, feature, userDetail); - - List apps = new ArrayList<>(); - boolean isAppWhitelisted = false; - for (EnterpriseApp enterpriseApp : enterpriseInstallPolicy.getApps()) { - apps.add(enterpriseApp.getProductId()); - String packageName = enterpriseApp.getProductId().replace("app:", ""); - if (applicationPolicyDTO.getApplicationDTO().getPackageName().equals(packageName)) { - isAppWhitelisted = true; - } - } - - if (enterpriseInstallPolicy.getProductSetBehavior().equals(AndroidConstants - .ApplicationInstall.BEHAVIOUR_WHITELISTED_APPS_ONLY)) { - // This app can only be installed if the app is approved by whitelist to user. - if (!isAppWhitelisted) { - String errorMessage = "App: " + applicationPolicyDTO.getApplicationDTO() - .getPackageName() + " for device " + deviceIdentifier.getId(); - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } - } - googleAPIInvoker.installApps(enterpriseConfigs.getEnterpriseId(), userDetail - .getGoogleUserId(), userDetail.getAndroidPlayDeviceId(), "app:" + - applicationPolicyDTO.getApplicationDTO().getPackageName()); - - sentToDevice = true; - } - } else if (applicationPolicyDTO.getAction().equals(AndroidConstants.ApplicationInstall.UNINSTALL)) { - - googleAPIInvoker.uninstallApps(enterpriseConfigs.getEnterpriseId(), userDetail - .getGoogleUserId(), userDetail.getAndroidPlayDeviceId(), "app:" + - applicationPolicyDTO.getApplicationDTO().getPackageName()); - sentToDevice = true; - } - - } - - } catch (EnterpriseServiceException e) { - String errorMessage = "App install failed for device " + deviceIdentifier.getId(); - log.error(errorMessage); - return Response.status(Response.Status.NOT_FOUND).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND) - .setMessage(errorMessage).build()).build(); - } catch (FeatureManagementException e) { - String errorMessage = "Could not fetch effective policy for device " + deviceIdentifier.getId(); - log.error(errorMessage); - return Response.status(Response.Status.NOT_FOUND).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND) - .setMessage(errorMessage).build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while updating user"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - - if (sentToDevice) { - return Response.status(Response.Status.OK).build(); - } else { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Could not install on the device of user " - ).build()).build(); - } - } - - @Override - @Produces(MediaType.APPLICATION_JSON) - @GET - @Path("/wipe-device") - public Response wipeEnterprise() { - log.warn("Wiping all devices!!!"); - try{ - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigs(); - try { - // Take all enterprise devices in the DB. - List androidEnterpriseUsers = AndroidAPIUtils.getAndroidPluginService() - .getAllEnterpriseDevices(enterpriseConfigs.getEnterpriseId()); - - // Extract the device identifiers of enterprise devices. - List deviceID = new ArrayList<>(); - if (androidEnterpriseUsers != null && !androidEnterpriseUsers.isEmpty()) { - for (AndroidEnterpriseUser userDevice: androidEnterpriseUsers) { - deviceID.add(userDevice.getEmmDeviceId()); - } - } - - List byodDevices = new ArrayList<>(); - List copeDevices = new ArrayList<>(); - // Get all registered device - List devices = AndroidAPIUtils.getDeviceManagementService(). - getAllDevices(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, false); - for (Device device : devices) { // Go through all enrolled devices - if (deviceID.contains(device.getDeviceIdentifier())) { // Filter out only enterprise enrolled devices. - if (device.getEnrolmentInfo().getOwnership().equals(EnrolmentInfo.OwnerShip.BYOD)) { - byodDevices.add(device.getDeviceIdentifier()); - } else { - copeDevices.add(device.getDeviceIdentifier()); - } - } - } - - CommandOperation operation = new CommandOperation(); - operation.setType(Operation.Type.COMMAND);//TODO: Check if this should be profile - // type when implementing COPE/COSU - if (byodDevices != null && !byodDevices.isEmpty()) { // BYOD devices only needs a data wipe(work profile) - log.warn("Wiping " + byodDevices.size() + " BYOD devices"); - operation.setCode(AndroidConstants.OperationCodes.ENTERPRISE_WIPE); - } else if (copeDevices != null && !copeDevices.isEmpty()) { - log.warn("Wiping " + copeDevices.size() + " COPE/COSU devices"); - operation.setCode(AndroidConstants.OperationCodes.WIPE_DATA); - } - AndroidDeviceUtils.getOperationResponse(deviceID, operation); - log.warn("Added wipe to all devices"); - return Response.status(Response.Status.OK).build(); - } catch (EnterpriseServiceException e) { - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Error when saving configs").build()).build(); - } catch (OperationManagementException e) { - String errorMessage = "Could not add wipe command to enterprise " + enterpriseConfigs.getEnterpriseId(); - log.error(errorMessage); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (DeviceManagementException e) { - String errorMessage = "Could not add wipe command to enterprise " + enterpriseConfigs.getEnterpriseId() + - " due to an error in device management"; - log.error(errorMessage); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (InvalidDeviceException e) { - String errorMessage = "Could not add wipe command to enterprise due to invalid device ids"; - log.error(errorMessage); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } catch (NotFoundException e) { - String errorMessage = "Not found"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Unexpected server error"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing wipe enterprice command"; - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build(); - } - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceManagementAPIImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceManagementAPIImpl.java deleted file mode 100644 index 72006e78d..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceManagementAPIImpl.java +++ /dev/null @@ -1,402 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - * Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.mobile.android.api.impl; - -import com.google.api.client.http.HttpStatusCodes; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.application.mgt.common.SubAction; -import org.wso2.carbon.device.application.mgt.common.SubscriptionType; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; -import org.wso2.carbon.device.mgt.mobile.android.api.DeviceManagementAPI; -import org.wso2.carbon.device.mgt.mobile.android.api.invoker.GoogleAPIInvoker; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidPluginConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.Message; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseConfigs; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidApplication; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidDevice; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseApp; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseInstallPolicy; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.*; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidDeviceUtils; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidEnterpriseUtils; - -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -@Path("/devices") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class DeviceManagementAPIImpl implements DeviceManagementAPI { - - private static final Log log = LogFactory.getLog(DeviceManagementAPIImpl.class); - - @PUT - @Path("/{id}/applications") - @Override - public Response updateApplicationList(@PathParam("id") - @NotNull - @Size(min = 2, max = 45) - @Pattern(regexp = "^[A-Za-z0-9]*$") - String id, List androidApplications) { - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Message responseMessage = androidService.updateApplicationList(id, androidApplications); - return Response.status(Response.Status.ACCEPTED).entity(responseMessage).build(); - } catch (ApplicationManagementException e) { - String msg = "Error occurred while modifying the application list."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - } - - @PUT - @Path("/{id}/pending-operations") - @Override - public Response getPendingOperations(@QueryParam("disableGoogleApps") boolean disableGoogleApps, - @PathParam("id") String id, - @HeaderParam("If-Modified-Since") String ifModifiedSince, - List resultOperations) { - if (id == null || id.isEmpty()) { - String msg = "Device identifier is null or empty, hence returning device not found"; - log.error(msg); - return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); - } - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); - List pendingOperations = androidService - .getPendingOperations(deviceIdentifier, resultOperations); - if (pendingOperations != null && !disableGoogleApps) { - handleEnrollmentGoogleApps(pendingOperations, deviceIdentifier); - } - return Response.status(Response.Status.CREATED).entity(pendingOperations).build(); - } catch (InvalidDeviceException e) { - String msg = "Device identifier is invalid. Device identifier " + id; - log.error(msg, e); - return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing get pending operations"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting pending operations of the device."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - } - - @POST - @Override - public Response enrollDevice(@Valid AndroidDevice androidDevice) { - if (androidDevice == null) { - String errorMessage = "The payload of the android device enrollment is incorrect."; - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - String token = null; - String googleEMMAndroidId = null; - String googleEMMDeviceId = null; - if (androidDevice.getProperties() != null) { - for (Device.Property property : androidDevice.getProperties()) { - if (property.getName().equals(AndroidPluginConstants.GOOGLE_AFW_EMM_ANDROID_ID)) { - googleEMMAndroidId = property.getValue(); - } else if (property.getName().equals(AndroidPluginConstants.GOOGLE_AFW_DEVICE_ID)) { - googleEMMDeviceId = property.getValue(); - } - } - if (googleEMMAndroidId != null && googleEMMDeviceId != null) { - EnterpriseUser user = new EnterpriseUser(); - user.setAndroidPlayDeviceId(googleEMMAndroidId); - user.setEmmDeviceIdentifier(googleEMMDeviceId); - try { - AndroidEnterpriseAPIImpl enterpriseService = new AndroidEnterpriseAPIImpl(); - token = enterpriseService.insertUser(user); - } catch (EnterpriseServiceException e) { - //todo - } - } - } - Message message = androidService.enrollDevice(androidDevice); - if (token != null) { - message.setResponseMessage("Google response token" + token); - } - return Response.status(Integer.parseInt(message.getResponseCode())) - .entity(message.getResponseMessage()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while enrolling device"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while enrolling the android, which carries the id '" + androidDevice - .getDeviceIdentifier() + "'"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - } - - @GET - @Path("/{id}/status") - @Override - public Response isEnrolled(@PathParam("id") String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { - DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Message responseMessage = androidService.isEnrolled(id, deviceIdentifier); - return Response.status(Integer.parseInt(responseMessage.getResponseCode())).entity(responseMessage).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while checking enrollment status of the device."; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - } - - @PUT - @Path("/{id}") - @Override - public Response modifyEnrollment(@PathParam("id") String id, @Valid AndroidDevice androidDevice) { - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - if (androidService.modifyEnrollment(id, androidDevice)) { - Message responseMessage = new Message(); - responseMessage.setResponseCode(Response.Status.ACCEPTED.toString()); - responseMessage.setResponseMessage("Enrollment of Android device that " + - "carries the id '" + id + "' has successfully updated"); - return Response.status(Response.Status.ACCEPTED).entity(responseMessage).build(); - } else { - Message responseMessage = new Message(); - responseMessage.setResponseCode(Response.Status.NOT_MODIFIED.toString()); - responseMessage.setResponseMessage("Enrollment of Android device that " + - "carries the id '" + id + "' has not been updated"); - return Response.status(Response.Status.NOT_MODIFIED).entity(responseMessage).build(); - } - } catch (BadRequestException e) { - String errorMessage = "The payload of the android device enrollment is incorrect."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (NotFoundException e) { - String errorMessage = "The device to be modified doesn't exist."; - log.error(errorMessage, e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while modifying enrollment"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (DeviceManagementException e) { - String msg = - "Error occurred while modifying enrollment of the Android device that carries the id '" + id + "'"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - } - - @DELETE - @Path("/{id}") - @Override - public Response disEnrollDevice(@PathParam("id") String id) { - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - if (androidService.disEnrollDevice(id)) { - String msg = "Android device that carries id '" + id + "' is successfully "; - Message responseMessage = new Message(); - responseMessage.setResponseCode(Response.Status.OK.toString()); - responseMessage.setResponseMessage(msg + "dis-enrolled"); - return Response.status(Response.Status.OK).entity(responseMessage).build(); - } else { - Message responseMessage = new Message(); - responseMessage.setResponseCode(Response.Status.NOT_FOUND.toString()); - responseMessage.setResponseMessage("Android device that carries id '" + id + "' is not available"); - return Response.status(Response.Status.NOT_FOUND).entity(responseMessage).build(); - } - } catch (DeviceManagementException e) { - String msg = "Error occurred while %s the Android device that carries the id '" + id + "'"; - msg = String.format(msg, "dis-enrolling"); - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - } - - private void handleEnrollmentGoogleApps(List operations, DeviceIdentifier - deviceIdentifier) { - boolean containsGoogleAppPolicy = false; - for (int x = 0; x < operations.size() && !containsGoogleAppPolicy; x++) { - Operation operation = operations.get(x); - - // Check if the operation has a policy bundle inside. - if (operation.getCode().equals(AndroidConstants.OperationCodes.POLICY_BUNDLE)) { - ArrayList operationPayLoad = (ArrayList) operation.getPayLoad(); - - - // If there is a policy bundle, read its payload - for (int i = 0; i < operationPayLoad.size() && !containsGoogleAppPolicy; i++) { - Object policy = operationPayLoad.get(i); - ProfileOperation profileOperation = (ProfileOperation) policy; - String code = profileOperation.getCode(); - - // Find if there is an ENROLLMENT_APP_INSTALL payload - if (code.equals(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE)) { - String payload = profileOperation.getPayLoad().toString(); - JsonElement appListElement = new JsonParser().parse(payload).getAsJsonObject() - .get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE); - JsonArray appListArray = appListElement.getAsJsonArray(); - - // Find if there are Apps with Work profile configurations - boolean alreadySendToGoogle = false; - for (JsonElement appElement : appListArray) { - JsonElement googlePolicyPayload = appElement.getAsJsonObject(). - get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD); - if (googlePolicyPayload != null) { - String uuid = appElement.getAsJsonObject().get("uuid").toString(); - containsGoogleAppPolicy = true;// breaking out of outer for loop - try { - uuid = uuid.replace("\"", ""); - if (alreadySendToGoogle) { - sendPayloadToGoogle(uuid, payload, deviceIdentifier, false); - } else { - sendPayloadToGoogle(uuid, payload, deviceIdentifier, true); - alreadySendToGoogle = true; - } - } catch (org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException e) { - String errorMessage = "App install failed for device " + deviceIdentifier.getId(); - log.error(errorMessage, e); - } - } - } - - } - } - } - } - } - - /** - * Sends the app install policy to Google - * @param payload policy profile - * @param deviceIdentifier device to apply policy - */ - private void sendPayloadToGoogle(String uuid, String payload, DeviceIdentifier deviceIdentifier, - boolean requireSendingToGoogle) throws - org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException { - try { - EnterpriseConfigs enterpriseConfigs = AndroidEnterpriseUtils.getEnterpriseConfigsFromGoogle(); - if (enterpriseConfigs.getErrorResponse() == null) { - GoogleAPIInvoker googleAPIInvoker = new GoogleAPIInvoker(enterpriseConfigs.getEsa()); - AndroidEnterpriseUser userDetail = AndroidAPIUtils.getAndroidPluginService() - .getEnterpriseUserByDevice(deviceIdentifier.getId()); - if (userDetail != null && userDetail.getEnterpriseId() != null && !userDetail.getEnterpriseId() - .isEmpty() && userDetail.getEmmUsername() != null && payload != null) { - EnterpriseInstallPolicy enterpriseInstallPolicy = AndroidEnterpriseUtils - .getDeviceAppPolicy(payload, null, userDetail); - - List apps = new ArrayList<>(); - for (EnterpriseApp enterpriseApp : enterpriseInstallPolicy.getApps()) { - apps.add(enterpriseApp.getProductId()); - } - if (requireSendingToGoogle) { - googleAPIInvoker.approveAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail - .getGoogleUserId(), apps, enterpriseInstallPolicy.getProductSetBehavior()); - googleAPIInvoker.updateAppsForUser(enterpriseConfigs.getEnterpriseId(), userDetail.getGoogleUserId(), - AndroidEnterpriseUtils.convertToDeviceInstance(enterpriseInstallPolicy)); - } - AndroidAPIUtils.getAppSubscriptionService().performEntAppSubscription(uuid, - Arrays.asList(CarbonContext.getThreadLocalCarbonContext().getUsername()), - SubscriptionType.USER.toString(), SubAction.INSTALL.toString(), false); - } - } - } catch (EnterpriseServiceException e) { - String errorMessage = "App install failed for device " + deviceIdentifier.getId(); - log.error(errorMessage); - } - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceManagementAdminAPIImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceManagementAdminAPIImpl.java deleted file mode 100644 index 5221598fc..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceManagementAdminAPIImpl.java +++ /dev/null @@ -1,1095 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.api.impl; - -import com.google.api.client.http.HttpStatusCodes; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; -import org.wso2.carbon.device.mgt.mobile.android.api.DeviceManagementAdminAPI; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationInstallationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationRestrictionBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationUninstallationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationUpdateBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.BlacklistApplicationsBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.CameraBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.DeviceLockBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.DisplayMessageBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EncryptionBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.FileTransferBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.GlobalProxyBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.LockCodeBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.NotificationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.PasswordPolicyBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.UpgradeFirmwareBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.VpnBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WebClipBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WifiBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WipeDataBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils; - -import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.List; - -@Path("/admin/devices") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class DeviceManagementAdminAPIImpl implements DeviceManagementAdminAPI { - - private static final Log log = LogFactory.getLog(DeviceManagementAdminAPIImpl.class); - - @POST - @Path("/file-transfer") - @Override - public Response fileTransfer(FileTransferBeanWrapper fileTransferBeanWrapper) { - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.fileTransfer(fileTransferBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance for file transfer operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e) { - String errorMessage = "Invalid Device Identifiers ( " + fileTransferBeanWrapper.getDeviceIDs() + " ) found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing file tranfer operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/lock-devices") - @Override - public Response configureDeviceLock(DeviceLockBeanWrapper deviceLockBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android device lock operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.configureDeviceLock(deviceLockBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing device lock operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/unlock-devices") - @Override - public Response configureDeviceUnlock(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android device unlock operation."); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.configureDeviceUnlock(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing device unlock operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/location") - @Override - public Response getDeviceLocation(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android device location operation."); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.getDeviceLocation(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while retrieving device location"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/clear-password") - @Override - public Response removePassword(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android clear password operation."); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.removePassword(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance."; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing remove password operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/control-camera") - @Override - public Response configureCamera(CameraBeanWrapper cameraBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android Camera operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.configureCamera(cameraBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing control camera operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/info") - @Override - public Response getDeviceInformation(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking get Android device information operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.getDeviceInformation(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while retrieving device information"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/logcat") - @Override - public Response getDeviceLogcat(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking get Android device logcat operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.getDeviceLogcat(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while retrieving device logcat"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/enterprise-wipe") - @Override - public Response wipeDevice(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking enterprise-wipe device operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.wipeDevice(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing enterprice wipe device operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/wipe") - @Override - public Response wipeData(WipeDataBeanWrapper wipeDataBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android wipe-data device operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.wipeData(wipeDataBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing Android wipe-data device operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/applications") - @Override - public Response getApplications(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android getApplicationList device operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.getApplications(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing Android getApplicationList device operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/ring") - @Override - public Response ringDevice(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android ring-device device operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.ringDevice(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing Android ring device operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/reboot") - @Override - public Response rebootDevice(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android reboot-device device operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.rebootDevice(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing Android reboot device operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/change-LockTask") - @Override - public Response changeLockTask(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android change LockTask mode operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.changeLockTask(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing Android change LockTask mode operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/mute") - @Override - public Response muteDevice(List deviceIDs) { - if (log.isDebugEnabled()) { - log.debug("Invoking mute device operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.muteDevice(deviceIDs); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing mute device operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/install-application") - @Override - public Response installApplication( - ApplicationInstallationBeanWrapper applicationInstallationBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'InstallApplication' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.installApplication(applicationInstallationBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing install application operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/update-application") - @Override - public Response updateApplication(ApplicationUpdateBeanWrapper applicationUpdateBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'UpdateApplication' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.updateApplication(applicationUpdateBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing update application operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/uninstall-application") - @Override - public Response uninstallApplication( - ApplicationUninstallationBeanWrapper applicationUninstallationBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'UninstallApplication' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.uninstallApplication(applicationUninstallationBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing uninstall application operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/blacklist-applications") - @Override - public Response blacklistApplications(@Valid BlacklistApplicationsBeanWrapper blacklistApplicationsBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'Blacklist-Applications' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.blacklistApplications(blacklistApplicationsBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing blacklist application operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/upgrade-firmware") - @Override - public Response upgradeFirmware(UpgradeFirmwareBeanWrapper upgradeFirmwareBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android upgrade-firmware device operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.upgradeFirmware(upgradeFirmwareBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing upgrade firmware operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/configure-vpn") - @Override - public Response configureVPN(VpnBeanWrapper vpnConfiguration) { - if (log.isDebugEnabled()) { - log.debug("Invoking Android VPN device operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.configureVPN(vpnConfiguration); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing configure vpn operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/send-notification") - @Override - public Response sendNotification(NotificationBeanWrapper notificationBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'notification' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.sendNotification(notificationBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing send notification operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/configure-wifi") - @Override - public Response configureWifi(WifiBeanWrapper wifiBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'configure wifi' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.configureWifi(wifiBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing configure wifi operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/encrypt-storage") - @Override - public Response encryptStorage(EncryptionBeanWrapper encryptionBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'encrypt' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.encryptStorage(encryptionBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing encrypt operation operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/change-lock-code") - @Override - public Response changeLockCode(LockCodeBeanWrapper lockCodeBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'change lock code' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.changeLockCode(lockCodeBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing change lock code operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/set-password-policy") - @Override - public Response setPasswordPolicy(PasswordPolicyBeanWrapper passwordPolicyBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'password policy' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.setPasswordPolicy(passwordPolicyBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing set password policy operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("set-webclip") - @Override - public Response setWebClip(WebClipBeanWrapper webClipBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'webclip' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.setWebClip(webClipBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing set webclip operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/configure-global-proxy") - @Override - public Response setRecommendedGlobalProxy(GlobalProxyBeanWrapper globalProxyBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Applying 'configure-global-proxy' operation: " + - globalProxyBeanWrapper.getOperation().toJSON() + " for Devices: [" - + String.join(",", globalProxyBeanWrapper.getDeviceIDs()) + "]"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.setRecommendedGlobalProxy(globalProxyBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while applying 'configure-global-proxy' operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/send-app-conf") - @Override - public Response sendApplicationConfiguration( - ApplicationRestrictionBeanWrapper applicationRestrictionBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'send application configuration' operation"); - } - - try{ - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - ProfileOperation operation = androidService.sendApplicationConfiguration(applicationRestrictionBeanWrapper); - DeviceIdentifier deviceIdentifier; - List deviceIdentifiers = new ArrayList<>(); - for (String deviceId : applicationRestrictionBeanWrapper.getDeviceIDs()) { - deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); - deviceIdentifiers.add(deviceIdentifier); - } - Activity activity = AndroidAPIUtils.getDeviceManagementService().addOperation( - DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers); - return Response.status(Response.Status.CREATED).entity(activity).build(); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while sending app configuration"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @POST - @Path("/configure-display-message") - @Override - public Response configureDisplayMessage(DisplayMessageBeanWrapper displayMessageBeanWrapper) { - if (log.isDebugEnabled()) { - log.debug("Invoking 'configure-display-message' operation"); - } - - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Activity activity = androidService.configureDisplayMessage(displayMessageBeanWrapper); - return Response.status(Response.Status.CREATED).entity(activity).build(); - - } catch (OperationManagementException e) { - String errorMessage = "Issue in retrieving operation management service instance"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (BadRequestException e){ - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while executing configure-display-message operation"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceTypeConfigurationAPIImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceTypeConfigurationAPIImpl.java deleted file mode 100644 index 14abd8786..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/DeviceTypeConfigurationAPIImpl.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.mobile.android.api.impl; - -import com.google.api.client.http.HttpStatusCodes; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException; -import org.wso2.carbon.device.mgt.common.license.mgt.License; -import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService; -import org.wso2.carbon.device.mgt.mobile.android.api.DeviceTypeConfigurationAPI; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.AndroidPlatformConfiguration; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils; - -import javax.validation.Valid; -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.Map; - -@Path("/configuration") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class DeviceTypeConfigurationAPIImpl implements DeviceTypeConfigurationAPI { - - private static final Log log = LogFactory.getLog(DeviceTypeConfigurationAPIImpl.class); - - @GET - @Override - public Response getConfiguration( - @HeaderParam("If-Modified-Since") String ifModifiedSince) { - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - PlatformConfiguration platformConfiguration = androidService.getPlatformConfig(); - return Response.status(Response.Status.OK).entity(platformConfiguration).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving the Android tenant configuration"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - } - - @PUT - @Override - public Response updateConfiguration( - @Valid AndroidPlatformConfiguration androidPlatformConfiguration) { - try { - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - androidService.updateConfiguration(androidPlatformConfiguration); - return Response.status(Response.Status.OK) - .entity("Android platform configuration has been updated successfully.").build(); - } catch (BadRequestException e) { - String msg = "The payload of the android platform configuration is incorrect."; - log.error(msg, e); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(msg).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String msg = "Error occurred while modifying configuration settings of Android platform"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - - } - - @GET - @Path("/license") - @Produces(MediaType.TEXT_PLAIN) - public Response getLicense( - @HeaderParam("If-Modified-Since") String ifModifiedSince) { - try { - License license = AndroidAPIUtils.getDeviceManagementService() - .getLicense(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, - DeviceManagementConstants.LanguageCodes.LANGUAGE_CODE_ENGLISH_US); - return Response.status(Response.Status.OK).entity((license == null) ? null : license.getText()).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving the license configured for Android device enrolment"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(msg).build()).build(); - } - } - - @GET - @Path("/enrollment-qr-config/{ownershipType}") - @Produces(MediaType.APPLICATION_JSON) - public Response getQRConfig( - @PathParam("ownershipType") String ownershipType) { - try { - DeviceTypeCommonService deviceTypeCommonService = AndroidAPIUtils.getDeviceTypeCommonService(); - Map enrollmentQRConfig = deviceTypeCommonService.getEnrollmentQRCode(ownershipType); - if (enrollmentQRConfig.isEmpty()) { - String msg = "Couldn't find Enrollment QR code config for Android. Please contact administrator."; - log.error(msg); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - return Response.status(Response.Status.OK).entity(enrollmentQRConfig).build(); - } catch (BadRequestException e) { - String msg = "Bad Request, trying to get Enrollment QR code for invalid device ownership type " - + ownershipType; - log.error(msg, e); - return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); - } catch (DeviceManagementException e) { - String msg = "Error occurred while retrieving the license configured for Android device enrolment"; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } catch (InvalidConfigurationException e) { - String msg = "Platform configuration is not configured properly to generate QR code for the Android " - + "enrollment. Device ownership mode is " + ownershipType; - log.error(msg, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); - } - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/EventReceiverAPIImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/EventReceiverAPIImpl.java deleted file mode 100644 index b4d230633..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/impl/EventReceiverAPIImpl.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.api.impl; - -import com.google.api.client.http.HttpStatusCodes; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.mobile.android.api.EventReceiverAPI; -import org.wso2.carbon.device.mgt.mobile.android.common.Message; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceState; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EventBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.*; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; -import org.wso2.carbon.device.mgt.mobile.android.api.util.AndroidAPIUtils; - -import javax.validation.Valid; -import javax.validation.constraints.Size; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import java.util.List; - -@Path("/events") -public class EventReceiverAPIImpl implements EventReceiverAPI { - - private static final Log log = LogFactory.getLog(EventReceiverAPIImpl.class); - - @POST - @Path("/publish") - @Override - public Response publishEvents(@Valid EventBeanWrapper eventBeanWrapper) { - try{ - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - Message message = androidService.publishEvents(eventBeanWrapper); - return Response.status(Integer.parseInt(message.getResponseCode())).entity(message.getResponseMessage()).build(); - } catch (UnexpectedServerErrorException e) { - String errorMessage = "Error occurred while getting the Data publisher Service instance."; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occurred while publishing events."; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } catch (DeviceManagementException e) { - String errorMessage = "Error occurred while checking Operation Analytics is Enabled."; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } - - @GET - @Override - public Response retrieveAlerts(@QueryParam("id") - @Size(min = 2, max = 45) - String deviceId, - @QueryParam("from") long from, - @QueryParam("to") long to, - @Size(min = 2, max = 45) - @QueryParam("type") String type, - @HeaderParam("If-Modified-Since") String ifModifiedSince) { - try{ - AndroidService androidService = AndroidAPIUtils.getAndroidService(); - List deviceStates = androidService.retrieveAlerts(deviceId, from, to, type, ifModifiedSince); - return Response.status(Response.Status.OK).entity(deviceStates).build(); - } catch (BadRequestException e){ - String errorMessage = "Request must contain " + - "the device identifier. Optionally, both from and to value should be present to get " + - "alerts between times."; - log.error(errorMessage); - return Response.status(Response.Status.BAD_REQUEST).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_BAD_REQUEST) - .setMessage(errorMessage).build()).build(); - } catch (NotFoundException e) { - String errorMessage = "Class not found"; - log.error(errorMessage, e); - return Response.status(Response.Status.NOT_FOUND).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND) - .setMessage(errorMessage).build()).build(); - } catch (AndroidDeviceMgtPluginException e) { - String errorMessage = "Error occured while retrieving alerts"; - log.error(errorMessage, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR) - .setMessage(errorMessage).build()).build(); - } - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/invoker/GoogleAPIInvoker.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/invoker/GoogleAPIInvoker.java deleted file mode 100644 index 2fd195f2d..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/invoker/GoogleAPIInvoker.java +++ /dev/null @@ -1,355 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.api.invoker; - -import com.google.api.client.auth.oauth2.Credential; -import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import com.google.api.client.http.HttpRequest; -import com.google.api.client.http.HttpRequestInitializer; -import com.google.api.client.http.HttpTransport; -import com.google.api.client.http.javanet.NetHttpTransport; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.services.androidenterprise.AndroidEnterprise; -import com.google.api.services.androidenterprise.AndroidEnterpriseScopes; -import com.google.api.services.androidenterprise.model.AdministratorWebToken; -import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpec; -import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecManagedConfigurations; -import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecPlaySearch; -import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecPrivateApps; -import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecStoreBuilder; -import com.google.api.services.androidenterprise.model.AdministratorWebTokenSpecWebApps; -import com.google.api.services.androidenterprise.model.AuthenticationToken; -import com.google.api.services.androidenterprise.model.Device; -import com.google.api.services.androidenterprise.model.Install; -import com.google.api.services.androidenterprise.model.LocalizedText; -import com.google.api.services.androidenterprise.model.ProductSet; -import com.google.api.services.androidenterprise.model.ProductsListResponse; -import com.google.api.services.androidenterprise.model.StoreCluster; -import com.google.api.services.androidenterprise.model.StoreLayout; -import com.google.api.services.androidenterprise.model.StoreLayoutClustersListResponse; -import com.google.api.services.androidenterprise.model.StoreLayoutPagesListResponse; -import com.google.api.services.androidenterprise.model.StorePage; -import com.google.api.services.androidenterprise.model.User; -import com.google.common.collect.ImmutableList; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStoreCluster; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStorePackages; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseStorePage; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseTokenUrl; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseServiceException; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -public class GoogleAPIInvoker { - - private static final Log log = LogFactory.getLog(GoogleAPIInvoker.class); - private String esa; - - public GoogleAPIInvoker(String esa) { - this.esa = esa; - } - - public String insertUser(String enterpriseId, String username) throws EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - - User user = new User(); - user.setAccountIdentifier(username); - user.setDisplayName(username); - user.setAccountType("userAccount"); - user.setManagementType("emmManaged"); - try { - User addedUser = androidEnterprise.users().insert(enterpriseId, user) - .execute(); - return addedUser.getId(); - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - } - - public String getToken(String enterpriseId, String userId) throws EnterpriseServiceException{ - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - try { - AuthenticationToken tokenResponse = androidEnterprise.users() - .generateAuthenticationToken(enterpriseId, userId).execute(); - return tokenResponse.getToken(); - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs getToken"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - } - - public Device updateAppsForUser(String enterpriseId, String userId , Device device) throws - EnterpriseServiceException{ - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - try { - Device deviceResponse = androidEnterprise.devices().update(enterpriseId, - userId, device.getAndroidId(), device) - .execute(); - return deviceResponse; - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs installApps"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - } - - public Install installApps(String enterpriseId, String userId , String deviceId, String productId) throws - EnterpriseServiceException{ - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - try { - Install install = new Install(); - install.setKind("androidenterprise#install"); - install.setProductId(productId); - return androidEnterprise.installs().update(enterpriseId, userId, deviceId, productId, install).execute(); - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs installApps"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - } - - public void uninstallApps(String enterpriseId, String userId , String deviceId, String productId) throws - EnterpriseServiceException{ - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - try { - androidEnterprise.installs().delete(enterpriseId, userId, deviceId, productId).execute(); - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs installApps"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - } - - public void approveAppsForUser(String enterpriseId, String userId , List products, String approvalType) - throws EnterpriseServiceException{ - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - try { - ProductSet productSet = new ProductSet(); - productSet.setKind("androidenterprise#productSet"); - productSet.setProductId(products); - productSet.setProductSetBehavior(approvalType); - - androidEnterprise.users().setAvailableProductSet(enterpriseId, userId, productSet).execute(); - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs approveAppsForUser"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - } - - public String getAdministratorWebToken(EnterpriseTokenUrl enterpriseTokenUrl) throws EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - AdministratorWebTokenSpec tokenSpec = new AdministratorWebTokenSpec(); - tokenSpec.setParent(enterpriseTokenUrl.getParentHost()); - tokenSpec.setPlaySearch(new AdministratorWebTokenSpecPlaySearch() - .setApproveApps(enterpriseTokenUrl.isApproveApps()) - .setEnabled(enterpriseTokenUrl.isSearchEnabled())); - tokenSpec.setPrivateApps(new AdministratorWebTokenSpecPrivateApps() - .setEnabled(enterpriseTokenUrl.isPrivateAppsEnabled())); - tokenSpec.setWebApps(new AdministratorWebTokenSpecWebApps().setEnabled(enterpriseTokenUrl.isWebAppEnabled())); - tokenSpec.setStoreBuilder(new AdministratorWebTokenSpecStoreBuilder() - .setEnabled(enterpriseTokenUrl.isOrganizeAppPageVisible())); - tokenSpec.setManagedConfigurations(new AdministratorWebTokenSpecManagedConfigurations() - .setEnabled(enterpriseTokenUrl.isManagedConfigEnabled())); - try { - AdministratorWebToken token = androidEnterprise.enterprises() - .createWebToken(enterpriseTokenUrl.getEnterpriseId(), tokenSpec).execute(); - return token.getToken(); - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs installApps"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - } - - public ProductsListResponse listProduct(String enterpriseId, String token) throws EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - try { - if (token == null) { - return androidEnterprise.products().list(enterpriseId).setMaxResults(100l).setApproved(true).execute(); - } else { - return androidEnterprise.products().list(enterpriseId).setMaxResults(100l).setToken(token) - .setApproved(true).execute(); - } - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs installApps"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - } - - public String insertPage(String enterpriseId, EnterpriseStorePage storePage) throws IOException, - EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - List names = - ImmutableList.of(new LocalizedText().setLocale(storePage.getLocale()).setText(storePage.getPageName())); - StorePage page = new StorePage(); - page.setName(names); - return androidEnterprise.storelayoutpages().insert(enterpriseId, page).execute().getId(); - } - - public String updatePage(String enterpriseId, EnterpriseStorePage storePage) throws IOException, - EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - List names = - ImmutableList.of(new LocalizedText().setLocale(storePage.getLocale()).setText(storePage.getPageName())); - StorePage page = new StorePage(); - page.setName(names); - page.setLink(storePage.getLinks()); - return androidEnterprise.storelayoutpages().update(enterpriseId, storePage.getPageId(), page).execute().getId(); - } - - public void deletePage(String enterpriseId, String pageId) throws IOException, - EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - androidEnterprise.storelayoutpages().delete(enterpriseId, pageId).execute(); - } - - public StoreLayoutPagesListResponse listPages(String enterpriseId) throws IOException, - EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - return androidEnterprise.storelayoutpages().list(enterpriseId).execute(); - } - - public StoreLayout setStoreLayout(String enterpriseId, String homepageId) - throws EnterpriseServiceException, IOException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - StoreLayout storeLayout = new StoreLayout(); - storeLayout.setStoreLayoutType("custom"); - storeLayout.setHomepageId(homepageId); - - return androidEnterprise - .enterprises() - .setStoreLayout(enterpriseId, storeLayout) - .execute(); - } - - public String insertCluster(String enterpriseId, EnterpriseStoreCluster storeCluster) throws IOException , - EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - StoreCluster cluster = new StoreCluster(); - List names = - ImmutableList.of(new LocalizedText().setLocale("en").setText(storeCluster.getName())); - cluster.setName(names); - List productIds = new ArrayList<>(); - for (EnterpriseStorePackages packages : storeCluster.getProducts()) { - productIds.add(packages.getPackageId()); - } - cluster.setProductId(productIds); - cluster.setOrderInPage(storeCluster.getOrderInPage()); - return androidEnterprise.storelayoutclusters() - .insert(enterpriseId, storeCluster.getPageId(), cluster) - .execute() - .getId(); - } - - public String updateCluster(String enterpriseId, EnterpriseStoreCluster storeCluster) throws IOException , - EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - StoreCluster cluster = new StoreCluster(); - List names = - ImmutableList.of(new LocalizedText().setLocale("en").setText(storeCluster.getName())); - cluster.setName(names); - List productIds = new ArrayList<>(); - for (EnterpriseStorePackages packages : storeCluster.getProducts()) { - productIds.add(packages.getPackageId()); - } - cluster.setProductId(productIds); - cluster.setOrderInPage(storeCluster.getOrderInPage()); - cluster.setId(storeCluster.getClusterId()); - return androidEnterprise.storelayoutclusters() - .update(enterpriseId, storeCluster.getPageId(), storeCluster.getClusterId(), cluster) - .execute() - .getId(); - } - - public StoreLayoutClustersListResponse getClusters(String enterpriseId, String pageId) - throws IOException, EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - return androidEnterprise.storelayoutclusters().list(enterpriseId, pageId).execute(); - } - - public void deleteCluster(String enterpriseId, String pageId, String clusterId) - throws IOException, EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - androidEnterprise.storelayoutclusters().delete(enterpriseId, pageId, clusterId).execute(); - } - - // Update the pages to include quick links to other pages. - public void addLinks(String enterpriseId, String pageId, List links) - throws IOException , EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - androidEnterprise.storelayoutpages() - .patch(enterpriseId, pageId, new StorePage().setLink(links)).execute(); - } - - public StoreLayout getStoreLayout(String enterpriseId) - throws IOException, EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - - return androidEnterprise - .enterprises() - .getStoreLayout(enterpriseId) - .execute(); - } - - public void unenroll(String enterpriseId) - throws IOException, EnterpriseServiceException { - AndroidEnterprise androidEnterprise = getEnterpriseClient(); - -// androidEnterprise.enterprises().unenroll(enterpriseId).execute(); - } - - private AndroidEnterprise getEnterpriseClient() throws EnterpriseServiceException { - - HttpTransport httpTransport = new NetHttpTransport(); - JacksonFactory jsonFactory = new JacksonFactory(); - - InputStream inputStream = new ByteArrayInputStream(esa.getBytes(StandardCharsets.UTF_8)); - - final Credential credential; - try { - credential = GoogleCredential.fromStream(inputStream, httpTransport, jsonFactory) - .createScoped(AndroidEnterpriseScopes.all()); - } catch (IOException e) { - String msg = "Error occurred while accessing Google APIs"; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } - - HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() { - @Override - public void initialize(HttpRequest request) throws IOException { - credential.initialize(request); - } - }; - - return new AndroidEnterprise.Builder(httpTransport, jsonFactory, httpRequestInitializer) - .build(); - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidDeviceUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidDeviceUtils.java deleted file mode 100644 index d47fd6b68..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidDeviceUtils.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - * Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.api.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException; -import org.wso2.carbon.policy.mgt.common.FeatureManagementException; -import org.wso2.carbon.policy.mgt.core.PolicyManagerService; - -import java.util.ArrayList; -import java.util.List; - -/** - * Util class for holding Android device related util methods. - */ -public class AndroidDeviceUtils { - - private static Log log = LogFactory.getLog(AndroidDeviceUtils.class); - - private AndroidDeviceUtils() { - throw new IllegalStateException("Utility class"); - } - - public static DeviceIdentifier convertToDeviceIdentifierObject(String deviceId) { - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(deviceId); - identifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - return identifier; - } - - public static Activity getOperationResponse(List deviceIDs, Operation operation) - throws OperationManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException { - if (deviceIDs == null || deviceIDs.isEmpty()) { - String errorMessage = "Device identifier list is empty"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - DeviceIdentifier deviceIdentifier; - List deviceIdentifiers = new ArrayList<>(); - for (String deviceId : deviceIDs) { - deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); - deviceIdentifiers.add(deviceIdentifier); - } - return AndroidAPIUtils.getDeviceManagementService().addOperation( - DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers); - } - - public static String getAndroidConfig(PlatformConfiguration configuration, String key) { - String value = null; - if (configuration != null && configuration.getConfiguration() != null && configuration - .getConfiguration().size() > 0) { - List configurations = configuration.getConfiguration(); - for (ConfigurationEntry configurationEntry : configurations) { - if (configurationEntry.getName().equals(key)) { - value = (String)configurationEntry.getValue(); - break; - } - } - } - return value; - } - - public static ProfileFeature getEnrollmentFeature(DeviceIdentifier deviceIdentifier) throws - FeatureManagementException { - PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService(); - - List effectiveProfileFeatures= policyManagerService.getEffectiveFeatures(deviceIdentifier); - - if (effectiveProfileFeatures != null) { - for (ProfileFeature feature : effectiveProfileFeatures) { - if (AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE - .equals(feature.getFeatureCode())) { - return feature; - } - } - } - return null; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidEnterpriseUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidEnterpriseUtils.java deleted file mode 100644 index ef7d94771..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidEnterpriseUtils.java +++ /dev/null @@ -1,552 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.api.util; - -import com.google.api.services.androidenterprise.model.AppVersion; -import com.google.api.services.androidenterprise.model.AutoInstallConstraint; -import com.google.api.services.androidenterprise.model.AutoInstallPolicy; -import com.google.api.services.androidenterprise.model.ConfigurationVariables; -import com.google.api.services.androidenterprise.model.Device; -import com.google.api.services.androidenterprise.model.ManagedConfiguration; -import com.google.api.services.androidenterprise.model.Policy; -import com.google.api.services.androidenterprise.model.Product; -import com.google.api.services.androidenterprise.model.ProductPolicy; - -import com.google.api.services.androidenterprise.model.ProductsListResponse; -import com.google.api.services.androidenterprise.model.VariableSet; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.application.mgt.common.ApplicationArtifact; -import org.wso2.carbon.device.application.mgt.common.LifecycleChanger; -import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; -import org.wso2.carbon.device.application.mgt.common.response.Application; -import org.wso2.carbon.device.application.mgt.common.response.Category; -import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; -import org.wso2.carbon.device.application.mgt.common.wrapper.ApplicationUpdateWrapper; -import org.wso2.carbon.device.application.mgt.common.wrapper.PublicAppReleaseWrapper; -import org.wso2.carbon.device.application.mgt.common.wrapper.PublicAppWrapper; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.BasicUserInfo; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.EnterpriseConfigs; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ErrorResponse; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseApp; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EnterpriseInstallPolicy; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseManagedConfig; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.*; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; -import org.wso2.carbon.user.core.service.RealmService; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.io.InputStream; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class AndroidEnterpriseUtils { - - private static Log log = LogFactory.getLog(AndroidEnterpriseUtils.class); - private static RealmService realmService = null; - private static List templates = Arrays.asList(AndroidConstants - .USER_CLAIM_EMAIL_ADDRESS_PLACEHOLDER, AndroidConstants.USER_CLAIM_FIRST_NAME_PLACEHOLDER, - AndroidConstants.USER_CLAIM_LAST_NAME_PLACEHOLDER); - - public static Device convertToDeviceInstance(EnterpriseInstallPolicy enterpriseInstallPolicy) - throws EnterpriseServiceException { - Device device = new Device(); - device.setManagementType(enterpriseInstallPolicy.getManagementType()); - device.setKind(enterpriseInstallPolicy.getKind()); - device.setAndroidId(enterpriseInstallPolicy.getAndroidId()); - Policy policy = new Policy(); - List policyList = new ArrayList<>(); - - for (EnterpriseApp app : enterpriseInstallPolicy.getApps()) { - ProductPolicy productPolicy = new ProductPolicy(); - AutoInstallPolicy autoInstallPolicy = new AutoInstallPolicy(); - autoInstallPolicy.setAutoInstallMode(app.getAutoInstallMode()); - autoInstallPolicy.setAutoInstallPriority(app.getAutoInstallPriority()); - List autoInstallConstraintList = new ArrayList<>(); - AutoInstallConstraint autoInstallConstraint = new AutoInstallConstraint(); - autoInstallConstraint.setChargingStateConstraint(app.getChargingStateConstraint()); - autoInstallConstraint.setDeviceIdleStateConstraint(app.getDeviceIdleStateConstraint()); - autoInstallConstraint.setNetworkTypeConstraint(app.getNetworkTypeConstraint()); - autoInstallConstraintList.add(autoInstallConstraint); - autoInstallPolicy.setAutoInstallConstraint(autoInstallConstraintList); - - productPolicy.setAutoInstallPolicy(autoInstallPolicy); - productPolicy.setProductId(app.getProductId()); - - // TODO: Cache this against package name - AndroidEnterpriseManagedConfig configs = AndroidAPIUtils.getAndroidPluginService() - .getConfigByPackageName(app.getProductId().replaceFirst("app:", "")); - - if (configs != null && configs.getMcmId() != null) { - ManagedConfiguration managedConfiguration = new ManagedConfiguration(); - ConfigurationVariables configurationVariables = new ConfigurationVariables(); - configurationVariables.setKind("androidenterprise#configurationVariables"); - configurationVariables.setMcmId(configs.getMcmId()); - - List variableSets = new ArrayList<>(); - BasicUserInfo userInfo = getBasicUserInfo(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername()); - for (String key : templates) { - VariableSet variableSet = new VariableSet(); - variableSet.setKind("androidenterprise#variableSet"); - - variableSet.setPlaceholder(key); - String value = getPlaceholderValue(userInfo, key); - if (value == null) { - continue; - } - variableSet.setUserValue(value); - variableSets.add(variableSet); - } - - if (!variableSets.isEmpty()) { - configurationVariables.setVariableSet(variableSets); - } - managedConfiguration.setConfigurationVariables(configurationVariables); - productPolicy.setManagedConfiguration(managedConfiguration); - } - policyList.add(productPolicy); - } - - policy.setProductPolicy(policyList); - policy.setAutoUpdatePolicy(enterpriseInstallPolicy.getAutoUpdatePolicy()); - policy.setProductAvailabilityPolicy(enterpriseInstallPolicy.getProductAvailabilityPolicy()); - device.setPolicy(policy); - return device; - } - - private static String getPlaceholderValue(BasicUserInfo userInfo, String key) { - if (userInfo != null) { - switch (key) { - case AndroidConstants.USER_CLAIM_EMAIL_ADDRESS_PLACEHOLDER: - return userInfo.getEmailAddress(); - case AndroidConstants.USER_CLAIM_FIRST_NAME_PLACEHOLDER: - return userInfo.getFirstname(); - case AndroidConstants.USER_CLAIM_LAST_NAME_PLACEHOLDER: - return userInfo.getLastname(); - } - } - return null; - } - - private static UserStoreManager getUserStoreManager() throws EnterpriseServiceException { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - if (realmService == null) { - realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); - if (realmService == null) { - String msg = "Realm service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - UserStoreManager userStoreManager; - int tenantId = ctx.getTenantId(); - try { - userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); - } catch (UserStoreException e) { - String msg = "Could not create user store manager."; - log.error(msg); - throw new EnterpriseServiceException(msg, e); - } - return userStoreManager; - } - - private static BasicUserInfo getBasicUserInfo(String username) throws EnterpriseServiceException { - UserStoreManager userStoreManager = getUserStoreManager(); - try { - if (!userStoreManager.isExistingUser(username)) { - if (log.isDebugEnabled()) { - log.debug("User by username: " + username + " does not exist."); - } - return null; - } - } catch (UserStoreException e) { - String msg = "Could not get user details of user " + username; - log.error(msg); - throw new EnterpriseServiceException(msg, e); - } - - BasicUserInfo userInfo = new BasicUserInfo(); - userInfo.setUsername(username); - try { - userInfo.setEmailAddress(userStoreManager.getUserClaimValue(username, AndroidConstants.USER_CLAIM_EMAIL_ADDRESS, null)); - userInfo.setFirstname(userStoreManager.getUserClaimValue(username, AndroidConstants.USER_CLAIM_FIRST_NAME, null)); - userInfo.setFirstname(userStoreManager.getUserClaimValue(username, AndroidConstants.USER_CLAIM_LAST_NAME, null)); - } catch (UserStoreException e) { - String msg = "Could not get claims of user " + username; - log.error(msg); - throw new EnterpriseServiceException(msg, e); - } - - return userInfo; - } - - public static EnterpriseConfigs getEnterpriseConfigs() throws AndroidDeviceMgtPluginException { - EnterpriseConfigs enterpriseConfigs = getEnterpriseConfigsFromGoogle(); - if (enterpriseConfigs.getErrorResponse() != null) { - if (enterpriseConfigs.getErrorResponse().getCode() == 500) { - throw new UnexpectedServerErrorException(enterpriseConfigs.getErrorResponse().getMessage()); - } else if (enterpriseConfigs.getErrorResponse().getCode() == 404) { - throw new NotFoundException(enterpriseConfigs.getErrorResponse().getMessage()); - } - } - return enterpriseConfigs; - } - - public static EnterpriseConfigs getEnterpriseConfigsFromGoogle() { - PlatformConfiguration configuration = null; - EnterpriseConfigs enterpriseConfigs = new EnterpriseConfigs(); - try { - configuration = AndroidAPIUtils.getDeviceManagementService(). - getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - } catch (DeviceManagementException e) { - String errorMessage = "Error while fetching tenant configurations for tenant " + - PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - log.error(errorMessage); - // Error is being used in enterprise APIs as well as from getpending operations which should not fail as - // these errors can cause due to issues misconfigurations in policy/esa configs which can cause to break all - // operations, if the error is thrown to cfx error handler - enterpriseConfigs.setErrorResponse(new ErrorResponse.ErrorResponseBuilder().setCode(500l) - .setMessage(errorMessage).build()); - } - String enterpriseId = AndroidDeviceUtils.getAndroidConfig(configuration,"enterpriseId"); - String esa = AndroidDeviceUtils.getAndroidConfig(configuration,"esa"); - if (enterpriseId == null || enterpriseId.isEmpty() || esa == null || esa.isEmpty()) { - String errorMessage = "Tenant is not configured to handle Android for work. Please contact Entgra."; - log.warn(errorMessage); - enterpriseConfigs.setErrorResponse(new ErrorResponse.ErrorResponseBuilder().setCode(404l) - .setMessage(errorMessage).build()); - } - - enterpriseConfigs.setEnterpriseId(enterpriseId); - enterpriseConfigs.setEsa(esa); - return enterpriseConfigs; - } - - public static void persistApp(ProductsListResponse productListResponse) throws ApplicationManagementException { - - ApplicationManager applicationManager = AndroidAPIUtils.getAppManagerService(); - List categories = applicationManager.getRegisteredCategories(); - if (productListResponse != null && productListResponse.getProduct() != null - && !productListResponse.getProduct().isEmpty()) { - - List packageNamesOfApps = new ArrayList<>(); - for (Product product : productListResponse.getProduct()) { - packageNamesOfApps.add(product.getProductId().replaceFirst("app:", "")); - } - - List existingApps = applicationManager.getApplications(packageNamesOfApps); - List products = productListResponse.getProduct(); - - for (Application app : existingApps){ - for (Product product : products){ - if (product.getProductId().replaceFirst("app:", "").equals(app.getPackageName())){ - ApplicationUpdateWrapper applicationUpdateWrapper = generatePubAppUpdateWrapper(product, categories); - applicationManager.updateApplication(app.getId(), applicationUpdateWrapper); - - PublicAppReleaseWrapper publicAppReleaseWrapper = new PublicAppReleaseWrapper(); - if (app.getSubMethod() - .equalsIgnoreCase(AndroidConstants.ApplicationProperties.FREE_SUB_METHOD)) { - publicAppReleaseWrapper.setPrice(0.0); - } else { - publicAppReleaseWrapper.setPrice(1.0); - } - - publicAppReleaseWrapper.setDescription(product.getRecentChanges()); - publicAppReleaseWrapper.setReleaseType("ga"); - publicAppReleaseWrapper.setVersion(getAppString(product.getAppVersion())); - publicAppReleaseWrapper.setSupportedOsVersions(product.getMinAndroidSdkVersion() + "-ALL"); - - ApplicationArtifact applicationArtifact = generateArtifacts(product); - applicationManager.updatePubAppRelease(app.getApplicationReleases().get(0).getUuid(), - publicAppReleaseWrapper, applicationArtifact); - products.remove(product); - break; - } - } - } - - for (Product product : products) { - if (product.getAppVersion() == null) { // This is to handled removed apps from playstore - continue; - } - - // Generate App wrapper - PublicAppWrapper publicAppWrapper = generatePubAppWrapper(product, categories); - PublicAppReleaseWrapper appReleaseWrapper = new PublicAppReleaseWrapper(); - - if (publicAppWrapper.getSubMethod() - .equalsIgnoreCase(AndroidConstants.ApplicationProperties.FREE_SUB_METHOD)) { - appReleaseWrapper.setPrice(0.0); - } else { - appReleaseWrapper.setPrice(1.0); - } - - appReleaseWrapper.setDescription(product.getRecentChanges()); - appReleaseWrapper.setReleaseType("ga"); - appReleaseWrapper.setVersion(getAppString(product.getAppVersion())); - appReleaseWrapper.setPackageName(product.getProductId().replaceFirst("app:", "")); - appReleaseWrapper.setSupportedOsVersions(String.valueOf(product.getMinAndroidSdkVersion()) + "-ALL"); - - publicAppWrapper.setPublicAppReleaseWrappers( - Arrays.asList(new PublicAppReleaseWrapper[] { appReleaseWrapper })); - - // Generate artifacts - ApplicationArtifact applicationArtifact = generateArtifacts(product); - - Application application = applicationManager.createPublicApp(publicAppWrapper, applicationArtifact); - if (application != null && (application.getApplicationReleases().get(0).getCurrentStatus() == null - || application.getApplicationReleases().get(0).getCurrentStatus().equals("CREATED"))) { - String uuid = application.getApplicationReleases().get(0).getUuid(); - LifecycleChanger lifecycleChanger = new LifecycleChanger(); - lifecycleChanger.setAction("IN-REVIEW"); - applicationManager.changeLifecycleState(uuid, lifecycleChanger); - lifecycleChanger.setAction("APPROVED"); - applicationManager.changeLifecycleState(uuid, lifecycleChanger); - lifecycleChanger.setAction("PUBLISHED"); - applicationManager.changeLifecycleState(uuid, lifecycleChanger); - } - } - } - } - - private static ApplicationUpdateWrapper generatePubAppUpdateWrapper(Product product, List categories) { - ApplicationUpdateWrapper applicationUpdateWrapper = new ApplicationUpdateWrapper(); - applicationUpdateWrapper.setName(product.getTitle()); - applicationUpdateWrapper.setDescription(product.getDescription()); - applicationUpdateWrapper.setCategories( - Collections.singletonList(AndroidConstants.GOOGLE_PLAY_SYNCED_APP_CATEGORY));//Default category - for (Category category : categories) { - if (product.getCategory() == null) { - List pubAppCategories = new ArrayList<>(); - pubAppCategories.add(AndroidConstants.GOOGLE_PLAY_SYNCED_APP_CATEGORY); - applicationUpdateWrapper.setCategories(pubAppCategories); - break; - } else if (product.getCategory().equalsIgnoreCase(category.getCategoryName())) { - List pubAppCategories = new ArrayList<>(); - pubAppCategories.add(category.getCategoryName()); - pubAppCategories.add(AndroidConstants.GOOGLE_PLAY_SYNCED_APP_CATEGORY); - applicationUpdateWrapper.setCategories(pubAppCategories); - break; - } - } - if (product.getProductPricing().equalsIgnoreCase(AndroidConstants.ApplicationProperties.FREE_SUB_METHOD)) { - applicationUpdateWrapper.setSubMethod(AndroidConstants.ApplicationProperties.FREE_SUB_METHOD); - } else { - applicationUpdateWrapper.setSubMethod(AndroidConstants.ApplicationProperties.PAID_SUB_METHOD); - } - // TODO: purchase an app from Playstore and see how to capture the real value for price field. - applicationUpdateWrapper.setPaymentCurrency("$"); - return applicationUpdateWrapper; - } - - private static PublicAppWrapper generatePubAppWrapper(Product product, List categories) { - PublicAppWrapper publicAppWrapper = new PublicAppWrapper(); - publicAppWrapper.setName(product.getTitle()); - publicAppWrapper.setDescription(product.getDescription()); - publicAppWrapper.setCategories( - Collections.singletonList(AndroidConstants.GOOGLE_PLAY_SYNCED_APP_CATEGORY));//Default category - for (Category category : categories) { - if (product.getCategory() == null) { - List pubAppCategories = new ArrayList<>(); - pubAppCategories.add(AndroidConstants.GOOGLE_PLAY_SYNCED_APP_CATEGORY); - publicAppWrapper.setCategories(pubAppCategories); - break; - } else if (product.getCategory().equalsIgnoreCase(category.getCategoryName())) { - List pubAppCategories = new ArrayList<>(); - pubAppCategories.add(category.getCategoryName()); - pubAppCategories.add(AndroidConstants.GOOGLE_PLAY_SYNCED_APP_CATEGORY); - publicAppWrapper.setCategories(pubAppCategories); - break; - } - } - if (product.getProductPricing().equalsIgnoreCase(AndroidConstants.ApplicationProperties.FREE_SUB_METHOD)) { - publicAppWrapper.setSubMethod(AndroidConstants.ApplicationProperties.FREE_SUB_METHOD); - } else { - publicAppWrapper.setSubMethod(AndroidConstants.ApplicationProperties.PAID_SUB_METHOD); - } - // TODO: purchase an app from Playstore and see how to capture the real value for price field. - publicAppWrapper.setPaymentCurrency("$"); - publicAppWrapper.setDeviceType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - return publicAppWrapper; - } - - private static ApplicationArtifact generateArtifacts(Product product) throws ApplicationManagementException { - ApplicationArtifact applicationArtifact = new ApplicationArtifact(); - try { - String iconName = product.getIconUrl().split(".com/")[1]; - applicationArtifact.setIconName(iconName); - InputStream iconInputStream = getInputStream(iconName, product.getIconUrl()); - applicationArtifact.setIconStream(iconInputStream); - Map screenshotMap = new HashMap<>(); - - int numberOfScreenShots = 3;// This is to handle some apps in playstore without 3 screenshots. - if (product.getScreenshotUrls() != null) { - if (product.getScreenshotUrls().size() < 3) { - numberOfScreenShots = product.getScreenshotUrls().size(); - } - for (int y = 1; y < 4; y++) { - int screenshotNumber = y - 1; - if (y > numberOfScreenShots) { - screenshotNumber = 0; - } - String screenshot = product.getScreenshotUrls().get(screenshotNumber); - String screenshotName = screenshot.split(".com/")[1]; - InputStream screenshotInputStream = getInputStream(screenshotName, screenshot); - screenshotMap.put(screenshotName, screenshotInputStream); - } - } else { // Private apps doesn't seem to send screenshots. Handling it. - for (int a = 0; a < 3; a++) { - String screenshot = product.getIconUrl(); - String screenshotName = screenshot.split(".com/")[1]; - InputStream screenshotInputStream = getInputStream(screenshotName, screenshot); - screenshotMap.put(screenshotName, screenshotInputStream); - } - } - applicationArtifact.setScreenshots(screenshotMap); - return applicationArtifact; - } catch (ApplicationManagementException e) { - String msg = "Error occurred while generating Application artifact"; - log.error(msg); - throw new ApplicationManagementException(msg, e); - } - } - - private static InputStream getInputStream(String filename, String url) throws ApplicationManagementException { - URL website; - try { - website = new URL(url); - } catch (MalformedURLException e) { - String msg = "Error occurred while converting the url " + url; - log.error(msg); - throw new ApplicationManagementException(msg, e); - } - ReadableByteChannel rbc = null; - FileOutputStream fos = null; - try { - rbc = Channels.newChannel(website.openStream()); - fos = new FileOutputStream(System.getProperty("java.io.tmpdir") - + File.separator + filename); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - }catch (IOException e) { - String msg = "Error occurred while opening stream for url " + url; - log.error(msg); - throw new ApplicationManagementException(msg, e); - } finally { - try { - fos.close(); - rbc.close(); - } catch (IOException e) {} - } - - File file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename); - InputStream targetStream; - try { - targetStream = new FileInputStream(file); - } catch (FileNotFoundException e) { - String msg = "Error occurred while reading the tmp file " + System.getProperty("java.io.tmpdir") - + File.separator + filename; - log.error(msg); - throw new ApplicationManagementException(msg, e); - } - file.deleteOnExit(); - return targetStream; - } - - private static String getAppString(List appVersions) { - int highestVersionCode = 0; - String highestVersionString = null; - for (AppVersion appVersion : appVersions) { - if (appVersion.getIsProduction() && appVersion.getVersionCode() > highestVersionCode) { - highestVersionCode = appVersion.getVersionCode(); - highestVersionString = appVersion.getVersionString(); - } - } - return highestVersionString; - } - - public static EnterpriseInstallPolicy getDeviceAppPolicy(String appPolicy, - ProfileFeature feature, - AndroidEnterpriseUser userDetail) { - EnterpriseInstallPolicy enterpriseInstallPolicy = new EnterpriseInstallPolicy(); - List apps = new ArrayList<>(); - JsonElement appListElement; - if (appPolicy == null) { - appListElement = new JsonParser().parse(feature.getContent().toString()).getAsJsonObject() - .get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE); - } else { - appListElement = new JsonParser().parse(appPolicy).getAsJsonObject() - .get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE); - } - JsonArray appListArray = appListElement.getAsJsonArray(); - - JsonObject googlePolicyPayload = appListArray.get(0).getAsJsonObject(); -// get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD).getAsString()).getAsJsonObject(); - enterpriseInstallPolicy.setAutoUpdatePolicy(googlePolicyPayload.get("autoUpdatePolicy").getAsString()); - enterpriseInstallPolicy.setProductSetBehavior(googlePolicyPayload.get("productSetBehavior").getAsString()); - -// enterpriseInstallPolicy.setProductAvailabilityPolicy(googlePolicyPayload.get("productAvailabilityPolicy").getAsString()); - enterpriseInstallPolicy.setManagementType("managedProfile"); - enterpriseInstallPolicy.setKind("androidenterprise#device"); - enterpriseInstallPolicy.setAndroidId(userDetail.getAndroidPlayDeviceId()); - enterpriseInstallPolicy.setUsername(userDetail.getEmmUsername()); - - for (JsonElement appElement : appListArray) { - - JsonElement policy = appElement.getAsJsonObject(). - get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD); - if (policy != null) { - JsonObject googlePolicyForApp = new JsonParser().parse(policy.getAsString()).getAsJsonObject(); - EnterpriseApp enterpriseApp = new EnterpriseApp(); - enterpriseApp.setProductId("app:" + googlePolicyForApp.get("packageName").getAsString()); - enterpriseApp.setAutoInstallMode(googlePolicyForApp.get("autoInstallMode").getAsString()); - enterpriseApp.setAutoInstallPriority(googlePolicyForApp.get("autoInstallPriority").getAsInt()); - enterpriseApp.setChargingStateConstraint(googlePolicyForApp.get("chargingStateConstraint").getAsString()); - enterpriseApp.setDeviceIdleStateConstraint(googlePolicyForApp.get("deviceIdleStateConstraint").getAsString()); - enterpriseApp.setNetworkTypeConstraint(googlePolicyForApp.get("networkTypeConstraint").getAsString()); - apps.add(enterpriseApp); - } - } - enterpriseInstallPolicy.setApps(apps); - return enterpriseInstallPolicy; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AndroidOperation.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AndroidOperation.java similarity index 94% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AndroidOperation.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AndroidOperation.java index aeccd384d..3361b90dc 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AndroidOperation.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AndroidOperation.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import com.google.gson.Gson; /* diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AndroidPlatformConfiguration.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AndroidPlatformConfiguration.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AndroidPlatformConfiguration.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AndroidPlatformConfiguration.java index 7dc0505ec..9832c3f03 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AndroidPlatformConfiguration.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AndroidPlatformConfiguration.java @@ -16,11 +16,12 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; +import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AppRestriction.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AppRestriction.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AppRestriction.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AppRestriction.java index 4f82dcc7c..2c8d8c93d 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/AppRestriction.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/AppRestriction.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationInstallation.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationInstallation.java similarity index 97% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationInstallation.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationInstallation.java index 3fcfc34a1..4c90d42cb 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationInstallation.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationInstallation.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationUninstallation.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationUninstallation.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationUninstallation.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationUninstallation.java index e8efbdef0..a5356ae59 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationUninstallation.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationUninstallation.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationUpdate.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationUpdate.java similarity index 97% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationUpdate.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationUpdate.java index cd9084df1..95241b444 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationUpdate.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ApplicationUpdate.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/BlacklistApplications.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/BlacklistApplications.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/BlacklistApplications.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/BlacklistApplications.java index cf99c2cf4..b7db28976 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/BlacklistApplications.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/BlacklistApplications.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Camera.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Camera.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Camera.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Camera.java index 21ee35f08..0dad70364 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Camera.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Camera.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceEncryption.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceEncryption.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceEncryption.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceEncryption.java index 0b5473de1..68ab6ae94 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceEncryption.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceEncryption.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceLock.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceLock.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceLock.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceLock.java index f0475d7c3..e76ff6f1a 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceLock.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceLock.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceState.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceState.java similarity index 97% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceState.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceState.java index 911fe5f37..fb23b0fcc 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DeviceState.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/DeviceState.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Disenrollment.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Disenrollment.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Disenrollment.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Disenrollment.java index 99e329c7d..c591d2ae0 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Disenrollment.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Disenrollment.java @@ -16,11 +16,11 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import java.io.Serializable; @ApiModel(value = "Disenrollment", diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ErrorListItem.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ErrorListItem.java similarity index 97% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ErrorListItem.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ErrorListItem.java index 2d8ca0856..1e48b0183 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ErrorListItem.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ErrorListItem.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ErrorResponse.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ErrorResponse.java similarity index 98% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ErrorResponse.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ErrorResponse.java index 97b7eb768..457782ade 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ErrorResponse.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/ErrorResponse.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/FileTransfer.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/FileTransfer.java similarity index 94% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/FileTransfer.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/FileTransfer.java index 8677147f5..2e8af23a7 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/FileTransfer.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/FileTransfer.java @@ -15,10 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.mdm.services.android.bean.AndroidOperation; import java.io.Serializable; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/LockCode.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/LockCode.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/LockCode.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/LockCode.java index 0e139e924..4c2764dad 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/LockCode.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/LockCode.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Notification.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Notification.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Notification.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Notification.java index ade05a1a4..7cc4d4627 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Notification.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Notification.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/NotifierFrequency.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/NotifierFrequency.java similarity index 81% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/NotifierFrequency.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/NotifierFrequency.java index f441ffb1e..e7061ae91 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/NotifierFrequency.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/NotifierFrequency.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -27,20 +27,9 @@ import java.io.Serializable; description = "This class represents notification frequency configuration.") public class NotifierFrequency extends AndroidOperation implements Serializable { - @ApiModelProperty(name = "type", value = "Notification type", required = true) - private int type; - @ApiModelProperty(name = "value", value = "Notification polling frequency", required = true) private int value; - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - public int getValue() { return value; } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/PasscodePolicy.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/PasscodePolicy.java similarity index 70% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/PasscodePolicy.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/PasscodePolicy.java index 3d29bb60d..c2e48ce70 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/PasscodePolicy.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/PasscodePolicy.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -31,20 +31,13 @@ import java.io.Serializable; + "password policy") public class PasscodePolicy extends AndroidOperation implements Serializable { - @ApiModelProperty(name = "maxFailedAttemptsDeviceLock", value = "The maximum number of times the end-user can enter" - + " his/her device passcode incorrectly. EMM will take different courses of action based on the" - + " OS when the failed attempts exceed the maximum failed attempts. Android devices will be " - + "automatically locked and admin can unlock the device", required = true) + @ApiModelProperty(name = "maxFailedAttempts", value = "The maximum number of times the end-user can enter" + + " his/her device passcode incorrectly. EMM will take different courses of action based on the" + + " OS when the failed attempts exceed the maximum failed attempts. Android devices will be " + + "automatically reset to the original factory settings", required = true) - @Max(10) - private int maxFailedAttemptsDeviceLock; - @ApiModelProperty(name = "maxFailedAttemptsDeviceWipe", value = "The maximum number of times the end-user can enter" - + " his/her device passcode incorrectly. EMM will take different courses of action based on the" - + " OS when the failed attempts exceed the maximum failed attempts. Android devices will be " - + "automatically wiped to factory settings", required = true) - - @Max(10) - private int maxFailedAttemptsDeviceWipe; + @Max(10) + private int maxFailedAttempts; @ApiModelProperty(name = "minLength", value = "The minimum number of alphanumerical values that the " + "end-user can enter as his/her passcode", required = true) @Max(15) @@ -70,12 +63,12 @@ public class PasscodePolicy extends AndroidOperation implements Serializable { + "Minimum length\n" + "Minimum complex characters", required = true) private boolean allowSimple; - public int getMaxFailedAttemptsDeviceLock(){ - return maxFailedAttemptsDeviceLock; + public int getMaxFailedAttempts() { + return maxFailedAttempts; } - public int getMaxFailedAttemptsDeviceWipe(){ - return maxFailedAttemptsDeviceWipe; + public void setMaxFailedAttempts(int maxFailedAttempts) { + this.maxFailedAttempts = maxFailedAttempts; } public int getMinLength() { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/UpgradeFirmware.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/UpgradeFirmware.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/UpgradeFirmware.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/UpgradeFirmware.java index f07a519db..748ee0e59 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/UpgradeFirmware.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/UpgradeFirmware.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Vpn.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Vpn.java similarity index 97% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Vpn.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Vpn.java index 76be3fc28..188d44f8f 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Vpn.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Vpn.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/WebClip.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/WebClip.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/WebClip.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/WebClip.java index 06b815df4..cf39b1070 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/WebClip.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/WebClip.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Wifi.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Wifi.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Wifi.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Wifi.java index d8e130987..8cdf3c58b 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/Wifi.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/Wifi.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/WipeData.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/WipeData.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/WipeData.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/WipeData.java index ff1c05bc0..83efddc12 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/WipeData.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/WipeData.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; +package org.wso2.carbon.mdm.services.android.bean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidApplication.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidApplication.java similarity index 98% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidApplication.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidApplication.java index 1c1776350..8dee1a60d 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidApplication.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidApplication.java @@ -1,4 +1,4 @@ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidDevice.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDevice.java similarity index 98% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidDevice.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDevice.java index 274b6ec89..6c5fcec34 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidDevice.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDevice.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.Device; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidDeviceInfo.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDeviceInfo.java similarity index 99% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidDeviceInfo.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDeviceInfo.java index 148d46d56..41fbb5857 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AndroidDeviceInfo.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AndroidDeviceInfo.java @@ -1,4 +1,4 @@ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AppRestrictionBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AppRestrictionBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AppRestrictionBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AppRestrictionBeanWrapper.java index 70a520b89..64412336e 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/AppRestrictionBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/AppRestrictionBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.AppRestriction; +import org.wso2.carbon.mdm.services.android.bean.AppRestriction; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationInstallationBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationInstallationBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationInstallationBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationInstallationBeanWrapper.java index 688703080..b0bd54cf3 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationInstallationBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationInstallationBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ApplicationInstallation; +import org.wso2.carbon.mdm.services.android.bean.ApplicationInstallation; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationUninstallationBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationUninstallationBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationUninstallationBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationUninstallationBeanWrapper.java index ad88bbb35..28c72c6cd 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationUninstallationBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationUninstallationBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ApplicationUninstallation; +import org.wso2.carbon.mdm.services.android.bean.ApplicationUninstallation; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationUpdateBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationUpdateBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationUpdateBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationUpdateBeanWrapper.java index 241cec506..b202bf883 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationUpdateBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/ApplicationUpdateBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ApplicationUpdate; +import org.wso2.carbon.mdm.services.android.bean.ApplicationUpdate; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/BlacklistApplicationsBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/BlacklistApplicationsBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/BlacklistApplicationsBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/BlacklistApplicationsBeanWrapper.java index 19f0e5a36..32b107bf4 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/BlacklistApplicationsBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/BlacklistApplicationsBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.BlacklistApplications; +import org.wso2.carbon.mdm.services.android.bean.BlacklistApplications; import javax.validation.Valid; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/CameraBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/CameraBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/CameraBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/CameraBeanWrapper.java index 04ac86a90..9f9a014f2 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/CameraBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/CameraBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Camera; +import org.wso2.carbon.mdm.services.android.bean.Camera; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DeviceEnrollmentInfo.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DeviceEnrollmentInfo.java similarity index 98% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DeviceEnrollmentInfo.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DeviceEnrollmentInfo.java index c6882a6e7..b2f77cc31 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DeviceEnrollmentInfo.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DeviceEnrollmentInfo.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DeviceLockBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DeviceLockBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DeviceLockBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DeviceLockBeanWrapper.java index 31e5e41aa..bd668faba 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DeviceLockBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DeviceLockBeanWrapper.java @@ -16,11 +16,11 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceLock; +import org.wso2.carbon.mdm.services.android.bean.DeviceLock; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DisenrollmentBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DisenrollmentBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DisenrollmentBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DisenrollmentBeanWrapper.java index 308da5161..fdcab0120 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DisenrollmentBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/DisenrollmentBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Disenrollment; +import org.wso2.carbon.mdm.services.android.bean.Disenrollment; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EncryptionBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/EncryptionBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EncryptionBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/EncryptionBeanWrapper.java index 557d39540..aeb01400a 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EncryptionBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/EncryptionBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceEncryption; +import org.wso2.carbon.mdm.services.android.bean.DeviceEncryption; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EventBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/EventBeanWrapper.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EventBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/EventBeanWrapper.java index ed4e314d3..c4fb13e07 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EventBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/EventBeanWrapper.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/FileTransferBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/FileTransferBeanWrapper.java similarity index 93% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/FileTransferBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/FileTransferBeanWrapper.java index 4777c3133..d34b00e66 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/FileTransferBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/FileTransferBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.FileTransfer; +import org.wso2.carbon.mdm.services.android.bean.FileTransfer; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/LockCodeBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/LockCodeBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/LockCodeBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/LockCodeBeanWrapper.java index 4cf164d46..364fd39d2 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/LockCodeBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/LockCodeBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.LockCode; +import org.wso2.carbon.mdm.services.android.bean.LockCode; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/NotificationBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/NotificationBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/NotificationBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/NotificationBeanWrapper.java index 97bb7f706..eb82e49ee 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/NotificationBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/NotificationBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Notification; +import org.wso2.carbon.mdm.services.android.bean.Notification; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/PasswordPolicyBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/PasswordPolicyBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/PasswordPolicyBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/PasswordPolicyBeanWrapper.java index b9e728624..e47ece1c5 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/PasswordPolicyBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/PasswordPolicyBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.PasscodePolicy; +import org.wso2.carbon.mdm.services.android.bean.PasscodePolicy; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/UpgradeFirmwareBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/UpgradeFirmwareBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/UpgradeFirmwareBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/UpgradeFirmwareBeanWrapper.java index ed0231d6a..b881422c2 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/UpgradeFirmwareBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/UpgradeFirmwareBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.UpgradeFirmware; +import org.wso2.carbon.mdm.services.android.bean.UpgradeFirmware; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/VpnBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/VpnBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/VpnBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/VpnBeanWrapper.java index 1a2d67a59..e71270d22 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/VpnBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/VpnBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Vpn; +import org.wso2.carbon.mdm.services.android.bean.Vpn; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WebClipBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WebClipBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WebClipBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WebClipBeanWrapper.java index 6f8667311..fb2edc239 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WebClipBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WebClipBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.WebClip; +import org.wso2.carbon.mdm.services.android.bean.WebClip; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WifiBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WifiBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WifiBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WifiBeanWrapper.java index 85e6df2d3..2d63a27d9 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WifiBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WifiBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Wifi; +import org.wso2.carbon.mdm.services.android.bean.Wifi; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WipeDataBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WipeDataBeanWrapper.java similarity index 91% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WipeDataBeanWrapper.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WipeDataBeanWrapper.java index fe753bd3f..b7ebb2903 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/WipeDataBeanWrapper.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/bean/wrapper/WipeDataBeanWrapper.java @@ -15,11 +15,11 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; +package org.wso2.carbon.mdm.services.android.bean.wrapper; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.WipeData; +import org.wso2.carbon.mdm.services.android.bean.WipeData; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ErrorHandler.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ErrorHandler.java similarity index 90% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ErrorHandler.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ErrorHandler.java index 1023bdef2..542cd6078 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ErrorHandler.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ErrorHandler.java @@ -15,7 +15,9 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.addons; +package org.wso2.carbon.mdm.services.android.common; + +import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ErrorMessage.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ErrorMessage.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ErrorMessage.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ErrorMessage.java index a27c9b5ad..fd880c04c 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ErrorMessage.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ErrorMessage.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.addons; +package org.wso2.carbon.mdm.services.android.common; public class ErrorMessage { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/GsonMessageBodyHandler.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/GsonMessageBodyHandler.java similarity index 98% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/GsonMessageBodyHandler.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/GsonMessageBodyHandler.java index bd6b7931f..297630029 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/GsonMessageBodyHandler.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/GsonMessageBodyHandler.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.addons; +package org.wso2.carbon.mdm.services.android.common; import com.google.gson.Gson; import com.google.gson.GsonBuilder; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ValidationInterceptor.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ValidationInterceptor.java similarity index 94% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ValidationInterceptor.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ValidationInterceptor.java index adc298e18..a563f09d1 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ValidationInterceptor.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/common/ValidationInterceptor.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.addons; +package org.wso2.carbon.mdm.services.android.common; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -29,11 +29,7 @@ import org.apache.cxf.message.MessageContentsList; import org.apache.cxf.phase.AbstractPhaseInterceptor; import org.apache.cxf.phase.Phase; -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; +import javax.validation.*; import javax.validation.executable.ExecutableValidator; import java.lang.reflect.Method; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/AndroidAgentException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/AndroidAgentException.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/AndroidAgentException.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/AndroidAgentException.java index 681c39f68..c12d03538 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/AndroidAgentException.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/AndroidAgentException.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.addons; +package org.wso2.carbon.mdm.services.android.exception; /** * diff --git a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/services/DCRService.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/AndroidOperationException.java similarity index 51% rename from components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/services/DCRService.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/AndroidOperationException.java index c170f9c5b..8c68866d8 100644 --- a/components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/src/main/java/org/wso2/extension/siddhi/device/client/services/DCRService.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/AndroidOperationException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -16,27 +16,22 @@ * under the License. */ -package org.wso2.extension.siddhi.device.client.services; +package org.wso2.carbon.mdm.services.android.exception; -import org.wso2.extension.siddhi.device.client.dto.OAuthApplication; -import org.wso2.extension.siddhi.device.client.dto.RegistrationProfile; +import org.wso2.carbon.mdm.services.android.util.Message; -import javax.ws.rs.Consumes; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; /** - * DCR Rest resource. + * Custom exception class for wrapping Android Operation related exceptions. */ -@Path("/") -public interface DCRService { - - // DCR APIs - @POST - @Produces(MediaType.APPLICATION_JSON) - @Consumes(MediaType.APPLICATION_JSON) - OAuthApplication register(RegistrationProfile registrationProfile); +public class AndroidOperationException extends WebApplicationException { + public AndroidOperationException(Message message, MediaType mediaType) { + super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(message). + type(mediaType).build()); + } } + diff --git a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/exception/OAuthTokenValidationException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/BadRequestException.java similarity index 53% rename from components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/exception/OAuthTokenValidationException.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/BadRequestException.java index 069aa1187..5fa5ededc 100644 --- a/components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/src/main/java/org/wso2/carbon/device/mgt/extensions/remote.session/authentication/oauth/exception/OAuthTokenValidationException.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/BadRequestException.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -15,15 +15,20 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.extensions.remote.session.authentication.oauth.exception; + +package org.wso2.carbon.mdm.services.android.exception; + +import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; /** - * This Exception will be thrown, when there any interference with token validation flow. + * Custom exception class for wrapping BadRequest related exceptions. */ -public class OAuthTokenValidationException extends Exception { +public class BadRequestException extends WebApplicationException { - public OAuthTokenValidationException(String msg, Exception nestedEx) { - super(msg, nestedEx); + public BadRequestException(ErrorResponse error) { + super(Response.status(Response.Status.BAD_REQUEST).entity(error).build()); } - -} +} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/ErrorDTO.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ErrorDTO.java similarity index 97% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/ErrorDTO.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ErrorDTO.java index 44e3385ca..ebd5ec8fc 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/ErrorDTO.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ErrorDTO.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.dto; +package org.wso2.carbon.mdm.services.android.exception; import java.util.ArrayList; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ForbiddenException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ForbiddenException.java new file mode 100644 index 000000000..75113f850 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ForbiddenException.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.mdm.services.android.exception; + +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +/** + * Exception class that is corresponding to 401 Forbidden response + */ + +public class ForbiddenException extends WebApplicationException { + + private String message; + + public ForbiddenException() { + super(Response.status(Response.Status.FORBIDDEN) + .build()); + } + + public ForbiddenException(ErrorDTO errorDTO) { + super(Response.status(Response.Status.FORBIDDEN) + .entity(errorDTO) + .header(AndroidConstants.HEADER_CONTENT_TYPE, AndroidConstants.APPLICATION_JSON) + .build()); + message = errorDTO.getDescription(); + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/GlobalThrowableMapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/GlobalThrowableMapper.java new file mode 100644 index 000000000..31370bd88 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/GlobalThrowableMapper.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.mdm.services.android.exception; + +import com.google.gson.JsonParseException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; + +import javax.naming.AuthenticationException; +import javax.validation.ConstraintViolationException; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +/** + * Handle the cxf level exceptions. + */ +public class GlobalThrowableMapper implements ExceptionMapper { + private static final Log log = LogFactory.getLog(GlobalThrowableMapper.class); + + private ErrorDTO e500 = new ErrorDTO(); + + GlobalThrowableMapper() { + e500.setCode((long) 500); + e500.setMessage("Internal server error."); + e500.setMoreInfo(""); + e500.setDescription("The server encountered an internal error. Please contact administrator."); + + } + + @Override + public Response toResponse(Throwable e) { + + if (e instanceof JsonParseException) { + String errorMessage = "Malformed request body."; + if (log.isDebugEnabled()) { + log.debug(errorMessage, e); + } + return AndroidDeviceUtils.buildBadRequestException(errorMessage).getResponse(); + } + if (e instanceof NotFoundException) { + return ((NotFoundException) e).getResponse(); + } + if (e instanceof BadRequestException) { + return ((BadRequestException) e).getResponse(); + } + if (e instanceof UnexpectedServerErrorException) { + if (log.isDebugEnabled()) { + log.debug("Unexpected server error", e); + } + return ((UnexpectedServerErrorException) e).getResponse(); + } + if (e instanceof ConstraintViolationException) { + if (log.isDebugEnabled()) { + log.debug("Constraint violation issue.", e); + return ((ParameterValidationException) e).getResponse(); + } + } + if (e instanceof IllegalArgumentException) { + ErrorDTO errorDetail = new ErrorDTO(); + errorDetail.setCode((long) 400); + errorDetail.setMoreInfo(""); + errorDetail.setMessage(""); + errorDetail.setDescription(e.getMessage()); + return Response + .status(Response.Status.BAD_REQUEST) + .entity(errorDetail) + .build(); + } + if (e instanceof ClientErrorException) { + if (log.isDebugEnabled()) { + log.debug("Client error", e); + } + return ((ClientErrorException) e).getResponse(); + } + if (e instanceof AuthenticationException) { + ErrorDTO errorDetail = new ErrorDTO(); + errorDetail.setCode((long) 401); + errorDetail.setMoreInfo(""); + errorDetail.setMessage(""); + errorDetail.setDescription(e.getMessage()); + return Response + .status(Response.Status.UNAUTHORIZED) + .entity(errorDetail) + .build(); + } + if (e instanceof ForbiddenException) { + if (log.isDebugEnabled()) { + log.debug("Resource forbidden", e); + } + return ((ForbiddenException) e).getResponse(); + } + //unknown exception log and return + log.error("An Unknown exception has been captured by global exception mapper.", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).header("Content-Type", "application/json") + .entity(e500).build(); + } +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/NotFoundException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/NotFoundException.java new file mode 100644 index 000000000..53863c3ac --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/NotFoundException.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.mdm.services.android.exception; + +import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +public class NotFoundException extends WebApplicationException { + private String message; + private static final long serialVersionUID = 147943572342342340L; + + public NotFoundException(ErrorResponse error) { + super(Response.status(Response.Status.NOT_FOUND).entity(error).build()); + } + public NotFoundException(ErrorDTO errorDTO) { + super(Response.status(Response.Status.NOT_FOUND) + .entity(errorDTO) + .header(AndroidConstants.HEADER_CONTENT_TYPE, AndroidConstants.APPLICATION_JSON) + .build()); + message = errorDTO.getDescription(); + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/OperationConfigurationException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/OperationConfigurationException.java similarity index 94% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/OperationConfigurationException.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/OperationConfigurationException.java index 93f677aa4..1300b1481 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/OperationConfigurationException.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/OperationConfigurationException.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.exception; +package org.wso2.carbon.mdm.services.android.exception; /** * diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ParameterValidationException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ParameterValidationException.java new file mode 100644 index 000000000..efb38a3d7 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/ParameterValidationException.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.mdm.services.android.exception; + +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; +import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; + +import javax.validation.ConstraintViolation; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import java.util.Set; + +public class ParameterValidationException extends WebApplicationException { + + private String message; + public ParameterValidationException(Set> violations) { + super(Response.status(Response.Status.BAD_REQUEST) + .entity(AndroidDeviceUtils.getConstraintViolationErrorDTO(violations)) + .header(AndroidConstants.HEADER_CONTENT_TYPE, AndroidConstants.APPLICATION_JSON) + .build()); + + //Set the error message + StringBuilder stringBuilder = new StringBuilder(); + for (ConstraintViolation violation : violations) { + stringBuilder.append(violation.getRootBeanClass().getSimpleName()); + stringBuilder.append("."); + stringBuilder.append(violation.getPropertyPath()); + stringBuilder.append(": "); + stringBuilder.append(violation.getMessage()); + stringBuilder.append(", "); + } + message = stringBuilder.toString(); + } + + @Override + public String getMessage() { + return message; + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/UnexpectedServerErrorException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/UnexpectedServerErrorException.java new file mode 100644 index 000000000..a66c2f506 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/exception/UnexpectedServerErrorException.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.mdm.services.android.exception; + +import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +public class UnexpectedServerErrorException extends WebApplicationException { + private String message; + private static final long serialVersionUID = 147943579458906890L; + + public UnexpectedServerErrorException(ErrorResponse error) { + super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build()); + } + public UnexpectedServerErrorException(ErrorDTO errorDTO) { + super(Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(errorDTO) + .header(AndroidConstants.HEADER_CONTENT_TYPE, AndroidConstants.APPLICATION_JSON) + .build()); + message = errorDTO.getDescription(); + } + + @Override + public String getMessage() { + return message; + } + + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceManagementAdminAPI.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementAdminService.java similarity index 83% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceManagementAdminAPI.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementAdminService.java index 118874bec..c8bd68d9c 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceManagementAdminAPI.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementAdminService.java @@ -1,39 +1,22 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) 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. + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. * */ -package org.wso2.carbon.device.mgt.mobile.android.api; +package org.wso2.carbon.mdm.services.android.services; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Info; @@ -49,26 +32,8 @@ import io.swagger.annotations.ResponseHeader; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationInstallationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationRestrictionBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationUninstallationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationUpdateBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.BlacklistApplicationsBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.CameraBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.DeviceLockBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.DisplayMessageBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EncryptionBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.FileTransferBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.GlobalProxyBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.LockCodeBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.NotificationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.PasswordPolicyBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.UpgradeFirmwareBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.VpnBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WebClipBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WifiBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WipeDataBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.*; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import javax.validation.Valid; import javax.ws.rs.Consumes; @@ -93,11 +58,11 @@ import java.util.List; } ), tags = { - @Tag(name = "android,device_management", description = "Android Device Management Admin Service") + @Tag(name = "android,device_management", description = "") } ) @Path("/admin/devices") -@Api(value = "Android Device Management Administrative Service") +@Api(value = "Android Device Management Administrative Service", description = "Device management related admin APIs.") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Scopes( @@ -174,12 +139,6 @@ import java.util.List; key = "perm:android:reboot", permissions = {"/device-mgt/devices/owning-device/operations/android/reboot"} ), - @Scope( - name = "Change LockTask mode", - description = "Change LoockTask mode of KIOSK devices", - key = "perm:android:change-LockTask", - permissions = {"/device-mgt/devices/owning-device/operations/android/change-LockTask"} - ), @Scope( name = "Mute Device", description = "Mute Android devices", @@ -234,12 +193,6 @@ import java.util.List; key = "perm:android:configure-wifi", permissions = {"/device-mgt/devices/owning-device/operations/android/wifi"} ), - @Scope( - name = "Configure Global Proxy", - description = "Configure Global Proxy on Android Device", - key = "perm:android:configure-global-proxy", - permissions = {"/device-mgt/devices/owning-device/operations/android/global-proxy"} - ), @Scope( name = "Encrypt Storage", description = "Encrypting storage on Android Device", @@ -269,22 +222,10 @@ import java.util.List; description = "Transferring a file to android devices", key = "perm:android:file-transfer", permissions = {"/device-mgt/devices/owning-device/operations/android/file-transfer"} - ), - @Scope( - name = "Send app restrictions", - description = "Send app restrictions to an application in the device", - key = "perm:android:send-app-restrictions", - permissions = {"/device-mgt/devices/owning-device/operations/android/send-app-conf"} - ), - @Scope( - name = "Configure display message", - description = "Configure display message on Android Device", - key = "perm:android:configure-display-message", - permissions = {"/device-mgt/devices/owning-device/operations/android/display-message"} ) } ) -public interface DeviceManagementAdminAPI { +public interface DeviceManagementAdminService { @POST @Path("/file-transfer") @@ -650,7 +591,8 @@ public interface DeviceManagementAdminAPI { "Disable the camera on the device by assigning true as the value or enable the " + "camera on the device to function by defining false as the value and the ID of the Android device. " + "Multiple device IDs can be added by using comma separated values. ", - required = true) CameraBeanWrapper cameraBeanWrapper); + required = true) + CameraBeanWrapper cameraBeanWrapper); @POST @Path("/info") @@ -897,7 +839,8 @@ public interface DeviceManagementAdminAPI { name = "wipeData", value = "Provide the the passcode, which is the passcode that the Android agent prompts the device owner to set at the time of device enrollment, " + "to enable the factory reset operation, and the ID of the Android device. Multiple device IDs can be added by using comma separated values. ", - required = true) WipeDataBeanWrapper wipeDataBeanWrapper); + required = true) + WipeDataBeanWrapper wipeDataBeanWrapper); @POST @Path("/applications") @@ -1083,66 +1026,6 @@ public interface DeviceManagementAdminAPI { required = true) List deviceIDs); - @POST - @Path("/change-LockTask") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Change LockTask mode of KIOSK Devices", - notes = "Enable or disable LockTask mode of KIOSK devices.", - response = Activity.class, - tags = "Android Device Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:change-LockTask") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 201, - message = "Created. \n Successfully scheduled the change LockTask operation.", - response = Activity.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "URL of the activity instance that refers to the scheduled operation."), - @ResponseHeader( - name = "Content-Type", - description = "Content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.")}), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.\n", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported.\n"), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding the new change LockTask operation.") - }) - Response changeLockTask( - @ApiParam( - name = "deviceIDs", - value = "Provide the ID of the Android device. Multiple device IDs can be added using comma separated values. ", - required = true) - List deviceIDs); - @POST @Path("/mute") @ApiOperation( @@ -1264,7 +1147,8 @@ public interface DeviceManagementAdminAPI { value = "Properties required to install an application on Android devices. Provide the the package name, type," + " URL and name of the application, the date and time for the scheduled installation, and the ID of the " + "Android device. Multiple device IDs can be added by using comma separated values.", - required = true) ApplicationInstallationBeanWrapper applicationInstallationBeanWrapper); + required = true) + ApplicationInstallationBeanWrapper applicationInstallationBeanWrapper); @POST @Path("/update-application") @@ -1328,7 +1212,8 @@ public interface DeviceManagementAdminAPI { value = "Properties required to update an application on Android devices. Provide the the package name, type," + "URL and name of the application, the date and time for the scheduled installation, and the ID of the" + "Android device. Multiple device IDs can be added by using comma separated values.", - required = true) ApplicationUpdateBeanWrapper applicationUpdateBeanWrapper); + required = true) + ApplicationUpdateBeanWrapper applicationUpdateBeanWrapper); @POST @Path("/uninstall-application") @@ -1389,7 +1274,8 @@ public interface DeviceManagementAdminAPI { value = "Properties required to uninstall an application. Provide the the package name, type," + "URL and name of the application, the date and time for the scheduled installation, and the ID of the" + "Android device. Multiple device IDs can be added by using comma separated values.", - required = true) ApplicationUninstallationBeanWrapper applicationUninstallationBeanWrapper); + required = true) + ApplicationUninstallationBeanWrapper applicationUninstallationBeanWrapper); @POST @Path("/blacklist-applications") @@ -1517,7 +1403,8 @@ public interface DeviceManagementAdminAPI { "yyyy-MM-dd'T'HH:mm:ss.SSSXXX format, the OTA upgrade server URL in one of the following formats " + "(example: http//abc.com, http://abc.com/ota), " + "and the ID of the Android device. Multiple device IDs can be added by using comma separated values.", - required = true) UpgradeFirmwareBeanWrapper upgradeFirmwareBeanWrapper); + required = true) + UpgradeFirmwareBeanWrapper upgradeFirmwareBeanWrapper); @POST @Path("/configure-vpn") @@ -1577,7 +1464,8 @@ public interface DeviceManagementAdminAPI { @ApiParam( name = "vpnBean", value = "VPN configuration and DeviceIds", - required = true) VpnBeanWrapper vpnBeanWrapper); + required = true) + VpnBeanWrapper vpnBeanWrapper); @POST @Path("/send-notification") @@ -1637,7 +1525,8 @@ public interface DeviceManagementAdminAPI { name = "notification", value = "The properties required to send a notification. Provide the message you wish to send and the ID of the " + "Android device. Multiple device IDs can be added by using comma separated values.", - required = true) NotificationBeanWrapper notificationBeanWrapper); + required = true) + NotificationBeanWrapper notificationBeanWrapper); @POST @Path("/configure-wifi") @@ -1698,7 +1587,8 @@ public interface DeviceManagementAdminAPI { value = "The properties required to configure Wi-Fi. Provide the password to connect to the specified Wi-Fi network," + "the ssid or the name of the Wi-Fi network that you wish to configure and the ID of the Android device." + " Multiple device IDs can be added by using comma separated values.", - required = true) WifiBeanWrapper wifiBeanWrapper); + required = true) + WifiBeanWrapper wifiBeanWrapper); @POST @Path("/encrypt-storage") @@ -1759,7 +1649,8 @@ public interface DeviceManagementAdminAPI { value = "Properties required to encrypt the storage. Encrypt the storage on the device by assigning " + "true as the value or do not encrypt the storage on the device by assigning false as the value and " + "provide the ID of the Android device. Multiple device IDs can be added by using comma separated values.", - required = true) EncryptionBeanWrapper encryptionBeanWrapper); + required = true) + EncryptionBeanWrapper encryptionBeanWrapper); @POST @Path("/change-lock-code") @@ -1820,7 +1711,8 @@ public interface DeviceManagementAdminAPI { value = "The properties to change th lock code. Provide the lock code that will replace the current lock code on Android devices and " + "the ID of the Android device. Multiple device IDs can be added by using comma separated values. " + "If a passcode policy has been set in EMM, the lock code should comply to the passcode policy.\t", - required = true) LockCodeBeanWrapper lockCodeBeanWrapper); + required = true) + LockCodeBeanWrapper lockCodeBeanWrapper); @POST @Path("/set-password-policy") @@ -1879,7 +1771,8 @@ public interface DeviceManagementAdminAPI { @ApiParam( name = "passwordPolicy", value = "The properties required to set a password policy.", - required = true) PasswordPolicyBeanWrapper passwordPolicyBeanWrapper); + required = true) + PasswordPolicyBeanWrapper passwordPolicyBeanWrapper); @POST @Path("/set-webclip") @@ -1938,177 +1831,8 @@ public interface DeviceManagementAdminAPI { @ApiParam( name = "webClip", value = "The properties to set the web clip.", - required = true) WebClipBeanWrapper webClipBeanWrapper); - @POST - @Path("/send-app-conf") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Sending an app restrictions to Android Devices", - notes = "Send application restrictions to Android devices.", - response = Activity.class, - tags = "Android Device Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, - value = "perm:android:send-app-restrictions") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 201, - message = "Created. \n Successfully sent the application configuration.", - response = Activity.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "URL of the activity instance that refers to the scheduled operation."), - @ResponseHeader( - name = "Content-Type", - description = "Content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.")}), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding a new send application config operation.") - }) - Response sendApplicationConfiguration( - @ApiParam( - name = "notification", - value = "The properties required to send application restrictions. Provide the restriction you " + - "wish to send and the ID of the Android device. Multiple device IDs can be added by using" + - " comma separated values.", - required = true) ApplicationRestrictionBeanWrapper applicationRestrictionBeanWrapper); + required = true) + WebClipBeanWrapper webClipBeanWrapper); - @POST - @Path("/configure-global-proxy") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Setting a network independent proxy recommendation on Android Devices", - notes = "Set global proxy on Android devices. All the network traffic will be routed through the proxy " + - "server regardless of the network the device is connected to.", - response = Activity.class, - tags = "Android Device Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, - value = "perm:android:configure-global-proxy") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 201, - message = "Created. \n Successfully scheduled the global proxy operation.", - response = Activity.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "URL of the activity instance that refers to the scheduled operation."), - @ResponseHeader( - name = "Content-Type", - description = "Content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.")}), - @ApiResponse( - code = 303, - message = "See Other. \n The source can be retrieved from the URL specified in the location header.\n", - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "The Source URL of the document.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 415, - message = "Unsupported media type. \n The format of the requested entity was not supported."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding the set global proxy operation.") - }) - Response setRecommendedGlobalProxy( - @ApiParam( - name = "globalProxyInfo", - value = "The properties to set the global proxy settings.", - required = true) GlobalProxyBeanWrapper globalProxyBeanWrapper); - @POST - @Path("/configure-display-message") - @ApiOperation( - consumes = MediaType.APPLICATION_JSON, - httpMethod = "POST", - value = "Sending a messages to Android Devices.", - notes = "Send a message to Android Devices.", - response = Activity.class, - tags = "Android Device Management Administrative Service", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:configure-display-message") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 201, - message = "Created. \n Successfully sent the message.", - response = Activity.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Location", - description = "URL of the activity instance that refers to the scheduled operation."), - @ResponseHeader( - name = "Content-Type", - description = "Content type of the body"), - @ResponseHeader( - name = "ETag", - description = "Entity Tag of the response resource.\n" + - "Used by caches, or in conditional requests."), - @ResponseHeader( - name = "Last-Modified", - description = "Date and time the resource was last modified.\n" + - "Used by caches, or in conditional requests.")}), - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request or validation error."), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n " + - "Server error occurred while adding a new display messages operation.") - }) - Response configureDisplayMessage( - @ApiParam( - name = "display-message", - value = "The properties required to send a messages. Provide the message you wish to send and the ID of the " + - "Android device. Multiple device IDs can be added by using comma separated values.", - required = true) DisplayMessageBeanWrapper displayMessageBeanWrapper); } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceManagementAPI.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementService.java similarity index 83% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceManagementAPI.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementService.java index 73db4dd71..48c95f82e 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceManagementAPI.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceManagementService.java @@ -15,33 +15,17 @@ * specific language governing permissions and limitations * under the License. * - * - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.api; +package org.wso2.carbon.mdm.services.android.services; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidApplication; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidDevice; +import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidApplication; +import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import javax.validation.Valid; import javax.validation.constraints.NotNull; @@ -73,10 +57,11 @@ import java.util.List; } ), tags = { - @Tag(name = "android,device_management", description = "Android Device Management Service") + @Tag(name = "android,device_management", description = "") } ) -@Api(value = "Android Device Management") +@Api(value = "Android Device Management", + description = "This carries all the resources related to the Android device management functionalities.") @Path("/devices") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -96,7 +81,7 @@ import java.util.List; ) } ) -public interface DeviceManagementAPI { +public interface DeviceManagementService { @PUT @Path("/{id}/applications") @@ -151,13 +136,13 @@ public interface DeviceManagementAPI { name = "id", value = "The unique device identifier.") @NotNull - @Size(min = 2 , max = 45) + @Size(min = 2, max = 45) @Pattern(regexp = "^[A-Za-z0-9]*$") @PathParam("id") String id, @ApiParam( name = "applications", value = "The properties to update application details. Multiple applications can be updated using comma separated values.") - List androidApplications); + List androidApplications); @PUT @Path("/{id}/pending-operations") @@ -208,10 +193,6 @@ public interface DeviceManagementAPI { message = "Internal Server Error. \n Server error occurred while fetching the list of pending operations.") }) Response getPendingOperations( - @ApiParam( - name = "disableGoogleApps", - value = "Specifically disable having Google apps installed.") - @QueryParam("disableGoogleApps") boolean disableGoogleApps, @ApiParam( name = "id", value = "The unique device identifier.", @@ -221,12 +202,72 @@ public interface DeviceManagementAPI { name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time.\n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + - "Example: Mon, 05 Jan 2014 15:10:00 +0200.") + "Example: Mon, 05 Jan 2014 15:10:00 +0200.", + required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince, @ApiParam( name = "resultOperations", value = "Properties to update the device operations and their status.") - List resultOperations); + List resultOperations); + + @GET + @Path("/{id}/operations") + @ApiOperation( + httpMethod = "GET", + value = "Getting operations made for specified device", + notes = "Use this REST API to retrieve the operation made for an Android device. If operation state " + + "specified this will return operations only with specified operation status", + tags = "Android Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") + }) + } + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched operations made for the Android device.", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource was last modified.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client already has the latest version of the requested resource."), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported"), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the enrollment status of the Android device.") + }) + Response getOperations( + @ApiParam( + name = "id", + value = "The unique device identifier") + @PathParam("id") String id, + @ApiParam( + name = "status", + value = "The operation status such as IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED") + @QueryParam("status") String status, + @ApiParam( + name = "If-Modified-Since", + value = "Checks if the requested variant was modified, since the specified date-time.\n" + + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + + "Example: Mon, 05 Jan 2014 15:10:00 +0200", + required = false) + @HeaderParam("If-Modified-Since") String ifModifiedSince); + @POST @ApiOperation( @@ -336,7 +377,8 @@ public interface DeviceManagementAPI { name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time.\n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + - "Example: Mon, 05 Jan 2014 15:10:00 +0200") + "Example: Mon, 05 Jan 2014 15:10:00 +0200", + required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); @PUT diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceTypeConfigurationAPI.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceTypeConfigurationService.java similarity index 84% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceTypeConfigurationAPI.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceTypeConfigurationService.java index 537444a90..5e2440941 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/DeviceTypeConfigurationAPI.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/DeviceTypeConfigurationService.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.mobile.android.api; +package org.wso2.carbon.mdm.services.android.services; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Info; @@ -32,8 +32,9 @@ import io.swagger.annotations.ResponseHeader; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.AndroidPlatformConfiguration; +import org.wso2.carbon.mdm.services.android.bean.AndroidPlatformConfiguration; +import org.wso2.carbon.mdm.services.android.exception.AndroidAgentException; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import javax.validation.Valid; import javax.ws.rs.*; @@ -54,10 +55,10 @@ import javax.ws.rs.core.Response; } ), tags = { - @Tag(name = "android,device_management", description = "Device Type Configuration Service") + @Tag(name = "android,device_management", description = "") } ) -@Api(value = "Android Configuration Management") +@Api(value = "Android Configuration Management", description = "This API carries all the resource used to mange the Android platform configurations.") @Path("/configuration") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -83,7 +84,7 @@ import javax.ws.rs.core.Response; ) } ) -public interface DeviceTypeConfigurationAPI { +public interface DeviceTypeConfigurationService { @GET @ApiOperation( @@ -135,7 +136,8 @@ public interface DeviceTypeConfigurationAPI { name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time.\n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + - "Example: Mon, 05 Jan 2014 15:10:00 +0200") + "Example: Mon, 05 Jan 2014 15:10:00 +0200", + required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); @PUT @@ -243,47 +245,8 @@ public interface DeviceTypeConfigurationAPI { name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time.\n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + - "Example: Mon, 05 Jan 2014 15:10:00 +0200.") - @HeaderParam("If-Modified-Since") String ifModifiedSince); + "Example: Mon, 05 Jan 2014 15:10:00 +0200.", + required = false) + @HeaderParam("If-Modified-Since") String ifModifiedSince) throws AndroidAgentException; - @GET - @Path("/enrollment-qr-config/{ownershipType}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Getting the Enrollment QR config for device type Android", - notes = "Use this REST API to retrieve the Enrollment QR Config that is used for the Android device " + - "enrollment.", - tags = "Android Configuration Management", - extensions = { - @Extension(properties = { - @ExtensionProperty(name = AndroidConstants.SCOPE, value = "perm:android:enroll") - }) - } - ) - @ApiResponses(value = { - @ApiResponse( - code = 400, - message = "Bad Request. \n Invalid request."), - @ApiResponse( - code = 200, - message = "OK. \n Successfully fetched Android Enrollment QR configuration.", - response = String.class, - responseHeaders = { - @ResponseHeader( - name = "Content-Type", - description = "Content type of the body") - }), - @ApiResponse( - code = 500, - message = "Internal Server Error. \n Server error occurred while fetching the Android Enrollment QR" - + " configuration.") - }) - Response getQRConfig( - @ApiParam( - name = "ownershipType", - value = "The ownership type that device has enrolled.", - required = true) - @PathParam("ownershipType") String ownershipType); } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/EventReceiverAPI.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/EventReceiverService.java similarity index 92% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/EventReceiverAPI.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/EventReceiverService.java index 09f61943c..7888f11a8 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/EventReceiverAPI.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/EventReceiverService.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.mobile.android.api; +package org.wso2.carbon.mdm.services.android.services; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Info; @@ -31,9 +31,9 @@ import io.swagger.annotations.ApiResponses; import io.swagger.annotations.ResponseHeader; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scopes; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceState; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EventBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.DeviceState; +import org.wso2.carbon.mdm.services.android.bean.wrapper.EventBeanWrapper; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; import javax.validation.Valid; import javax.validation.constraints.Size; @@ -53,10 +53,12 @@ import javax.ws.rs.core.Response; } ), tags = { - @Tag(name = "android,device_management", description = "Android Even Receiver Service") + @Tag(name = "android,device_management", description = "") } ) -@Api(value = "Event Receiver") +@Api(value = "Event Receiver", description = "Event publishing/retrieving related APIs. To enable event publishing/retrieving you need to" + + " configure WSO2 EMM as explained in https://docs.wso2.com/display/EMM220/Managing+Event+Publishing+with+WSO2+Data+Analytics+Server, " + + "https://docs.wso2.com/display/EMM220/Creating+a+New+Event+Stream+and+Receiver") @Path("/events") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -70,7 +72,7 @@ import javax.ws.rs.core.Response; ) } ) -public interface EventReceiverAPI { +public interface EventReceiverService { @POST @Path("/publish") @@ -129,7 +131,8 @@ public interface EventReceiverAPI { @ApiParam( name = "eventBeanWrapper", value = "Information of the agent event to be published on DAS.") - @Valid EventBeanWrapper eventBeanWrapper); + @Valid + EventBeanWrapper eventBeanWrapper); @GET @ApiOperation( @@ -204,7 +207,8 @@ public interface EventReceiverAPI { name = "If-Modified-Since", value = "Checks if the requested variant was modified, since the specified date-time.\n" + "Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z.\n" + - "Example: Mon, 05 Jan 2014 15:10:00 +0200") + "Example: Mon, 05 Jan 2014 15:10:00 +0200", + required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementAdminServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementAdminServiceImpl.java new file mode 100644 index 000000000..3aed2ce48 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementAdminServiceImpl.java @@ -0,0 +1,1017 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.mdm.services.android.services.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONException; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; +import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; +import org.wso2.carbon.mdm.services.android.bean.ApplicationInstallation; +import org.wso2.carbon.mdm.services.android.bean.ApplicationUninstallation; +import org.wso2.carbon.mdm.services.android.bean.ApplicationUpdate; +import org.wso2.carbon.mdm.services.android.bean.BlacklistApplications; +import org.wso2.carbon.mdm.services.android.bean.Camera; +import org.wso2.carbon.mdm.services.android.bean.DeviceEncryption; +import org.wso2.carbon.mdm.services.android.bean.DeviceLock; +import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; +import org.wso2.carbon.mdm.services.android.bean.FileTransfer; +import org.wso2.carbon.mdm.services.android.bean.LockCode; +import org.wso2.carbon.mdm.services.android.bean.Notification; +import org.wso2.carbon.mdm.services.android.bean.PasscodePolicy; +import org.wso2.carbon.mdm.services.android.bean.UpgradeFirmware; +import org.wso2.carbon.mdm.services.android.bean.Vpn; +import org.wso2.carbon.mdm.services.android.bean.WebClip; +import org.wso2.carbon.mdm.services.android.bean.Wifi; +import org.wso2.carbon.mdm.services.android.bean.WipeData; +import org.wso2.carbon.mdm.services.android.bean.wrapper.ApplicationInstallationBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.ApplicationUninstallationBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.ApplicationUpdateBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.BlacklistApplicationsBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.CameraBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.DeviceLockBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.EncryptionBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.FileTransferBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.LockCodeBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.NotificationBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.PasswordPolicyBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.UpgradeFirmwareBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.VpnBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.WebClipBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.WifiBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.WipeDataBeanWrapper; +import org.wso2.carbon.mdm.services.android.exception.BadRequestException; +import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException; +import org.wso2.carbon.mdm.services.android.services.DeviceManagementAdminService; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; +import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; + +import javax.validation.Valid; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.List; + +@Path("/admin/devices") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminService { + + private static final Log log = LogFactory.getLog(DeviceManagementAdminServiceImpl.class); + private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ"; + + @POST + @Path("/file-transfer") + @Override + public Response fileTransfer(FileTransferBeanWrapper fileTransferBeanWrapper) { + try { + if (fileTransferBeanWrapper == null || fileTransferBeanWrapper.getOperation() == null + || fileTransferBeanWrapper.getDeviceIDs() == null) { + String errorMessage = "The payload of the file transfer operation is incorrect."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + if (log.isDebugEnabled()) { + log.debug("Invoking Android file transfer operation for " + fileTransferBeanWrapper.getDeviceIDs()); + } + FileTransfer file = fileTransferBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + if (fileTransferBeanWrapper.isUpload()) { + operation.setCode(AndroidConstants.OperationCodes.FILE_DOWNLOAD); + } else { + operation.setCode(AndroidConstants.OperationCodes.FILE_UPLOAD); + } + operation.setType(Operation.Type.PROFILE); + operation.setEnabled(true); + operation.setPayLoad(file.toJSON()); + Activity activity = AndroidDeviceUtils.getOperationResponse(fileTransferBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers ( " + fileTransferBeanWrapper.getDeviceIDs() + " ) found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance for file transfer operation"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/lock-devices") + @Override + public Response configureDeviceLock(DeviceLockBeanWrapper deviceLockBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android device lock operation"); + } + + try { + if (deviceLockBeanWrapper == null || deviceLockBeanWrapper.getOperation() == null) { + String errorMessage = "Lock bean is empty."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + DeviceLock lock = deviceLockBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.DEVICE_LOCK); + operation.setType(Operation.Type.PROFILE); + operation.setEnabled(true); + operation.setPayLoad(lock.toJSON()); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceLockBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/unlock-devices") + @Override + public Response configureDeviceUnlock(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android device unlock operation."); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.DEVICE_UNLOCK); + operation.setType(Operation.Type.COMMAND); + operation.setEnabled(true); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/location") + @Override + public Response getDeviceLocation(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android device location operation."); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.DEVICE_LOCATION); + operation.setType(Operation.Type.COMMAND); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/clear-password") + @Override + public Response removePassword(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android clear password operation."); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.CLEAR_PASSWORD); + operation.setType(Operation.Type.COMMAND); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance."; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/control-camera") + @Override + public Response configureCamera(CameraBeanWrapper cameraBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android Camera operation"); + } + + try { + if (cameraBeanWrapper == null || cameraBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the configure camera operation is incorrect."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + Camera camera = cameraBeanWrapper.getOperation(); + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.CAMERA); + operation.setType(Operation.Type.COMMAND); + operation.setEnabled(camera.isEnabled()); + Activity activity = AndroidDeviceUtils.getOperationResponse(cameraBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/info") + @Override + public Response getDeviceInformation(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking get Android device information operation"); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.DEVICE_INFO); + operation.setType(Operation.Type.COMMAND); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } + } + + @POST + @Path("/logcat") + @Override + public Response getDeviceLogcat(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking get Android device logcat operation"); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.LOGCAT); + operation.setType(Operation.Type.COMMAND); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build(); + } + } + + @POST + @Path("/enterprise-wipe") + @Override + public Response wipeDevice(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking enterprise-wipe device operation"); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.ENTERPRISE_WIPE); + operation.setType(Operation.Type.COMMAND); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/wipe") + @Override + public Response wipeData(WipeDataBeanWrapper wipeDataBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android wipe-data device operation"); + } + + try { + if (wipeDataBeanWrapper == null || wipeDataBeanWrapper.getOperation() == null) { + String errorMessage = "WipeData bean is empty."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + WipeData wipeData = wipeDataBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.WIPE_DATA); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(wipeData.toJSON()); + Activity activity = AndroidDeviceUtils.getOperationResponse(wipeDataBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/applications") + @Override + public Response getApplications(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android getApplicationList device operation"); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.APPLICATION_LIST); + operation.setType(Operation.Type.COMMAND); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/ring") + @Override + public Response ringDevice(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android ring-device device operation"); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.DEVICE_RING); + operation.setType(Operation.Type.COMMAND); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/reboot") + @Override + public Response rebootDevice(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android reboot-device device operation"); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.DEVICE_REBOOT); + operation.setType(Operation.Type.COMMAND); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/mute") + @Override + public Response muteDevice(List deviceIDs) { + if (log.isDebugEnabled()) { + log.debug("Invoking mute device operation"); + } + + try { + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.DEVICE_MUTE); + operation.setType(Operation.Type.COMMAND); + operation.setEnabled(true); + Activity activity = AndroidDeviceUtils.getOperationResponse(deviceIDs, operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/install-application") + @Override + public Response installApplication(ApplicationInstallationBeanWrapper applicationInstallationBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'InstallApplication' operation"); + } + + try { + if (applicationInstallationBeanWrapper == null || applicationInstallationBeanWrapper.getOperation() == + null) { + String errorMessage = "The payload of the application installing operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + + ApplicationInstallation applicationInstallation = applicationInstallationBeanWrapper.getOperation(); + validateApplicationUrl(applicationInstallation.getUrl()); + validateApplicationType(applicationInstallation.getType()); + validateScheduleDate(applicationInstallation.getSchedule()); + + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.INSTALL_APPLICATION); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(applicationInstallation.toJSON()); + Activity activity = AndroidDeviceUtils + .getOperationResponse(applicationInstallationBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (JSONException e) { + String errorMessage = "Invalid payload for the operation."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/update-application") + @Override + public Response updateApplication(ApplicationUpdateBeanWrapper applicationUpdateBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'UpdateApplication' operation"); + } + + try { + if (applicationUpdateBeanWrapper == null || applicationUpdateBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the application update operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + ApplicationUpdate applicationUpdate = applicationUpdateBeanWrapper.getOperation(); + validateApplicationUrl(applicationUpdate.getUrl()); + validateApplicationType(applicationUpdate.getType()); + validateScheduleDate(applicationUpdate.getSchedule()); + + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.UPDATE_APPLICATION); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(applicationUpdate.toJSON()); + + Activity activity = AndroidDeviceUtils + .getOperationResponse(applicationUpdateBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/uninstall-application") + @Override + public Response uninstallApplication(ApplicationUninstallationBeanWrapper applicationUninstallationBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'UninstallApplication' operation"); + } + + try { + if (applicationUninstallationBeanWrapper == null || + applicationUninstallationBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the application uninstalling operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + ApplicationUninstallation applicationUninstallation = applicationUninstallationBeanWrapper.getOperation(); + validateApplicationType(applicationUninstallation.getType()); + + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.UNINSTALL_APPLICATION); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(applicationUninstallation.toJSON()); + Activity activity = AndroidDeviceUtils + .getOperationResponse(applicationUninstallationBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/blacklist-applications") + @Override + public Response blacklistApplications(@Valid BlacklistApplicationsBeanWrapper blacklistApplicationsBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'Blacklist-Applications' operation"); + } + + try { + if (blacklistApplicationsBeanWrapper == null || blacklistApplicationsBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the blacklisting apps operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + BlacklistApplications blacklistApplications = blacklistApplicationsBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.BLACKLIST_APPLICATIONS); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(blacklistApplications.toJSON()); + Activity activity = AndroidDeviceUtils + .getOperationResponse(blacklistApplicationsBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/upgrade-firmware") + @Override + public Response upgradeFirmware(UpgradeFirmwareBeanWrapper upgradeFirmwareBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android upgrade-firmware device operation"); + } + + try { + if (upgradeFirmwareBeanWrapper == null || upgradeFirmwareBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the upgrade firmware operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + UpgradeFirmware upgradeFirmware = upgradeFirmwareBeanWrapper.getOperation(); + validateScheduleDate(upgradeFirmware.getSchedule()); + + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.UPGRADE_FIRMWARE); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(upgradeFirmware.toJSON()); + Activity activity = AndroidDeviceUtils + .getOperationResponse(upgradeFirmwareBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/configure-vpn") + @Override + public Response configureVPN(VpnBeanWrapper vpnConfiguration) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android VPN device operation"); + } + + try { + if (vpnConfiguration == null || vpnConfiguration.getOperation() == null) { + String errorMessage = "The payload of the VPN operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + Vpn vpn = vpnConfiguration.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.VPN); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(vpn.toJSON()); + Activity activity = AndroidDeviceUtils.getOperationResponse(vpnConfiguration.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/send-notification") + @Override + public Response sendNotification(NotificationBeanWrapper notificationBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'notification' operation"); + } + + try { + if (notificationBeanWrapper == null || notificationBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the notification operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + Notification notification = notificationBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.NOTIFICATION); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(notification.toJSON()); + Activity activity = AndroidDeviceUtils.getOperationResponse(notificationBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/configure-wifi") + @Override + public Response configureWifi(WifiBeanWrapper wifiBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'configure wifi' operation"); + } + + try { + if (wifiBeanWrapper == null || wifiBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the wifi operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + Wifi wifi = wifiBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.WIFI); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(wifi.toJSON()); + + Activity activity = AndroidDeviceUtils.getOperationResponse(wifiBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/encrypt-storage") + @Override + public Response encryptStorage(EncryptionBeanWrapper encryptionBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'encrypt' operation"); + } + + try { + if (encryptionBeanWrapper == null || encryptionBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the device encryption operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + DeviceEncryption deviceEncryption = encryptionBeanWrapper.getOperation(); + CommandOperation operation = new CommandOperation(); + operation.setCode(AndroidConstants.OperationCodes.ENCRYPT_STORAGE); + operation.setType(Operation.Type.COMMAND); + operation.setEnabled(deviceEncryption.isEncrypted()); + Activity activity = AndroidDeviceUtils.getOperationResponse(encryptionBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/change-lock-code") + @Override + public Response changeLockCode(LockCodeBeanWrapper lockCodeBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'change lock code' operation"); + } + + try { + if (lockCodeBeanWrapper == null || lockCodeBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the change lock code operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + LockCode lockCode = lockCodeBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_CODE); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(lockCode.toJSON()); + Activity activity = AndroidDeviceUtils.getOperationResponse(lockCodeBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("/set-password-policy") + @Override + public Response setPasswordPolicy(PasswordPolicyBeanWrapper passwordPolicyBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'password policy' operation"); + } + + try { + if (passwordPolicyBeanWrapper == null || passwordPolicyBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the change password policy operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + PasscodePolicy passcodePolicy = passwordPolicyBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.PASSCODE_POLICY); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(passcodePolicy.toJSON()); + + Activity activity = AndroidDeviceUtils + .getOperationResponse(passwordPolicyBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + @POST + @Path("set-webclip") + @Override + public Response setWebClip(WebClipBeanWrapper webClipBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking 'webclip' operation"); + } + + try { + + if (webClipBeanWrapper == null || webClipBeanWrapper.getOperation() == null) { + String errorMessage = "The payload of the add webclip operation is incorrect"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + WebClip webClip = webClipBeanWrapper.getOperation(); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.WEBCLIP); + operation.setType(Operation.Type.PROFILE); + operation.setPayLoad(webClip.toJSON()); + + Activity activity = AndroidDeviceUtils.getOperationResponse(webClipBeanWrapper.getDeviceIDs(), operation); + return Response.status(Response.Status.CREATED).entity(activity).build(); + } catch (InvalidDeviceException e) { + String errorMessage = "Invalid Device Identifiers found."; + log.error(errorMessage, e); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (OperationManagementException e) { + String errorMessage = "Issue in retrieving operation management service instance"; + log.error(errorMessage, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(errorMessage).build()); + } + } + + private static void validateApplicationUrl(String apkUrl) { + try { + URL url = new URL(apkUrl); + URLConnection conn = url.openConnection(); + if (((HttpURLConnection) conn).getResponseCode() != HttpURLConnection.HTTP_OK) { + String errorMessage = "URL is not pointed to a downloadable file."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + } catch (MalformedURLException e) { + String errorMessage = "Malformed application url."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } catch (IOException e) { + String errorMessage = "Invalid application url."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + } + + private static void validateApplicationType(String type) { + if (type != null) { + if (!"enterprise".equalsIgnoreCase(type) + && !"public".equalsIgnoreCase(type) + && !"webapp".equalsIgnoreCase(type)) { + String errorMessage = "Invalid application type."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + } else { + String errorMessage = "Application type is missing."; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + } + + private static void validateScheduleDate(String dateString) { + try { + if (dateString != null && !dateString.isEmpty()) { + SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + sdf.setLenient(false); + sdf.parse(dateString); + } + } catch (ParseException e) { + String errorMessage = "Issue in validating the schedule date"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java new file mode 100644 index 000000000..108193efd --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceManagementServiceImpl.java @@ -0,0 +1,525 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.mdm.services.android.services.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; +import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; +import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidApplication; +import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice; +import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException; +import org.wso2.carbon.mdm.services.android.services.DeviceManagementService; +import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; +import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; +import org.wso2.carbon.mdm.services.android.util.Message; +import org.wso2.carbon.policy.mgt.common.PolicyManagementException; +import org.wso2.carbon.policy.mgt.core.PolicyManagerService; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +@Path("/devices") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class DeviceManagementServiceImpl implements DeviceManagementService { + + private static final String OPERATION_ERROR_STATUS = "ERROR"; + private static final Log log = LogFactory.getLog(DeviceManagementServiceImpl.class); + + @PUT + @Path("/{id}/applications") + @Override + public Response updateApplicationList(@PathParam("id") + @NotNull + @Size(min = 2, max = 45) + @Pattern(regexp = "^[A-Za-z0-9]*$") + String id, List androidApplications) { + Application application; + List applications = new ArrayList<>(); + for (AndroidApplication androidApplication : androidApplications) { + application = new Application(); + application.setPlatform(androidApplication.getPlatform()); + application.setCategory(androidApplication.getCategory()); + application.setName(androidApplication.getName()); + application.setLocationUrl(androidApplication.getLocationUrl()); + application.setImageUrl(androidApplication.getImageUrl()); + application.setVersion(androidApplication.getVersion()); + application.setType(androidApplication.getType()); + application.setAppProperties(androidApplication.getAppProperties()); + application.setApplicationIdentifier(androidApplication.getApplicationIdentifier()); + application.setMemoryUsage(androidApplication.getMemoryUsage()); + applications.add(application); + } + Message responseMessage = new Message(); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(id); + deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + try { + AndroidAPIUtils.getApplicationManagerService(). + updateApplicationListInstalledInDevice(deviceIdentifier, applications); + responseMessage.setResponseMessage("Device information has modified successfully."); + return Response.status(Response.Status.ACCEPTED).entity(responseMessage).build(); + } catch (ApplicationManagementException e) { + String msg = "Error occurred while modifying the application list."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + @PUT + @Path("/{id}/pending-operations") + @Override + public Response getPendingOperations(@PathParam("id") String id, + @HeaderParam("If-Modified-Since") String ifModifiedSince, + List resultOperations) { + if (id == null || id.isEmpty()) { + String msg = "Device identifier is null or empty, hence returning device not found"; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); + Device device; + try { + device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false); + if (!AndroidDeviceUtils.isValidDeviceIdentifier(device)) { + String msg = "Device not found for identifier '" + id + "'"; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } + if (log.isDebugEnabled()) { + log.debug("Invoking Android pending operations:" + id); + } + if (resultOperations != null && !resultOperations.isEmpty()) { + updateOperations(device, resultOperations); + } + } catch (OperationManagementException e) { + String msg = "Issue in retrieving operation management service instance"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (PolicyComplianceException e) { + String msg = "Issue in updating Monitoring operation"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (DeviceManagementException e) { + String msg = "Issue in retrieving device management service instance"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (ApplicationManagementException e) { + String msg = "Issue in retrieving application management service instance"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (NotificationManagementException e) { + String msg = "Issue in retrieving Notification management service instance"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + + List pendingOperations; + try { + pendingOperations = AndroidDeviceUtils.getPendingOperations(device); + } catch (OperationManagementException e) { + String msg = "Issue in retrieving operation management service instance"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + return Response.status(Response.Status.CREATED).entity(pendingOperations).build(); + } + + @Override + public Response getOperations(String id, String status, String ifModifiedSince) { + if (id == null || id.isEmpty()) { + String msg = "Device identifier is null or empty, hence returning device not found"; + log.error(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); + Device device; + try { + device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false); + if (!AndroidDeviceUtils.isValidDeviceIdentifier(device)) { + String msg = "Device not found for identifier '" + id + "'"; + log.error(msg); + return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); + } + if (log.isDebugEnabled()) { + log.debug("Invoking Android pending operations:" + id); + } + + List operations; + if (status != null && !status.isEmpty()) { + operations = AndroidAPIUtils.getDeviceManagementService() + .getOperationsByDeviceAndStatus(deviceIdentifier, Operation.Status.valueOf(status)); + } else { + operations = AndroidAPIUtils.getDeviceManagementService() + .getOperations(deviceIdentifier); + } + return Response.status(Response.Status.OK).entity(operations).build(); + } catch (OperationManagementException e) { + String msg = "Issue in retrieving operation management service instance"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (DeviceManagementException e) { + String msg = "Issue in retrieving device management service instance"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + private void updateOperations(Device device, List operations) + throws OperationManagementException, PolicyComplianceException, + ApplicationManagementException, NotificationManagementException, DeviceManagementException { + DeviceIdentifier id = new DeviceIdentifier(); + id.setId(device.getDeviceIdentifier()); + id.setType(AndroidConstants.DEVICE_TYPE_ANDROID); + String deviceName = device.getName(); + for (Operation operation : operations) { + AndroidDeviceUtils.updateOperation(device, operation); + if (OPERATION_ERROR_STATUS.equals(operation.getStatus().toString())) { + org.wso2.carbon.device.mgt.common.notification.mgt.Notification notification = new + org.wso2.carbon.device.mgt.common.notification.mgt.Notification(); + notification.setOperationId(operation.getId()); + notification.setStatus(org.wso2.carbon.device.mgt.common.notification.mgt.Notification. + Status.NEW.toString()); + notification.setDescription(operation.getCode() + " operation failed to execute on device " + + deviceName + " (ID: " + device.getDeviceIdentifier() + ")"); + AndroidAPIUtils.getNotificationManagementService().addNotification(id, notification); + } + if (log.isDebugEnabled()) { + log.debug("Updating operation '" + operation.toString() + "'"); + } + } + } + + @POST + @Override + public Response enrollDevice(@Valid AndroidDevice androidDevice) { + if (androidDevice == null) { + String errorMessage = "The payload of the android device enrollment is incorrect."; + log.error(errorMessage); + throw new org.wso2.carbon.mdm.services.android.exception.BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + try { + Device device = new Device(); + device.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + device.setEnrolmentInfo(androidDevice.getEnrolmentInfo()); + device.getEnrolmentInfo().setOwner(AndroidAPIUtils.getAuthenticatedUser()); + device.setDeviceInfo(androidDevice.getDeviceInfo()); + device.setDeviceIdentifier(androidDevice.getDeviceIdentifier()); + device.setDescription(androidDevice.getDescription()); + device.setName(androidDevice.getName()); + device.setFeatures(androidDevice.getFeatures()); + device.setProperties(androidDevice.getProperties()); + + boolean status = AndroidAPIUtils.getDeviceManagementService().enrollDevice(device); + if (status) { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(androidDevice.getDeviceIdentifier(), + device.getType()); + + //Immediately update location information from initial payload + DeviceLocation deviceLocation = extractLocation(deviceIdentifier, androidDevice.getProperties()); + if (deviceLocation != null) { + try { + DeviceInformationManager informationManager = AndroidAPIUtils + .getDeviceInformationManagerService(); + informationManager.addDeviceLocation(device, deviceLocation); + } catch (DeviceDetailsMgtException e) { + String msg = "Error occurred while updating the device location upon android " + + "', which carries the id '" + androidDevice.getDeviceIdentifier() + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + //Adding Tasks to get device information + List deviceIdentifiers = new ArrayList<>(); + deviceIdentifiers.add(deviceIdentifier); + + List taskOperaions = new ArrayList<>(); + taskOperaions.add(AndroidConstants.OperationCodes.APPLICATION_LIST); + taskOperaions.add(AndroidConstants.OperationCodes.DEVICE_INFO); + taskOperaions.add(AndroidConstants.OperationCodes.DEVICE_LOCATION); + + for (String str : taskOperaions) { + CommandOperation operation = new CommandOperation(); + operation.setEnabled(true); + operation.setType(Operation.Type.COMMAND); + operation.setCode(str); + AndroidAPIUtils.getDeviceManagementService(). + addOperation(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, + operation, deviceIdentifiers); + } + PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService(); + policyManagerService.getEffectivePolicy(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType())); + + Message responseMessage = new Message(); + responseMessage.setResponseCode(Response.Status.OK.toString()); + responseMessage.setResponseMessage("Android device, which carries the id '" + + androidDevice.getDeviceIdentifier() + "' has successfully been enrolled"); + return Response.status(Response.Status.OK).entity(responseMessage).build(); + } else { + Message responseMessage = new Message(); + responseMessage.setResponseCode(Response.Status.INTERNAL_SERVER_ERROR.toString()); + responseMessage.setResponseMessage("Failed to enroll '" + + device.getType() + "' device, which carries the id '" + + androidDevice.getDeviceIdentifier() + "'"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(responseMessage).build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while enrolling the android, which carries the id '" + + androidDevice.getDeviceIdentifier() + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (PolicyManagementException e) { + String msg = "Error occurred while enforcing default enrollment policy upon android " + + "', which carries the id '" + + androidDevice.getDeviceIdentifier() + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (OperationManagementException e) { + String msg = "Error occurred while enforcing default enrollment policy upon android " + + "', which carries the id '" + + androidDevice.getDeviceIdentifier() + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (InvalidDeviceException e) { + String msg = "Error occurred while enforcing default enrollment policy upon android " + + "', which carries the id '" + + androidDevice.getDeviceIdentifier() + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + @GET + @Path("/{id}/status") + @Override + public Response isEnrolled(@PathParam("id") String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { + DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); + try { + Device device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); + if (device != null) { + String status = String.valueOf(device.getEnrolmentInfo().getStatus()); + Message responseMessage = new Message(); + responseMessage.setResponseCode(Response.Status.OK.toString()); + responseMessage + .setResponseMessage("Status of android device that carries the id '" + id + "' is " + status); + return Response.status(Response.Status.OK).entity(responseMessage).build(); + } else { + Message responseMessage = new Message(); + responseMessage.setResponseCode(Response.Status.NOT_FOUND.toString()); + responseMessage.setResponseMessage("No Android device is found upon the id '" + id + "'"); + return Response.status(Response.Status.NOT_FOUND).entity(responseMessage).build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while checking enrollment status of the device."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + @PUT + @Path("/{id}") + @Override + public Response modifyEnrollment(@PathParam("id") String id, @Valid AndroidDevice androidDevice) { + Device device; + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(id); + deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); + try { + device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); + } catch (DeviceManagementException e) { + String msg = "Error occurred while getting enrollment details of the Android device that carries the id '" + + id + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + + if (androidDevice == null) { + String errorMessage = "The payload of the android device enrollment is incorrect."; + log.error(errorMessage); + throw new org.wso2.carbon.mdm.services.android.exception.BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + if (device == null) { + String errorMessage = "The device to be modified doesn't exist."; + log.error(errorMessage); + throw new org.wso2.carbon.mdm.services.android.exception.NotFoundException( + new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage(errorMessage).build()); + } + if(androidDevice.getEnrolmentInfo() != null){ + device.setEnrolmentInfo(device.getEnrolmentInfo()); + } + device.getEnrolmentInfo().setOwner(AndroidAPIUtils.getAuthenticatedUser()); + if(androidDevice.getDeviceInfo() != null) { + device.setDeviceInfo(androidDevice.getDeviceInfo()); + } + device.setDeviceIdentifier(androidDevice.getDeviceIdentifier()); + if(androidDevice.getDescription() != null) { + device.setDescription(androidDevice.getDescription()); + } + if(androidDevice.getName() != null) { + device.setName(androidDevice.getName()); + } + if(androidDevice.getFeatures() != null) { + device.setFeatures(androidDevice.getFeatures()); + } + if(androidDevice.getProperties() != null) { + device.setProperties(androidDevice.getProperties()); + } + boolean result; + try { + device.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + result = AndroidAPIUtils.getDeviceManagementService().modifyEnrollment(device); + if (result) { + Message responseMessage = new Message(); + responseMessage.setResponseCode(Response.Status.ACCEPTED.toString()); + responseMessage.setResponseMessage("Enrollment of Android device that " + + "carries the id '" + id + "' has successfully updated"); + return Response.status(Response.Status.ACCEPTED).entity(responseMessage).build(); + } else { + Message responseMessage = new Message(); + responseMessage.setResponseCode(Response.Status.NOT_MODIFIED.toString()); + responseMessage.setResponseMessage("Enrollment of Android device that " + + "carries the id '" + id + "' has not been updated"); + return Response.status(Response.Status.NOT_MODIFIED).entity(responseMessage).build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while modifying enrollment of the Android device that carries the id '" + + id + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + @DELETE + @Path("/{id}") + @Override + public Response disEnrollDevice(@PathParam("id") String id) { + boolean result; + DeviceIdentifier deviceIdentifier = AndroidDeviceUtils.convertToDeviceIdentifierObject(id); + try { + result = AndroidAPIUtils.getDeviceManagementService().disenrollDevice(deviceIdentifier); + if (result) { + Message responseMessage = new Message(); + responseMessage.setResponseCode(Response.Status.OK.toString()); + responseMessage.setResponseMessage("Android device that carries id '" + id + + "' has successfully dis-enrolled"); + return Response.status(Response.Status.OK).entity(responseMessage).build(); + } else { + Message responseMessage = new Message(); + responseMessage.setResponseCode(Response.Status.NOT_FOUND.toString()); + responseMessage.setResponseMessage("Android device that carries id '" + id + + "' has not been dis-enrolled"); + return Response.status(Response.Status.NOT_FOUND).entity(responseMessage).build(); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while dis-enrolling the Android device that carries the id '" + id + "'"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + /** + * Extracts the device location + * + * @param deviceIdentifier + * @param properties + * @return returns null when location not found + */ + private DeviceLocation extractLocation(DeviceIdentifier deviceIdentifier, List properties) + throws DeviceManagementException { + + DeviceLocation location = null; + String latitude = "", longitude = ""; + + if (properties == null) return null; + + for (Device.Property property : properties) { + String propertyName = property.getName(); + if (propertyName == null) continue; + if (propertyName.equals("LATITUDE")) { + latitude = property.getValue(); + if (!longitude.isEmpty()) break; + } else if (propertyName.equals("LONGITUDE")) { + longitude = property.getValue(); + if (!latitude.isEmpty()) break; + } + } + + if (!latitude.isEmpty() && !longitude.isEmpty()) { + location = new DeviceLocation(); + location.setLatitude(Double.valueOf(latitude)); + location.setLongitude(Double.valueOf(longitude)); + location.setDeviceIdentifier(deviceIdentifier); + Device savedDevice = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier, false); + location.setDeviceId(savedDevice.getId()); + } + return location; + } +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceTypeConfigurationServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceTypeConfigurationServiceImpl.java new file mode 100644 index 000000000..7c813b2fc --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/DeviceTypeConfigurationServiceImpl.java @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.mdm.services.android.services.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.license.mgt.License; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; +import org.wso2.carbon.mdm.services.android.bean.AndroidPlatformConfiguration; +import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; +import org.wso2.carbon.mdm.services.android.bean.NotifierFrequency; +import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException; +import org.wso2.carbon.mdm.services.android.services.DeviceTypeConfigurationService; +import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; + +import javax.validation.Valid; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +@Path("/configuration") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class DeviceTypeConfigurationServiceImpl implements DeviceTypeConfigurationService { + + private static final Log log = LogFactory.getLog(DeviceTypeConfigurationServiceImpl.class); + + @GET + @Override + public Response getConfiguration( + @HeaderParam("If-Modified-Since") String ifModifiedSince) { + String msg; + PlatformConfiguration platformConfiguration; + List configs; + try { + platformConfiguration = AndroidAPIUtils.getDeviceManagementService(). + getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + if (platformConfiguration != null) { + configs = platformConfiguration.getConfiguration(); + } else { + platformConfiguration = new PlatformConfiguration(); + configs = new ArrayList<>(); + } + ConfigurationEntry entry = new ConfigurationEntry(); + License license = AndroidAPIUtils.getDeviceManagementService().getLicense( + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, AndroidConstants. + TenantConfigProperties.LANGUAGE_US); + + if (license != null && configs != null) { + entry.setContentType(AndroidConstants.TenantConfigProperties.CONTENT_TYPE_TEXT); + entry.setName(AndroidConstants.TenantConfigProperties.LICENSE_KEY); + entry.setValue(license.getText()); + configs.add(entry); + platformConfiguration.setConfiguration(configs); + } + } catch (DeviceManagementException e) { + msg = "Error occurred while retrieving the Android tenant configuration"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + return Response.status(Response.Status.OK).entity(platformConfiguration).build(); + } + + @PUT + @Override + public Response updateConfiguration(@Valid AndroidPlatformConfiguration androidPlatformConfiguration) { + String msg; + ConfigurationEntry licenseEntry = null; + PlatformConfiguration configuration = new PlatformConfiguration(); + if (androidPlatformConfiguration == null) { + String errorMessage = "The payload of the android platform configuration is incorrect."; + log.error(errorMessage); + throw new org.wso2.carbon.mdm.services.android.exception.BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + configuration.setConfiguration(androidPlatformConfiguration.getConfiguration()); + try { + configuration.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + List configs = configuration.getConfiguration(); + for (ConfigurationEntry entry : configs) { + if (AndroidConstants.TenantConfigProperties.LICENSE_KEY.equals(entry.getName())) { + License license = new License(); + license.setName(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + license.setLanguage(AndroidConstants.TenantConfigProperties.LANGUAGE_US); + license.setVersion("1.0.0"); + license.setText(entry.getValue().toString()); + AndroidAPIUtils.getDeviceManagementService().addLicense(DeviceManagementConstants. + MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, license); + licenseEntry = entry; + } else if (AndroidConstants.TenantConfigProperties.NOTIFIER_FREQUENCY.equals(entry.getName())) { + List deviceList = AndroidAPIUtils. + getDeviceManagementService(). + getAllDevices(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, false); + List deviceIdList = new ArrayList<>(); + for (Device device : deviceList) { + if (EnrolmentInfo.Status.REMOVED != device.getEnrolmentInfo().getStatus()) { + deviceIdList.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + } + } + if (!deviceIdList.isEmpty()) { + if (entry.getValue() != null) { + NotifierFrequency notifierFrequency = new NotifierFrequency(); + notifierFrequency.setValue(Integer.parseInt(entry.getValue().toString())); + ProfileOperation operation = new ProfileOperation(); + operation.setCode(AndroidConstants.OperationCodes.NOTIFIER_FREQUENCY); + operation.setPayLoad(notifierFrequency.toJSON()); + operation.setEnabled(true); + AndroidAPIUtils.getDeviceManagementService().addOperation( + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, + operation, deviceIdList); + } else { + return Response.status(Response.Status.BAD_REQUEST) + .entity("No value specified for notifierFrequency.").build(); + } + } + } + } + + if (licenseEntry != null) { + configs.remove(licenseEntry); + } + configuration.setConfiguration(configs); + AndroidAPIUtils.getDeviceManagementService().saveConfiguration(configuration); + } catch (DeviceManagementException e) { + msg = "Error occurred while modifying configuration settings of Android platform"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (NumberFormatException e) { + msg = "Error occurred while reading notification frequency."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (OperationManagementException e) { + msg = "Error occurred while modifying configuration settings of Android platform."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } catch (InvalidDeviceException e) { + msg = "Error occurred with the device."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + return Response.status(Response.Status.OK) + .entity("Android platform configuration has been updated successfully.").build(); + } + + + @GET + @Path("/license") + @Produces(MediaType.TEXT_PLAIN) + public Response getLicense( + @HeaderParam("If-Modified-Since") String ifModifiedSince) { + License license; + try { + license = + AndroidAPIUtils.getDeviceManagementService().getLicense( + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, + DeviceManagementConstants.LanguageCodes.LANGUAGE_CODE_ENGLISH_US); + } catch (DeviceManagementException e) { + String msg = "Error occurred while retrieving the license configured for Android device enrolment"; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + return Response.status(Response.Status.OK).entity((license == null) ? null : license.getText()).build(); + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/EventReceiverServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/EventReceiverServiceImpl.java new file mode 100644 index 000000000..ba86a8a22 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/services/impl/EventReceiverServiceImpl.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.mdm.services.android.services.impl; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; +import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; +import org.wso2.carbon.mdm.services.android.bean.DeviceState; +import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; +import org.wso2.carbon.mdm.services.android.bean.wrapper.EventBeanWrapper; +import org.wso2.carbon.mdm.services.android.exception.BadRequestException; +import org.wso2.carbon.mdm.services.android.exception.NotFoundException; +import org.wso2.carbon.mdm.services.android.exception.UnexpectedServerErrorException; +import org.wso2.carbon.mdm.services.android.services.EventReceiverService; +import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; +import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; +import org.wso2.carbon.mdm.services.android.util.Message; + +import javax.validation.Valid; +import javax.validation.constraints.Size; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.util.List; + +@Path("/events") +public class EventReceiverServiceImpl implements EventReceiverService { + private static final String EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream"; + private static final Log log = LogFactory.getLog(EventReceiverServiceImpl.class); + private Gson gson = new Gson(); + + private static final String LONGITUDE = "longitude"; + private static final String LATITUDE = "latitude"; + private static final String TIME_STAMP = "timeStamp"; + private static final String LOCATION_EVENT_TYPE = "location"; + + @POST + @Path("/publish") + @Override + public Response publishEvents(@Valid EventBeanWrapper eventBeanWrapper) { + if (log.isDebugEnabled()) { + log.debug("Invoking Android device event logging."); + } + Device device; + try { + if (!DeviceManagerUtil.isPublishLocationResponseEnabled()) { + return Response.status(Response.Status.ACCEPTED).entity("Event is publishing has not enabled.").build(); + } + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(eventBeanWrapper.getDeviceIdentifier(), + AndroidConstants.DEVICE_TYPE_ANDROID); + device = AndroidAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier); + if (device != null && EnrolmentInfo.Status.ACTIVE != device.getEnrolmentInfo().getStatus()){ + return Response.status(Response.Status.ACCEPTED).entity("Device is not in Active state.").build(); + } else if (device == null){ + return Response.status(Response.Status.ACCEPTED).entity("Device is not enrolled yet.").build(); + } + } catch (DeviceManagementException e) { + log.error("Error occurred while checking Operation Analytics is Enabled.", e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); + } + String eventType = eventBeanWrapper.getType(); + if (!LOCATION_EVENT_TYPE.equals(eventType)) { + String msg = "Dropping Android " + eventType + " Event.Only Location Event Type is supported."; + log.warn(msg); + return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } + Message message = new Message(); + Object[] metaData = {eventBeanWrapper.getDeviceIdentifier(), device.getEnrolmentInfo().getOwner(), + AndroidConstants.DEVICE_TYPE_ANDROID}; + String eventPayload = eventBeanWrapper.getPayload(); + JsonObject jsonObject = gson.fromJson(eventPayload, JsonObject.class); + Object[] payload = { + jsonObject.get(TIME_STAMP).getAsLong(), + jsonObject.get(LATITUDE).getAsDouble(), + jsonObject.get(LONGITUDE).getAsDouble() + }; + try { + if (AndroidAPIUtils.getEventPublisherService().publishEvent( + EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload)) { + message.setResponseCode("Event is published successfully."); + return Response.status(Response.Status.CREATED).entity(message).build(); + } else { + log.warn("Error occurred while trying to publish the event. This could be due to unavailability " + + "of the publishing service. Please make sure that analytics server is running and accessible " + + "by this server"); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(503l).setMessage("Error occurred due to " + + "unavailability of the publishing service.").build()); + } + } catch (DataPublisherConfigurationException e) { + String msg = "Error occurred while getting the Data publisher Service instance."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + @GET + @Override + public Response retrieveAlerts(@QueryParam("id") + @Size(min = 2, max = 45) + String deviceId, + @QueryParam("from") long from, + @QueryParam("to") long to, + @Size(min = 2, max = 45) + @QueryParam("type") String type, + @HeaderParam("If-Modified-Since") String ifModifiedSince) { + + if (from != 0l && to != 0l && deviceId != null) { + return retrieveAlertFromDate(deviceId, from, to); + } else if (deviceId != null && type != null) { + return retrieveAlertByType(deviceId, type); + } else if (deviceId != null) { + return retrieveAlert(deviceId); + } else { + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request must contain " + + "the device identifier. Optionally, both from and to value should be present to get " + + "alerts between times.").build()); + } + } + + private Response retrieveAlert(String deviceId) { + if (log.isDebugEnabled()) { + log.debug("Retrieving events for given device Identifier."); + } + String query = "deviceIdentifier:" + deviceId; + List deviceStates; + try { + deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); + if (deviceStates == null) { + throw new NotFoundException( + new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No any alerts are " + + "published for Device: " + deviceId + ".").build()); + } else { + return Response.status(Response.Status.OK).entity(deviceStates).build(); + } + } catch (AnalyticsException e) { + String msg = "Error occurred while getting published events for specific device: " + deviceId + "."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + private Response retrieveAlertFromDate(String deviceId, long from, long to) { + String fromDate = String.valueOf(from); + String toDate = String.valueOf(to); + if (log.isDebugEnabled()) { + log.debug("Retrieving events for given device Identifier and time period."); + } + + String query = "deviceIdentifier:" + deviceId + " AND _timestamp: [" + fromDate + " TO " + toDate + "]"; + List deviceStates; + try { + deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); + if (deviceStates == null) { + throw new NotFoundException( + new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No any alerts are " + + "published on given date for given Device: " + deviceId + ".").build()); + + } else { + return Response.status(Response.Status.OK).entity(deviceStates).build(); + } + } catch (AnalyticsException e) { + String msg = "Error occurred while getting published events for specific " + + "Device: " + deviceId + " on given Date."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + + private Response retrieveAlertByType(String deviceId, String type) { + if (log.isDebugEnabled()) { + log.debug("Retrieving events for given device identifier and type."); + } + String query = "deviceIdentifier:" + deviceId + " AND type:" + type; + List deviceStates; + try { + deviceStates = AndroidDeviceUtils.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); + if (deviceStates == null) { + throw new NotFoundException( + new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage("No any alerts are " + + "published for given Device: '" + deviceId + "' and given specific Type.").build()); + + } else { + return Response.status(Response.Status.OK).entity(deviceStates).build(); + } + } catch (AnalyticsException e) { + String msg = "Error occurred while getting published events for specific " + + "Device: " + deviceId + "and given specific Type."; + log.error(msg, e); + throw new UnexpectedServerErrorException( + new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); + } + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidAPIUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java similarity index 51% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidAPIUtils.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java index 4cc1b5e63..336801721 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/device/mgt/mobile/android/api/util/AndroidAPIUtils.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidAPIUtils.java @@ -16,17 +16,17 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.api.util; +package org.wso2.carbon.mdm.services.android.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; -import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; -import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService; +import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; +import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; /** @@ -36,69 +36,26 @@ public class AndroidAPIUtils { private static Log log = LogFactory.getLog(AndroidAPIUtils.class); - private static ApplicationManager applicationManager = null; - private static SubscriptionManager subscriptionManager = null; private static DeviceManagementProviderService deviceManagementProviderService = null; - private static AndroidGoogleEnterpriseService androidGoogleEnterpriseService = null; - private static AndroidService androidService = null; + private static DeviceInformationManager informationManager = null; private static PolicyManagerService policyManagerService = null; - private static DeviceTypeCommonService deviceTypeCommonService = null; + private static ApplicationManagementProviderService applicationManagementProviderService = null; + private static NotificationManagementService notificationManagementService = null; + private static EventsPublisherService eventsPublisherService = null; + private static AnalyticsDataAPI analyticsDataAPI = null; private AndroidAPIUtils() { throw new IllegalStateException("Utility class"); } - public static ApplicationManager getAppManagerService() { - if (applicationManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - applicationManager = (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null); - if (applicationManager == null) { - String msg = "Application Management service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } + public static String getAuthenticatedUser() { + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); + String tenantDomain = threadLocalCarbonContext.getTenantDomain(); + if (username != null && username.endsWith(tenantDomain)) { + return username.substring(0, username.lastIndexOf("@")); } - return applicationManager; - } - - public static SubscriptionManager getAppSubscriptionService() { - if (subscriptionManager == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - subscriptionManager = (SubscriptionManager) ctx.getOSGiService(SubscriptionManager.class, null); - if (subscriptionManager == null) { - String msg = "Application Subscription service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - return subscriptionManager; - } - - public static AndroidGoogleEnterpriseService getAndroidPluginService() { - if (androidGoogleEnterpriseService == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - androidGoogleEnterpriseService = - (AndroidGoogleEnterpriseService) ctx.getOSGiService(AndroidGoogleEnterpriseService.class, null); - if (androidGoogleEnterpriseService == null) { - String msg = "Android plugin service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - return androidGoogleEnterpriseService; - } - - public static AndroidService getAndroidService() { - if (androidService == null) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - androidService = (AndroidService) ctx.getOSGiService(AndroidService.class, null); - if (androidService == null) { - String msg = "Android service has not initialized."; - log.error(msg); - throw new IllegalStateException(msg); - } - } - return androidService; + return username; } public static DeviceManagementProviderService getDeviceManagementService() { @@ -115,18 +72,17 @@ public class AndroidAPIUtils { return deviceManagementProviderService; } - public static DeviceTypeCommonService getDeviceTypeCommonService() { - if (deviceTypeCommonService == null) { + public static DeviceInformationManager getDeviceInformationManagerService() { + if (informationManager == null) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - deviceTypeCommonService = (DeviceTypeCommonService) ctx - .getOSGiService(DeviceTypeCommonService.class, null); - if (deviceTypeCommonService == null) { - String msg = "Device Type Common service has not initialized."; + informationManager = (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); + if (informationManager == null) { + String msg = "Information Manager service not initialized."; log.error(msg); throw new IllegalStateException(msg); } } - return deviceTypeCommonService; + return informationManager; } public static PolicyManagerService getPolicyManagerService() { @@ -142,4 +98,58 @@ public class AndroidAPIUtils { return policyManagerService; } + public static ApplicationManagementProviderService getApplicationManagerService() { + if (applicationManagementProviderService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + applicationManagementProviderService = + (ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null); + if (applicationManagementProviderService == null) { + String msg = "Application Management provider service has not initialized"; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return applicationManagementProviderService; + } + + public static NotificationManagementService getNotificationManagementService() { + if (notificationManagementService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + notificationManagementService = (NotificationManagementService) ctx.getOSGiService( + NotificationManagementService.class, null); + if (notificationManagementService == null) { + String msg = "Notification Management service not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return notificationManagementService; + } + + public static EventsPublisherService getEventPublisherService() { + if (eventsPublisherService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + eventsPublisherService = (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null); + if (eventsPublisherService == null) { + String msg = "Event Publisher service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return eventsPublisherService; + } + + public static AnalyticsDataAPI getAnalyticsDataAPI() { + if (analyticsDataAPI == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + analyticsDataAPI = (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); + if (analyticsDataAPI == null) { + String msg = "Analytics api service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return analyticsDataAPI; + } + } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidConstants.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidConstants.java new file mode 100644 index 000000000..d7491c916 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidConstants.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http:www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.mdm.services.android.util; + +/** + * Defines constants used in Android-REST API bundle. + */ +public final class AndroidConstants { + + public static final String DEVICE_TYPE_ANDROID = "android"; + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + public static final String APPLICATION_JSON = "application/json"; + public static final String SCOPE = "scope"; + + public final class DeviceProperties { + private DeviceProperties() { + throw new AssertionError(); + } + + public static final String PROPERTY_USER_KEY = "username"; + public static final String PROPERTY_DEVICE_KEY = "device"; + } + + public final class DeviceFeatures { + private DeviceFeatures() { + throw new AssertionError(); + } + } + + public final class DeviceConstants { + private DeviceConstants() { + throw new AssertionError(); + } + + public static final String DEVICE_MAC_KEY = "mac"; + public static final String DEVICE_DESCRIPTION_KEY = "description"; + public static final String DEVICE_OWNERSHIP_KEY = "ownership"; + public static final String DEVICE_PROPERTIES_KEY = "properties"; + public static final String DEVICE_FEATURES_KEY = "features"; + public static final String DEVICE_DATA = "data"; + public static final String DEVICE_ID_NOT_FOUND = "Device not found for device id: %s"; + public static final String DEVICE_ID_SERVICE_NOT_FOUND = + "Issue in retrieving device management service instance for device found at %s"; + } + + public final class Messages { + private Messages() { + throw new AssertionError(); + } + + public static final String DEVICE_MANAGER_SERVICE_NOT_AVAILABLE = + "Device Manager service not available"; + } + + public final class OperationCodes { + private OperationCodes() { + throw new AssertionError(); + } + + public static final String DEVICE_LOCK = "DEVICE_LOCK"; + public static final String FILE_DOWNLOAD = "FILE_UPLOAD_TO_THE_DEVICE"; + public static final String FILE_UPLOAD = "FILE_DOWNLOAD_FROM_THE_DEVICE"; + public static final String DEVICE_UNLOCK = "DEVICE_UNLOCK"; + public static final String DEVICE_LOCATION = "DEVICE_LOCATION"; + public static final String WIFI = "WIFI"; + public static final String CAMERA = "CAMERA"; + public static final String DEVICE_MUTE = "DEVICE_MUTE"; + public static final String PASSCODE_POLICY = "PASSCODE_POLICY"; + public static final String DEVICE_INFO = "DEVICE_INFO"; + public static final String ENTERPRISE_WIPE = "ENTERPRISE_WIPE"; + public static final String CLEAR_PASSWORD = "CLEAR_PASSWORD"; + public static final String WIPE_DATA = "WIPE_DATA"; + public static final String APPLICATION_LIST = "APPLICATION_LIST"; + public static final String CHANGE_LOCK_CODE = "CHANGE_LOCK_CODE"; + public static final String INSTALL_APPLICATION = "INSTALL_APPLICATION"; + public static final String UPDATE_APPLICATION = "UPDATE_APPLICATION"; + public static final String UNINSTALL_APPLICATION = "UNINSTALL_APPLICATION"; + public static final String BLACKLIST_APPLICATIONS = "BLACKLIST_APPLICATIONS"; + public static final String ENCRYPT_STORAGE = "ENCRYPT_STORAGE"; + public static final String DEVICE_RING = "DEVICE_RING"; + public static final String DEVICE_REBOOT = "REBOOT"; + public static final String UPGRADE_FIRMWARE = "UPGRADE_FIRMWARE"; + public static final String NOTIFICATION = "NOTIFICATION"; + public static final String WEBCLIP = "WEBCLIP"; + public static final String DISENROLL = "DISENROLL"; + public static final String MONITOR = "MONITOR"; + public static final String VPN = "VPN"; + public static final String LOGCAT = "LOGCAT"; + public static final String APP_RESTRICTION = "APP-RESTRICTION"; + public static final String WORK_PROFILE = "WORK_PROFILE"; + public static final String NOTIFIER_FREQUENCY = "NOTIFIER_FREQUENCY"; + } + + public final class StatusCodes { + private StatusCodes() { + throw new AssertionError(); + } + + public static final int MULTI_STATUS_HTTP_CODE = 207; + } + + public final class TenantConfigProperties { + private TenantConfigProperties() { + throw new AssertionError(); + } + + public static final String LICENSE_KEY = "androidEula"; + public static final String LANGUAGE_US = "en_US"; + public static final String CONTENT_TYPE_TEXT = "text"; + public static final String NOTIFIER_FREQUENCY = "notifierFrequency"; + } + + public final class ApplicationProperties { + private ApplicationProperties() { + throw new AssertionError(); + } + + public static final String NAME = "name"; + public static final String IDENTIFIER = "package"; + public static final String USS = "USS"; + public static final String VERSION = "version"; + public static final String ICON = "icon"; + public static final String IS_ACTIVE = "isActive"; + } + + public final class ErrorMessages { + private ErrorMessages () { throw new AssertionError(); } + + public static final String STATUS_BAD_REQUEST_MESSAGE_DEFAULT = "Bad Request"; + + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidDeviceUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidDeviceUtils.java new file mode 100644 index 000000000..60b2dd266 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/AndroidDeviceUtils.java @@ -0,0 +1,492 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.mdm.services.android.util; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.analytics.api.AnalyticsDataAPI; +import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; +import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; +import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; +import org.wso2.carbon.analytics.datasource.commons.Record; +import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; +import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; +import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; +import org.wso2.carbon.mdm.services.android.bean.DeviceState; +import org.wso2.carbon.mdm.services.android.bean.ErrorListItem; +import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; +import org.wso2.carbon.mdm.services.android.exception.BadRequestException; + +import javax.validation.ConstraintViolation; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Util class for holding Android device related util methods. + */ +public class AndroidDeviceUtils { + + private static Log log = LogFactory.getLog(AndroidDeviceUtils.class); + + private AndroidDeviceUtils() { + throw new IllegalStateException("Utility class"); + } + + public static boolean isValidDeviceIdentifier(Device device) { + return !(device == null || device.getDeviceIdentifier() == null || + device.getDeviceIdentifier().isEmpty() || + device.getEnrolmentInfo() == null || + EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())); + } + + public static DeviceIdentifier convertToDeviceIdentifierObject(String deviceId) { + DeviceIdentifier identifier = new DeviceIdentifier(); + identifier.setId(deviceId); + identifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + return identifier; + } + + public static Activity getOperationResponse(List deviceIDs, Operation operation) + throws OperationManagementException, InvalidDeviceException { + if (deviceIDs == null || deviceIDs.isEmpty()) { + String errorMessage = "Device identifier list is empty"; + log.error(errorMessage); + throw new BadRequestException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build()); + } + DeviceIdentifier deviceIdentifier; + List deviceIdentifiers = new ArrayList<>(); + for (String deviceId : deviceIDs) { + deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); + deviceIdentifiers.add(deviceIdentifier); + } + return AndroidAPIUtils.getDeviceManagementService().addOperation( + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers); + } + + public static List getAllEventsForDevice(String tableName, String query) throws AnalyticsException { + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + AnalyticsDataAPI analyticsDataAPI = AndroidAPIUtils.getAnalyticsDataAPI(); + int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); + if (eventCount == 0) { + return null; + } + List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount); + List recordIds = getRecordIds(resultEntries); + AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); + Map deviceStateses = createDeviceStatusData(AnalyticsDataAPIUtil.listRecords( + analyticsDataAPI, response)); + return getSortedDeviceStateData(deviceStateses, resultEntries); + } + + private static List getRecordIds(List searchResults) { + List ids = new ArrayList<>(); + for (SearchResultEntry searchResult : searchResults) { + ids.add(searchResult.getId()); + } + return ids; + } + + public static Map createDeviceStatusData(List records) { + Map deviceStatuses = new HashMap<>(); + for (Record record : records) { + DeviceState deviceState = createDeviceStatusData(record); + deviceStatuses.put(deviceState.getId(), deviceState); + } + return deviceStatuses; + } + + private static DeviceState createDeviceStatusData(Record record) { + DeviceState deviceState = new DeviceState(); + deviceState.setId(record.getId()); + deviceState.setValues(record.getValues()); + return deviceState; + } + + public static List getSortedDeviceStateData(Map sensorDatas, + List searchResults) { + List sortedRecords = new ArrayList<>(); + for (SearchResultEntry searchResultEntry : searchResults) { + sortedRecords.add(sensorDatas.get(searchResultEntry.getId())); + } + return sortedRecords; + } + + public static void updateOperation(Device device, Operation operation) + throws OperationManagementException, PolicyComplianceException, ApplicationManagementException { + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(device.getDeviceIdentifier()); + deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + + if (!Operation.Status.ERROR.equals(operation.getStatus()) && + AndroidConstants.OperationCodes.MONITOR.equals(operation.getCode())) { + if (log.isDebugEnabled()) { + log.debug("Received compliance status from MONITOR operation ID: " + operation.getId()); + } + AndroidAPIUtils.getPolicyManagerService().checkPolicyCompliance(deviceIdentifier, + getComplianceFeatures(operation.getPayLoad())); + } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. + OperationCodes.APPLICATION_LIST.equals(operation.getCode())) { + if (log.isDebugEnabled()) { + log.debug("Received applications list from device '" + device.getDeviceIdentifier() + "'"); + } + updateApplicationList(operation, device); + + } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. + OperationCodes.DEVICE_INFO.equals(operation.getCode())) { + + try { + if (log.isDebugEnabled()) { + log.debug("Operation response: " + operation.getOperationResponse()); + } + Device deviceInfoBean = new Gson().fromJson(operation.getOperationResponse(), Device.class); + DeviceInfo deviceInfo = convertDeviceToInfo(deviceInfoBean); + updateDeviceInfo(device, deviceInfo); + } catch (DeviceDetailsMgtException e) { + throw new OperationManagementException("Error occurred while updating the device information.", e); + } + + } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && + AndroidConstants.OperationCodes.DEVICE_LOCATION.equals(operation.getCode())) { + try { + DeviceLocation location = new Gson().fromJson(operation.getOperationResponse(), DeviceLocation.class); + // reason for checking "location.getLatitude() != null" because when device fails to provide + // device location and send status instead, above Gson converter create new location object + // with null attributes + if (location != null && location.getLatitude() != null) { + location.setDeviceIdentifier(deviceIdentifier); + updateDeviceLocation(device, location); + } + } catch (DeviceDetailsMgtException e) { + throw new OperationManagementException("Error occurred while updating the device location.", e); + } + } + AndroidAPIUtils.getDeviceManagementService().updateOperation(device, operation); + } + + public static List getPendingOperations + (Device device) throws OperationManagementException { + + List operations; + operations = AndroidAPIUtils.getDeviceManagementService().getPendingOperations(device); + return operations; + } + + private static void updateApplicationList(Operation operation, Device device) + throws ApplicationManagementException { + // Parsing json string to get applications list. + if (operation.getOperationResponse() != null) { + if (operation.getOperationResponse().equals("SAME_APPLICATION_LIST")) { + return; + } + JsonElement jsonElement = new JsonParser().parse(operation.getOperationResponse()); + JsonArray jsonArray = jsonElement.getAsJsonArray(); + Application app; + List applications = new ArrayList<>(jsonArray.size()); + for (JsonElement element : jsonArray) { + app = new Application(); + app.setName(element.getAsJsonObject(). + get(AndroidConstants.ApplicationProperties.NAME).getAsString()); + app.setApplicationIdentifier(element.getAsJsonObject(). + get(AndroidConstants.ApplicationProperties.IDENTIFIER).getAsString()); + app.setPlatform(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS) != null) { + app.setMemoryUsage(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS).getAsInt()); + } + if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION) != null) { + app.setVersion(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION).getAsString()); + } + if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE) != null) { + app.setActive(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE).getAsBoolean()); + } + applications.add(app); + } + AndroidAPIUtils.getApplicationManagerService().updateApplicationListInstalledInDevice(device, applications); + } else { + if (log.isDebugEnabled()) { + log.debug("Operation Response is null."); + } + } + + } + + private static void updateDeviceLocation(Device device, DeviceLocation deviceLocation) + throws DeviceDetailsMgtException { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + DeviceInformationManager informationManager = + (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); + + informationManager.addDeviceLocation(device, deviceLocation); + } + + private static void updateDeviceInfo(Device device, DeviceInfo deviceInfo) + throws DeviceDetailsMgtException { + DeviceInformationManager informationManager = AndroidAPIUtils.getDeviceInformationManagerService(); + informationManager.addDeviceInfo(device, deviceInfo); + } + + private static DeviceInfo convertDeviceToInfo(Device device) { + + DeviceInfo deviceInfo = + new DeviceInfo(); + if (deviceInfo.getDeviceDetailsMap() == null) { + deviceInfo.setDeviceDetailsMap(new HashMap<>()); + } + List props = device.getProperties(); + + for (Device.Property prop : props) { + if (Utils.getDeviceDetailsColumnNames().containsValue(prop.getName())) { + extractDefinedProperties(deviceInfo, prop); + } else { + extractMapProperties(deviceInfo, prop); + } + } + return deviceInfo; + } + + private static void extractMapProperties(DeviceInfo deviceInfo, Device.Property prop) { + if (prop.getName().equalsIgnoreCase("CPU_INFO")) { + deviceInfo.getDeviceDetailsMap().put("cpuUser", getProperty(prop.getValue(), "User")); + deviceInfo.getDeviceDetailsMap().put("cpuSystem", getProperty(prop.getValue(), "System")); + deviceInfo.getDeviceDetailsMap().put("IOW", getProperty(prop.getValue(), "IOW")); + deviceInfo.getDeviceDetailsMap().put("IRQ", getProperty(prop.getValue(), "IRQ")); + } else if (prop.getName().equalsIgnoreCase("RAM_INFO")) { + if (!getProperty(prop.getValue(), "TOTAL_MEMORY").isEmpty()) { + deviceInfo.setTotalRAMMemory(Double.parseDouble(getProperty(prop.getValue(), "TOTAL_MEMORY"))); + } else { + deviceInfo.setTotalRAMMemory(-1D); + } + if (!getProperty(prop.getValue(), "AVAILABLE_MEMORY").isEmpty()) { + deviceInfo.setAvailableRAMMemory(Double.parseDouble( + getProperty(prop.getValue(), "AVAILABLE_MEMORY"))); + } else { + deviceInfo.setAvailableRAMMemory(-1D); + } + deviceInfo.getDeviceDetailsMap().put("ramThreshold", getProperty(prop.getValue(), "THRESHOLD")); + deviceInfo.getDeviceDetailsMap().put("ramLowMemory", getProperty(prop.getValue(), "LOW_MEMORY")); + } else if (prop.getName().equalsIgnoreCase("BATTERY_INFO")) { + deviceInfo.setPluggedIn(Boolean.parseBoolean(getProperty(prop.getValue(), "PLUGGED"))); + + deviceInfo.getDeviceDetailsMap().put("batteryLevel", getProperty(prop.getValue(), "BATTERY_LEVEL")); + deviceInfo.getDeviceDetailsMap().put("batteryScale", getProperty(prop.getValue(), "SCALE")); + deviceInfo.getDeviceDetailsMap().put("batteryVoltage", + getProperty(prop.getValue(), "BATTERY_VOLTAGE")); + deviceInfo.getDeviceDetailsMap().put("batteryTemperature", + getProperty(prop.getValue(), "TEMPERATURE")); + deviceInfo.getDeviceDetailsMap().put("batteryCurrentTemperature", + getProperty(prop.getValue(), "CURRENT_AVERAGE")); + deviceInfo.getDeviceDetailsMap().put("batteryTechnology", + getProperty(prop.getValue(), "TECHNOLOGY")); + deviceInfo.getDeviceDetailsMap().put("batteryHealth", getProperty(prop.getValue(), "HEALTH")); + deviceInfo.getDeviceDetailsMap().put("batteryStatus", getProperty(prop.getValue(), "STATUS")); + } else if (prop.getName().equalsIgnoreCase("NETWORK_INFO")) { + deviceInfo.setSsid(getProperty(prop.getValue(), "WIFI_SSID")); + deviceInfo.setConnectionType(getProperty(prop.getValue(), "CONNECTION_TYPE")); + + deviceInfo.getDeviceDetailsMap().put("mobileSignalStrength", + getProperty(prop.getValue(), "MOBILE_SIGNAL_STRENGTH")); + deviceInfo.getDeviceDetailsMap().put("wifiSignalStrength", + getProperty(prop.getValue(), "WIFI_SIGNAL_STRENGTH")); + } else if (prop.getName().equalsIgnoreCase("DEVICE_INFO")) { + if (!getProperty(prop.getValue(), "BATTERY_LEVEL").isEmpty()) { + deviceInfo.setBatteryLevel(Double.parseDouble( + getProperty(prop.getValue(), "BATTERY_LEVEL"))); + } else { + deviceInfo.setBatteryLevel(-1D); + } + if (!getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY").isEmpty()) { + deviceInfo.setInternalTotalMemory(Double.parseDouble( + getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY"))); + } else { + deviceInfo.setInternalTotalMemory(-1D); + } + if (!getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY").isEmpty()) { + deviceInfo.setInternalAvailableMemory(Double.parseDouble( + getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY"))); + } else { + deviceInfo.setInternalAvailableMemory(-1D); + } + if (!getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY").isEmpty()) { + deviceInfo.setExternalTotalMemory(Double.parseDouble( + getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY"))); + } else { + deviceInfo.setExternalTotalMemory(-1D); + } + if (!getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY").isEmpty()) { + deviceInfo.setExternalAvailableMemory(Double.parseDouble( + getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY"))); + } else { + deviceInfo.setExternalAvailableMemory(-1D); + } + + deviceInfo.getDeviceDetailsMap().put("encryptionEnabled", + getProperty(prop.getValue(), "ENCRYPTION_ENABLED")); + deviceInfo.getDeviceDetailsMap().put("passcodeEnabled", + getProperty(prop.getValue(), "PASSCODE_ENABLED")); + deviceInfo.getDeviceDetailsMap().put("operator", + getProperty(prop.getValue(), "OPERATOR")); + deviceInfo.getDeviceDetailsMap().put("PhoneNumber", + getProperty(prop.getValue(), "PHONE_NUMBER")); + } else if (prop.getName().equalsIgnoreCase("IMEI")) { + deviceInfo.getDeviceDetailsMap().put("IMEI", prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("IMSI")) { + deviceInfo.getDeviceDetailsMap().put("IMSI", prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("MAC")) { + deviceInfo.getDeviceDetailsMap().put("mac", prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("SERIAL")) { + deviceInfo.getDeviceDetailsMap().put("serial", prop.getValue()); + } + } + + private static void extractDefinedProperties(DeviceInfo deviceInfo, Device.Property prop) { + if (prop.getName().equalsIgnoreCase("DEVICE_MODEL")) { + deviceInfo.setDeviceModel(prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("VENDOR")) { + deviceInfo.setVendor(prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("OS_VERSION")) { + deviceInfo.setOsVersion(prop.getValue()); + } else if (prop.getName().equalsIgnoreCase("OS_BUILD_DATE")) { + deviceInfo.setOsBuildDate(prop.getValue()); + } + } + + private static String getProperty(String properties, String needed) { + // This is not a key value pair. value is the immediate element to its filed name. + // Ex: + // [{"name":"ENCRYPTION_ENABLED","value":"false"},{"name":"PASSCODE_ENABLED","value":"true"}, + // {"name":"BATTERY_LEVEL","value":"100"},{"name":"INTERNAL_TOTAL_MEMORY","value":"0.76"}] + JsonElement jsonElement = new JsonParser().parse(properties); + JsonArray jsonArray = jsonElement.getAsJsonArray(); + for (JsonElement element : jsonArray) { + if (element.isJsonObject()) { + JsonObject jsonObject = element.getAsJsonObject(); + if (jsonObject.has("name") + && jsonObject.get("name").getAsString().equalsIgnoreCase(needed)) { + if (jsonObject.has("value") && jsonObject.get("value") != JsonNull.INSTANCE) { + return jsonObject.get("value").getAsString().replace("%", ""); + } else { + return ""; + } + } + } + } + return ""; + } + + private static List getComplianceFeatures(Object compliancePayload) + throws PolicyComplianceException { + String compliancePayloadString = new Gson().toJson(compliancePayload); + if (compliancePayload == null) { + return null; + } + // Parsing json string to get compliance features. + JsonElement jsonElement; + if (compliancePayloadString instanceof String) { + jsonElement = new JsonParser().parse(compliancePayloadString); + } else { + throw new PolicyComplianceException("Invalid policy compliance payload"); + } + + JsonArray jsonArray = jsonElement.getAsJsonArray(); + Gson gson = new Gson(); + ComplianceFeature complianceFeature; + List complianceFeatures = new ArrayList(jsonArray.size()); + + for (JsonElement element : jsonArray) { + complianceFeature = gson.fromJson(element, ComplianceFeature.class); + complianceFeatures.add(complianceFeature); + } + return complianceFeatures; + } + + /** + * Returns a new BadRequestException + * + * @param description description of the exception + * @return a new BadRequestException with the specified details as a response DTO + */ + public static BadRequestException buildBadRequestException(String description) { + ErrorResponse errorResponse = getErrorResponse(AndroidConstants. + ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400l, description); + return new BadRequestException(errorResponse); + } + + /** + * Returns generic ErrorResponse. + * + * @param message specific error message + * @param code error code + * @param description error description + * @return generic Response with error specific details. + */ + public static ErrorResponse getErrorResponse(String message, Long code, String description) { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setCode(code); + errorResponse.setMoreInfo(""); + errorResponse.setMessage(message); + errorResponse.setDescription(description); + return errorResponse; + } + + public static ErrorResponse getConstraintViolationErrorDTO(Set> violations) { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setDescription("Validation Error"); + errorResponse.setMessage("Bad Request"); + errorResponse.setCode(400l); + errorResponse.setMoreInfo(""); + List errorListItems = new ArrayList<>(); + for (ConstraintViolation violation : violations) { + ErrorListItem errorListItemDTO = new ErrorListItem(); + errorListItemDTO.setCode(400 + "_" + violation.getPropertyPath()); + errorListItemDTO.setMessage(violation.getPropertyPath() + ": " + violation.getMessage()); + errorListItems.add(errorListItemDTO); + } + errorResponse.setErrorItems(errorListItems); + return errorResponse; + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ApiOriginFilter.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/ApiOriginFilter.java similarity index 84% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ApiOriginFilter.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/ApiOriginFilter.java index e9c4c69da..455d582bb 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.addons/src/main/java/org/wso2/carbon/device/mgt/mobile/android/addons/ApiOriginFilter.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/ApiOriginFilter.java @@ -16,14 +16,9 @@ * under the License. * */ -package org.wso2.carbon.device.mgt.mobile.android.addons; +package org.wso2.carbon.mdm.services.android.util; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/DeviceIDHolder.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/DeviceIDHolder.java new file mode 100644 index 000000000..7b09fc700 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/DeviceIDHolder.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.mdm.services.android.util; + +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; + +import java.util.List; + +/** + * Holder class for storing valid & invalid device-ids. + */ +public class DeviceIDHolder { + + private List errorDeviceIdList; + private List validDeviceIDList; + + public List getErrorDeviceIdList() { + return errorDeviceIdList; + } + + public void setErrorDeviceIdList(List errorDeviceIdList) { + this.errorDeviceIdList = errorDeviceIdList; + } + + public List getValidDeviceIDList() { + return validDeviceIDList; + } + + public void setValidDeviceIDList(List validDeviceIDList) { + this.validDeviceIDList = validDeviceIDList; + } +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/Message.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/Message.java similarity index 87% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/Message.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/Message.java index b8168d837..34cafd064 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/Message.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/java/org/wso2/carbon/mdm/services/android/util/Message.java @@ -16,8 +16,9 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common; +package org.wso2.carbon.mdm.services.android.util; +import javax.ws.rs.core.MediaType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @@ -48,16 +49,16 @@ public class Message { this.responseCode = responseCode; } - private Message.MessageBuilder getBuilder() { - return new Message.MessageBuilder(); + private MessageBuilder getBuilder() { + return new MessageBuilder(); } - public static Message.MessageBuilder responseCode(String responseCode) { + public static MessageBuilder responseCode(String responseCode) { Message message = new Message(); return message.getBuilder().responseCode(responseCode); } - public static Message.MessageBuilder responseMessage(String responseMessage) { + public static MessageBuilder responseMessage(String responseMessage) { Message message = new Message(); return message.getBuilder().responseMessage(responseMessage); } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/META-INF/permissions.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/META-INF/permissions.xml index 0b0e8150f..1c3c034b8 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/META-INF/permissions.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/META-INF/permissions.xml @@ -249,13 +249,6 @@ POST - - Change LockTask mode - /device-mgt/admin/device/android/operation/change-LockTask - /admin/devices/change-LockTask - POST - - Ring device /device-mgt/admin/device/android/operation/ring diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/cxf-servlet.xml index b3afc3e28..4f0e65511 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -26,7 +26,6 @@ - @@ -34,7 +33,7 @@ - + @@ -44,7 +43,8 @@ - + + @@ -59,13 +59,12 @@ - - - - - - - + + + + + + diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/web.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/web.xml index 33eca93f1..b62410431 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/web.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/main/webapp/WEB-INF/web.xml @@ -76,7 +76,7 @@ ApiOriginFilter - org.wso2.carbon.device.mgt.mobile.android.addons.ApiOriginFilter + org.wso2.carbon.mdm.services.android.util.ApiOriginFilter ApiOriginFilter diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/DeviceManagementAdminServiceTests.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/DeviceManagementAdminServiceTests.java new file mode 100644 index 000000000..30e5474d7 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/DeviceManagementAdminServiceTests.java @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.mdm.services.android; + +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockObjectFactory; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.mdm.services.android.mocks.DeviceManagementProviderServiceMock; +import org.wso2.carbon.mdm.services.android.services.impl.DeviceManagementAdminServiceImpl; +import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils; +import org.wso2.carbon.mdm.services.android.utils.TestUtils; + +import javax.ws.rs.core.Response; + +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PrepareForTest(AndroidAPIUtils.class) +public class DeviceManagementAdminServiceTests { + + private DeviceManagementAdminServiceImpl deviceManagementAdminService; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new PowerMockObjectFactory(); + } + + @BeforeClass + public void init() throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + MockitoAnnotations.initMocks(this); + deviceManagementAdminService = new DeviceManagementAdminServiceImpl(); + } + + private void mockDeviceManagementService() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceManagementService")) + .toReturn(new DeviceManagementProviderServiceMock()); + } + + @Test + public void testConfigureDeviceLock() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.configureDeviceLock(TestUtils.getDeviceLockBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testConfigureDeviceUnlock() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.configureDeviceUnlock(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetDeviceLocation() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.getDeviceLocation(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testRemovePassword() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.removePassword(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testConfigureCamera() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.configureCamera(TestUtils.getCamerabeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetDeviceInformation() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.getDeviceInformation(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetDeviceLogcat() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.getDeviceLogcat(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testWipeDevice() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.wipeDevice(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testWipeData() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.wipeData(TestUtils.getWipeDataBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetApplications() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.getApplications(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testRingDevice() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.ringDevice(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testRebootDevice() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.rebootDevice(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testMuteDevice() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.muteDevice(TestUtils.getDeviceIds()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testInstallApplication() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService + .installApplication(TestUtils.getApplicationInstallationBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testUpdateApplication() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.updateApplication(TestUtils.getApplicationUpdateBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testUninstallApplicationPublic() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService + .uninstallApplication(TestUtils.getApplicationUninstallationBeanWrapperPublic()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testUninstallApplicationWebApp() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService + .uninstallApplication(TestUtils.getApplicationUninstallationBeanWrapperWebApp()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testBlacklistApplications() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService + .blacklistApplications(TestUtils.getBlacklistApplicationsBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testUpgradeFirmware() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.upgradeFirmware(TestUtils.getUpgradeFirmwareBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testConfigureVPN() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.configureVPN(TestUtils.getVpnBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testSendNotification() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.sendNotification(TestUtils.getNotificationBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testConfigureWifi() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.configureWifi(TestUtils.getWifiBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testEncryptStorage() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.encryptStorage(TestUtils.getEncryptionBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testChangeLockCode() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.changeLockCode(TestUtils.getLockCodeBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testSetPasswordPolicy() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.setPasswordPolicy(TestUtils.getPasswordPolicyBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testSetWebClip() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementAdminService.setWebClip(TestUtils.getWebClipBeanWrapper()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + +} + diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/DeviceManagementServiceTests.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/DeviceManagementServiceTests.java new file mode 100644 index 000000000..8c6e0afd1 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/DeviceManagementServiceTests.java @@ -0,0 +1,318 @@ +/* + * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.mdm.services.android; + +import org.mockito.MockitoAnnotations; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.testng.PowerMockObjectFactory; +import org.testng.Assert; +import org.testng.IObjectFactory; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.ObjectFactory; +import org.testng.annotations.Test; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice; +import org.wso2.carbon.mdm.services.android.mocks.ApplicationManagementProviderServiceMock; +import org.wso2.carbon.mdm.services.android.mocks.DeviceInformationManagerServiceMock; +import org.wso2.carbon.mdm.services.android.mocks.DeviceManagementProviderServiceMock; +import org.wso2.carbon.mdm.services.android.mocks.NotificationManagementServiceMock; +import org.wso2.carbon.mdm.services.android.mocks.PolicyManagerServiceMock; +import org.wso2.carbon.mdm.services.android.services.impl.DeviceManagementServiceImpl; +import org.wso2.carbon.mdm.services.android.util.AndroidAPIUtils; +import org.wso2.carbon.mdm.services.android.utils.TestUtils; + +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; + +@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) +@PrepareForTest(AndroidAPIUtils.class) +public class DeviceManagementServiceTests { + + private DeviceManagementServiceImpl deviceManagementService; + + @ObjectFactory + public IObjectFactory getObjectFactory() { + return new PowerMockObjectFactory(); + } + + @BeforeClass + public void init() throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + MockitoAnnotations.initMocks(this); + deviceManagementService = new DeviceManagementServiceImpl(); + } + + private void mockDeviceManagementService() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceManagementService")) + .toReturn(new DeviceManagementProviderServiceMock()); + } + + private void mockApplicationManagerService() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getApplicationManagerService")) + .toReturn(new ApplicationManagementProviderServiceMock()); + } + + private void mockPolicyManagerService() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getPolicyManagerService")) + .toReturn(new PolicyManagerServiceMock()); + } + + private void mockDeviceInformationManagerService() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getDeviceInformationManagerService")) + .toReturn(new DeviceInformationManagerServiceMock()); + } + + private void mockNotificationManagementService() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getNotificationManagementService")) + .toReturn(new NotificationManagementServiceMock()); + } + + private void mockUser() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + PowerMockito.stub(PowerMockito.method(AndroidAPIUtils.class, "getAuthenticatedUser")) + .toReturn("admin"); + } + + @Test + public void testUpdateApplicationList() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockApplicationManagerService(); + Response response = deviceManagementService + .updateApplicationList(TestUtils.getDeviceId(), TestUtils.getAndroidApplications()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); + } + + @Test + public void testGetPendingOperationsForNullDevice() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + Response response = deviceManagementService + .getPendingOperations(null, null, null); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); + } + + @Test + public void testGetPendingOperationsInvalidDevice() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementService + .getPendingOperations("1234", null, null); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); + } + + @Test + public void testGetPendingOperationsNullResponse() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementService + .getPendingOperations(TestUtils.getDeviceId(), null, null); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetPendingOperationsWithMonitorResponse() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockPolicyManagerService(); + Response response = deviceManagementService + .getPendingOperations(TestUtils.getDeviceId(), null, + TestUtils.getSuccessMonitorOperationResponse()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetPendingOperationsWithApplicationResponse() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockApplicationManagerService(); + Response response = deviceManagementService + .getPendingOperations(TestUtils.getDeviceId(), null, + TestUtils.getSuccessApplicationOperationResponse()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetPendingOperationsWithDeviceInfoResponse() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockDeviceInformationManagerService(); + Response response = deviceManagementService + .getPendingOperations(TestUtils.getDeviceId(), null, + TestUtils.getSuccessInfoOperationResponse()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetPendingOperationsWithInProgressResponse() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementService + .getPendingOperations(TestUtils.getDeviceId(), null, + TestUtils.getInProgressOperationResponse()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testGetPendingOperationsWithErrorResponse() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockNotificationManagementService(); + Response response = deviceManagementService + .getPendingOperations(TestUtils.getDeviceId(), null, + TestUtils.getErrorOperationResponse()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); + } + + @Test + public void testEnrollDeviceWithoutLocationSuccess() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockPolicyManagerService(); + mockUser(); + Response response = deviceManagementService.enrollDevice(TestUtils.getBasicAndroidDevice()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test + public void testEnrollDeviceWithLocationSuccess() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockDeviceInformationManagerService(); + mockPolicyManagerService(); + mockUser(); + AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice(); + + List properties = new ArrayList<>(); + Device.Property property = new Device.Property(); + property.setName("LATITUDE"); + property.setValue("79.5"); + properties.add(property); + property = new Device.Property(); + property.setName("LONGITUDE"); + property.setValue("6.9"); + properties.add(property); + androidDevice.setProperties(properties); + + Response response = deviceManagementService.enrollDevice(androidDevice); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test + public void testEnrollDeviceUnSuccess() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockUser(); + AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice(); + androidDevice.setDeviceIdentifier("1234"); + Response response = deviceManagementService.enrollDevice(androidDevice); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } + + @Test + public void testIsEnrolledExists() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementService.isEnrolled(TestUtils.getDeviceId(), null); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test + public void testIsEnrolledNonExist() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementService.isEnrolled("1234", null); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); + } + + @Test + public void testIsEnrolledNull() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementService.isEnrolled(null, null); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); + } + + @Test + public void testModifyEnrollmentSuccess() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockUser(); + Response response = deviceManagementService + .modifyEnrollment(TestUtils.getDeviceId(), TestUtils.getBasicAndroidDevice()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.ACCEPTED.getStatusCode()); + } + + @Test + public void testModifyEnrollmentUnSuccess() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + mockUser(); + AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice(); + androidDevice.setDeviceIdentifier("1234"); + Response response = deviceManagementService + .modifyEnrollment(TestUtils.getDeviceId(), androidDevice); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); + } + + @Test + public void testDisEnrollDeviceSuccess() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementService.disEnrollDevice(TestUtils.getDeviceId()); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + } + + @Test + public void testDisenrollUnSuccess() + throws DeviceManagementException, OperationManagementException, InvalidDeviceException { + mockDeviceManagementService(); + Response response = deviceManagementService.disEnrollDevice("1234"); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); + } + +} + diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/ApplicationManagementProviderServiceMock.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/ApplicationManagementProviderServiceMock.java similarity index 98% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/ApplicationManagementProviderServiceMock.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/ApplicationManagementProviderServiceMock.java index 36da0398e..1fe39c731 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/ApplicationManagementProviderServiceMock.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/ApplicationManagementProviderServiceMock.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.core.mokcs; +package org.wso2.carbon.mdm.services.android.mocks; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/DeviceInformationManagerServiceMock.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/DeviceInformationManagerServiceMock.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/DeviceInformationManagerServiceMock.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/DeviceInformationManagerServiceMock.java index bcc69787c..02d086f18 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/DeviceInformationManagerServiceMock.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/DeviceInformationManagerServiceMock.java @@ -1,4 +1,4 @@ -package org.wso2.carbon.device.mgt.mobile.android.core.mokcs; +package org.wso2.carbon.mdm.services.android.mocks; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; @@ -10,7 +10,6 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManag import java.util.List; public class DeviceInformationManagerServiceMock implements DeviceInformationManager { - @Override public void addDeviceInfo(DeviceIdentifier deviceIdentifier, DeviceInfo deviceInfo) throws DeviceDetailsMgtException { @@ -51,5 +50,4 @@ public class DeviceInformationManagerServiceMock implements DeviceInformationMan public List getDeviceLocations(List list) throws DeviceDetailsMgtException { return null; } - } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/DeviceManagementProviderServiceMock.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/DeviceManagementProviderServiceMock.java similarity index 89% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/DeviceManagementProviderServiceMock.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/DeviceManagementProviderServiceMock.java index 9bd50a2f0..ed1e828e5 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/DeviceManagementProviderServiceMock.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/DeviceManagementProviderServiceMock.java @@ -15,48 +15,32 @@ * specific language governing permissions and limitations * under the License. */ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.mobile.android.core.mokcs; +package org.wso2.carbon.mdm.services.android.mocks; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceTransferRequest; +import org.wso2.carbon.device.mgt.common.StartupOperationConfig; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration; +import org.wso2.carbon.device.mgt.common.device.details.DeviceData; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException; +import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.MonitoringOperation; import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.StartupOperationConfig; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; -import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; -import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; -import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.device.details.DeviceData; -import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; import org.wso2.carbon.device.mgt.common.exceptions.UnauthorizedDeviceAccessException; +import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; @@ -72,7 +56,7 @@ import org.wso2.carbon.device.mgt.core.geo.GeoCluster; import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.utils.TestUtils; +import org.wso2.carbon.mdm.services.android.utils.TestUtils; import java.util.Date; import java.util.HashMap; @@ -80,7 +64,6 @@ import java.util.List; import java.util.Map; public class DeviceManagementProviderServiceMock implements DeviceManagementProviderService { - @Override public List getAllDevices(String s) throws DeviceManagementException { return null; @@ -158,11 +141,7 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv @Override public Device getDevice(String s, boolean b) throws DeviceManagementException { - if (TestUtils.getDeviceId().equals(s)) { - return TestUtils.getDevice(); - } else { - return null; - } + return null; } @Override @@ -192,11 +171,8 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv @Override public Device getDevice(String s, Date date, boolean b) throws DeviceManagementException { - if (TestUtils.getDeviceId().equals(s)) { - return TestUtils.getDevice(); - } else { - return null; - } } + return null; + } @Override public Device getDevice(DeviceIdentifier deviceIdentifier, String s, Date date, boolean b) @@ -346,13 +322,12 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv } @Override - public FeatureManager getFeatureManager(String s) throws DeviceTypeNotFoundException { + public FeatureManager getFeatureManager(String s) { return null; } @Override - public PolicyConfigurationManager getPolicyUIConfigurationManager(String s) - throws DeviceTypeNotFoundException { + public PolicyConfigurationManager getPolicyUIConfigurationManager(String s) throws DeviceTypeNotFoundException { return null; } @@ -401,6 +376,11 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv return TestUtils.getDeviceId().equals(deviceIdentifier.getId()); } + @Override + public boolean deleteDevices(List list) throws DeviceManagementException, InvalidDeviceException { + return false; + } + @Override public boolean isEnrolled(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { return false; @@ -493,8 +473,7 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv } @Override - public Operation getNextPendingOperation(DeviceIdentifier deviceIdentifier, long l) - throws OperationManagementException { + public Operation getNextPendingOperation(DeviceIdentifier deviceIdentifier, long l) throws OperationManagementException { return null; } @@ -553,14 +532,12 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv return null; } - @Override - public List getFilteredActivities(String operationCode, int limit, int offset) + @Override public List getFilteredActivities(String operationCode, int limit, int offset) throws OperationManagementException { return null; } - @Override - public int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementException { + @Override public int getTotalCountOfFilteredActivities(String operationCode) throws OperationManagementException { return 0; } @@ -636,14 +613,12 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv } @Override - public List getDeviceTypes(PaginationRequest paginationRequest) - throws DeviceManagementException { + public List getDeviceTypes(PaginationRequest paginationRequest) throws DeviceManagementException { return null; } @Override - public List getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long l, - long l1) throws DeviceManagementException { + public List getDeviceLocationInfo(DeviceIdentifier deviceIdentifier, long l, long l1) throws DeviceManagementException { return null; } @@ -680,13 +655,12 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv } @Override - public boolean updateEnrollment(String owner, List deviceIdentifiers) { + public boolean updateEnrollment(String s, List list) throws DeviceManagementException, UserNotFoundException, InvalidDeviceException { return false; } @Override - public boolean addDeviceTypeVersion(DeviceTypeVersion deviceTypeVersion) - throws DeviceManagementException { + public boolean addDeviceTypeVersion(DeviceTypeVersion deviceTypeVersion) throws DeviceManagementException { return false; } @@ -696,8 +670,7 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv } @Override - public boolean updateDeviceTypeVersion(DeviceTypeVersion deviceTypeVersion) - throws DeviceManagementException { + public boolean updateDeviceTypeVersion(DeviceTypeVersion deviceTypeVersion) throws DeviceManagementException { return false; } @@ -722,33 +695,27 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv } @Override - public boolean deleteDeviceType(String s, DeviceType deviceType) - throws DeviceManagementException { + public boolean deleteDeviceType(String s, DeviceType deviceType) throws DeviceManagementException { return false; } @Override - public DeviceConfiguration getDeviceConfiguration(Map propertyMap) - throws DeviceManagementException, DeviceNotFoundException, UnauthorizedDeviceAccessException, - AmbiguousConfigurationException { + public DeviceConfiguration getDeviceConfiguration(Map map) throws DeviceManagementException, DeviceNotFoundException, UnauthorizedDeviceAccessException, AmbiguousConfigurationException { return null; } @Override - public List transferDeviceToTenant(DeviceTransferRequest deviceTransferRequest) - throws DeviceManagementException, DeviceNotFoundException { + public List transferDeviceToTenant(DeviceTransferRequest deviceTransferRequest) throws DeviceManagementException, DeviceNotFoundException { return null; } @Override - public PaginationResult getAppSubscribedDevices(int i, int i1, List list, String s) - throws DeviceManagementException { + public PaginationResult getAppSubscribedDevices(int i, int i1, List list, String s) throws DeviceManagementException { return null; } @Override - public PaginationResult getApplications(PaginationRequest paginationRequest) - throws ApplicationManagementException, DeviceTypeNotFoundException { + public PaginationResult getApplications(PaginationRequest paginationRequest) throws ApplicationManagementException, DeviceTypeNotFoundException { return null; } @@ -761,10 +728,4 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv public int getFunctioningDevicesInSystem() throws DeviceManagementException { return 0; } - - @Override - public boolean deleteDevices(List deviceIdentifiers) - throws DeviceManagementException, InvalidDeviceException { - return false; - } } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/NotificationManagementServiceMock.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/NotificationManagementServiceMock.java similarity index 97% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/NotificationManagementServiceMock.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/NotificationManagementServiceMock.java index 1f9cafbd3..4fd989de6 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/NotificationManagementServiceMock.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/NotificationManagementServiceMock.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.core.mokcs; +package org.wso2.carbon.mdm.services.android.mocks; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationRequest; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/PolicyManagerServiceMock.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/PolicyManagerServiceMock.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/PolicyManagerServiceMock.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/PolicyManagerServiceMock.java index cf406ed12..537b2e874 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/PolicyManagerServiceMock.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/PolicyManagerServiceMock.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.core.mokcs; +package org.wso2.carbon.mdm.services.android.mocks; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.Feature; @@ -143,9 +143,7 @@ public class PolicyManagerServiceMock implements PolicyManagerService { } @Override - public PaginationResult getPolicyCompliance(PaginationRequest paginationRequest, String s, - boolean b, boolean b1, String s1, String s2) - throws PolicyComplianceException { + public PaginationResult getPolicyCompliance(PaginationRequest paginationRequest, String s, boolean b, boolean b1, String s1, String s2) throws PolicyComplianceException { return null; } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/utils/TestUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/utils/TestUtils.java similarity index 87% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/utils/TestUtils.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/utils/TestUtils.java index 51eecfdae..cff3d8ca2 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/mokcs/utils/TestUtils.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/utils/TestUtils.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.core.mokcs.utils; +package org.wso2.carbon.mdm.services.android.utils; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; @@ -26,40 +26,40 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ApplicationInstallation; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ApplicationUninstallation; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ApplicationUpdate; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.BlacklistApplications; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Camera; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceEncryption; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceLock; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.LockCode; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Notification; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.PasscodePolicy; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.UpgradeFirmware; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Vpn; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.WebClip; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.Wifi; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.WipeData; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidApplication; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidDevice; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationInstallationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationUninstallationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.ApplicationUpdateBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.BlacklistApplicationsBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.CameraBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.DeviceLockBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.EncryptionBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.LockCodeBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.NotificationBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.PasswordPolicyBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.UpgradeFirmwareBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.VpnBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WebClipBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WifiBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.WipeDataBeanWrapper; -import org.wso2.carbon.device.mgt.mobile.android.core.util.MobileDeviceManagementUtil; +import org.wso2.carbon.mdm.services.android.bean.ApplicationInstallation; +import org.wso2.carbon.mdm.services.android.bean.ApplicationUninstallation; +import org.wso2.carbon.mdm.services.android.bean.ApplicationUpdate; +import org.wso2.carbon.mdm.services.android.bean.BlacklistApplications; +import org.wso2.carbon.mdm.services.android.bean.Camera; +import org.wso2.carbon.mdm.services.android.bean.DeviceEncryption; +import org.wso2.carbon.mdm.services.android.bean.DeviceLock; +import org.wso2.carbon.mdm.services.android.bean.LockCode; +import org.wso2.carbon.mdm.services.android.bean.Notification; +import org.wso2.carbon.mdm.services.android.bean.PasscodePolicy; +import org.wso2.carbon.mdm.services.android.bean.UpgradeFirmware; +import org.wso2.carbon.mdm.services.android.bean.Vpn; +import org.wso2.carbon.mdm.services.android.bean.WebClip; +import org.wso2.carbon.mdm.services.android.bean.Wifi; +import org.wso2.carbon.mdm.services.android.bean.WipeData; +import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidApplication; +import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice; +import org.wso2.carbon.mdm.services.android.bean.wrapper.ApplicationInstallationBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.ApplicationUninstallationBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.ApplicationUpdateBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.BlacklistApplicationsBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.CameraBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.DeviceLockBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.EncryptionBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.LockCodeBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.NotificationBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.PasswordPolicyBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.UpgradeFirmwareBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.VpnBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.WebClipBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.WifiBeanWrapper; +import org.wso2.carbon.mdm.services.android.bean.wrapper.WipeDataBeanWrapper; +import org.wso2.carbon.mdm.services.android.util.AndroidConstants; +import org.wso2.carbon.mdm.services.android.util.AndroidDeviceUtils; import java.util.ArrayList; import java.util.List; @@ -381,7 +381,7 @@ public class TestUtils { location.setCountry("Sri Lanka"); location.setLatitude(6.9); location.setLongitude(79.5); - location.setDeviceIdentifier(MobileDeviceManagementUtil.convertToDeviceIdentifierObject(getDeviceId())); + location.setDeviceIdentifier(AndroidDeviceUtils.convertToDeviceIdentifierObject(getDeviceId())); return location; } @@ -403,7 +403,7 @@ public class TestUtils { public static List getApplications() { List applications = new ArrayList<>(); Application app = new Application(); - app.setName("Entgra IoT Agent"); + app.setName("WSO2 IoT Agent"); app.setApplicationIdentifier("org.wos2.iot.agent"); app.setVersion("1.0.0"); app.setPlatform("Android"); diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/resources/log4j.properties b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/resources/log4j.properties similarity index 100% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/resources/log4j.properties rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/resources/log4j.properties diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/resources/testng.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/resources/testng.xml similarity index 80% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/resources/testng.xml rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/resources/testng.xml index edecf75b9..865a1e85b 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/resources/testng.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/resources/testng.xml @@ -23,8 +23,8 @@ - - + + diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/pom.xml deleted file mode 100644 index 6b11c155e..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/pom.xml +++ /dev/null @@ -1,166 +0,0 @@ - - - - - - android-plugin - org.wso2.carbon.devicemgt-plugins - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.device.mgt.mobile.android.common - bundle - WSO2 Carbon - Mobile Device Management Android Common Impl - WSO2 Carbon - Mobile Device Management Android Common Implementation - https://entgra.io/ - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - ${carbon.devicemgt.plugins.version} - Device Management Mobile Android Impl Bundle - - io.swagger.annotations.*;resolution:=optional, - javax.validation.constraints, - javax.xml.bind.annotation.*, - javax.xml, - javax.xml.stream, - javax.xml.bind.*, - javax.xml.parsers; version=0.0.0, - javax.naming, - org.wso2.carbon.context, - org.wso2.carbon.utils.*, - org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.ndatasource.core, - org.wso2.carbon.policy.mgt.common.*, - org.wso2.carbon.device.mgt.extensions.license.mgt.registry, - com.google.gson.* - - - org.wso2.carbon.device.mgt.mobile.android.common.* - - - - - - - - - - org.eclipse.osgi - org.eclipse.osgi - - - org.wso2.carbon - org.wso2.carbon.logging - - - com.google.code.gson - gson - - - io.swagger - swagger-annotations - - - org.hibernate - hibernate-validator - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - provided - - - commons-logging - commons-logging - - - objenesis - org.objenesis - - - guava - com.google.guava - - - - - org.codehaus.jackson - jackson-core-asl - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - - - woodstox-core-asl - org.codehaus.woodstox - - - commons-logging - commons-logging - - - axiom-api - org.apache.ws.commons.axiom - - - geronimo-stax-api_1.0_spec - org.apache.geronimo.specs.wso2 - - - axis2-client - org.apache.axis2.wso2 - - - httpcore - org.apache.httpcomponents - - - - - com.google.apis - google-api-services-androidenterprise - - - commons-logging - commons-logging - - - - - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/AndroidConstants.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/AndroidConstants.java deleted file mode 100644 index 437646f03..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/AndroidConstants.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http:www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - * Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common; - -import com.sun.org.apache.bcel.internal.generic.ATHROW; - -/** - * Defines constants used in Android-REST API bundle. - */ -public final class AndroidConstants { - - public static final String DEVICE_TYPE_ANDROID = "android"; - public static final String HEADER_CONTENT_TYPE = "Content-Type"; - public static final String APPLICATION_JSON = "application/json"; - public static final String SCOPE = "scope"; - - public static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress"; - public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname"; - public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname"; - - public static final String USER_CLAIM_EMAIL_ADDRESS_PLACEHOLDER = "$email"; - public static final String USER_CLAIM_FIRST_NAME_PLACEHOLDER = "$firstName"; - public static final String USER_CLAIM_LAST_NAME_PLACEHOLDER = "$lastName"; - - public static final String GOOGLE_PLAY_SYNCED_APP_CATEGORY = "GooglePlaySyncedApp"; - - public final class DeviceProperties { - private DeviceProperties() { - throw new AssertionError(); - } - - public static final String PROPERTY_USER_KEY = "username"; - public static final String PROPERTY_DEVICE_KEY = "device"; - } - - public final class DeviceFeatures { - private DeviceFeatures() { - throw new AssertionError(); - } - } - - public final class DeviceConstants { - private DeviceConstants() { - throw new AssertionError(); - } - - public static final String DEVICE_MAC_KEY = "mac"; - public static final String DEVICE_DESCRIPTION_KEY = "description"; - public static final String DEVICE_OWNERSHIP_KEY = "ownership"; - public static final String DEVICE_PROPERTIES_KEY = "properties"; - public static final String DEVICE_FEATURES_KEY = "features"; - public static final String DEVICE_DATA = "data"; - public static final String DEVICE_ID_NOT_FOUND = "Device not found for device id: %s"; - public static final String DEVICE_ID_SERVICE_NOT_FOUND = - "Issue in retrieving device management service instance for device found at %s"; - } - - public final class Messages { - private Messages() { - throw new AssertionError(); - } - - public static final String DEVICE_MANAGER_SERVICE_NOT_AVAILABLE = - "Device Manager service not available"; - } - - public final class OperationCodes { - private OperationCodes() { - throw new AssertionError(); - } - - public static final String DEVICE_LOCK = "DEVICE_LOCK"; - public static final String FILE_DOWNLOAD = "FILE_UPLOAD_TO_THE_DEVICE"; - public static final String FILE_UPLOAD = "FILE_DOWNLOAD_FROM_THE_DEVICE"; - public static final String DEVICE_UNLOCK = "DEVICE_UNLOCK"; - public static final String DEVICE_LOCATION = "DEVICE_LOCATION"; - public static final String WIFI = "WIFI"; - public static final String CAMERA = "CAMERA"; - public static final String DEVICE_MUTE = "DEVICE_MUTE"; - public static final String PASSCODE_POLICY = "PASSCODE_POLICY"; - public static final String DEVICE_INFO = "DEVICE_INFO"; - public static final String ENTERPRISE_WIPE = "ENTERPRISE_WIPE"; - public static final String CLEAR_PASSWORD = "CLEAR_PASSWORD"; - public static final String WIPE_DATA = "WIPE_DATA"; - public static final String APPLICATION_LIST = "APPLICATION_LIST"; - public static final String CHANGE_LOCK_CODE = "CHANGE_LOCK_CODE"; - public static final String INSTALL_APPLICATION = "INSTALL_APPLICATION"; - public static final String UPDATE_APPLICATION = "UPDATE_APPLICATION"; - public static final String UNINSTALL_APPLICATION = "UNINSTALL_APPLICATION"; - public static final String BLACKLIST_APPLICATIONS = "BLACKLIST_APPLICATIONS"; - public static final String ENCRYPT_STORAGE = "ENCRYPT_STORAGE"; - public static final String DEVICE_RING = "DEVICE_RING"; - public static final String DEVICE_REBOOT = "REBOOT"; - public static final String CHANGE_LOCK_TASK_MODE = "CHANGE_LOCK_TASK_MODE"; - public static final String UPGRADE_FIRMWARE = "UPGRADE_FIRMWARE"; - public static final String NOTIFICATION = "NOTIFICATION"; - public static final String POLICY_BUNDLE = "POLICY_BUNDLE"; - public static final String WEBCLIP = "WEBCLIP"; - public static final String DISENROLL = "DISENROLL"; - public static final String MONITOR = "MONITOR"; - public static final String VPN = "VPN"; - public static final String LOGCAT = "LOGCAT"; - public static final String APP_RESTRICTION = "APP-RESTRICTION"; - public static final String WORK_PROFILE = "WORK_PROFILE"; - public static final String NOTIFIER_FREQUENCY = "NOTIFIER_FREQUENCY"; - public static final String GLOBAL_PROXY = "SET_GLOBAL_PROXY"; - public static final String REMOTE_APP_CONFIG = "REMOTE_APP_CONFIG"; - public static final String DISPLAY_MESSAGE_CONFIGURATION = "DISPLAY_MESSAGE_CONFIGURATION"; - } - - public final class StatusCodes { - private StatusCodes() { - throw new AssertionError(); - } - - public static final int MULTI_STATUS_HTTP_CODE = 207; - } - - public final class TenantConfigProperties { - private TenantConfigProperties() { - throw new AssertionError(); - } - - public static final String LICENSE_KEY = "androidEula"; - public static final String LANGUAGE_US = "en_US"; - public static final String CONTENT_TYPE_TEXT = "text"; - public static final String NOTIFIER_FREQUENCY = "notifierFrequency"; - public static final String NOTIFIER_TYPE = "notifierType"; - public static final String SERVER_VERSION = "serverVersion"; - } - - public final class ApplicationProperties { - private ApplicationProperties() { - throw new AssertionError(); - } - - public static final String NAME = "name"; - public static final String IDENTIFIER = "package"; - public static final String USS = "USS"; - public static final String VERSION = "version"; - public static final String ICON = "icon"; - public static final String IS_ACTIVE = "isActive"; - public static final String FREE_SUB_METHOD = "FREE"; - public static final String PAID_SUB_METHOD = "PAID"; - public static final String TYPE = "type"; - public static final String ENTERPRISE = "ENTERPRISE"; - public static final String WEB_CLIP = "WEB_CLIP"; - public static final String WEBAPP = "WEBAPP"; - public static final String PACKAGE_NAME = "packageName"; - public static final String APP_IDENTIFIER = "appIdentifier"; - public static final String AGENT_VERSION = "AGENT_VERSION"; - - } - - public final class ApplicationInstall { - private ApplicationInstall() { - throw new AssertionError(); - } - - public static final String APPLICATION_NAME = "device_type_android"; - public static final String ENROLLMENT_APP_INSTALL_FEATURE_CODE = "ENROLLMENT_APP_INSTALL"; - public static final String DEFAULT_TOKEN_TYPE = "PRODUCTION"; - public static final String DEFAULT_VALIDITY_PERIOD = "3600"; - public static final String SUBSCRIPTION_SCOPE = "appm:subscribe"; - public static final String ENROLLMENT_APP_INSTALL_UUID = "uuid"; - public static final String ENROLLMENT_APP_INSTALL_APP_ID = "appId"; - public static final String GOOGLE_POLICY_PAYLOAD = "installGooglePolicyPayload"; - public static final String ENROLLMENT_APP_INSTALL_CODE = "enrollmentAppInstall"; - public static final String ENCODING = "UTF-8"; - public static final String AT = "@"; - public static final String COLON = ":"; - public static final String IOT_CORE_HOST = "iot.core.host"; - public static final String IOT_CORE_PORT = "iot.core.https.port"; - public static final String ENROLLMENT_APP_INSTALL_PROTOCOL = "https://"; - public static final String ENROLLMENT_APP_INSTALL_URL = "/api/application-mgt-store/v1.0/subscription/{uuid}/devices/install"; - public static final String AUTHORIZATION = "Authorization"; - public static final String AUTHORIZATION_HEADER_VALUE = "Bearer "; - public static final String BEHAVIOUR_WHITELISTED_APPS_ONLY = "whitelist"; - public static final String INSTALL = "INSTALL"; - public static final String UNINSTALL = "UNINSTALL"; - public static final String INSTALL_APPLICATION = "INSTALL_APPLICATION"; - public static final String UNINSTALL_APPLICATION = "UNINSTALL_APPLICATION"; - - } - - public final class ErrorMessages { - private ErrorMessages () { throw new AssertionError(); } - - public static final String STATUS_BAD_REQUEST_MESSAGE_DEFAULT = "Bad Request"; - - } - - public final class PlatformConfigs { - private PlatformConfigs() { throw new AssertionError(); } - - public final class KioskConfigs { - private KioskConfigs() { throw new AssertionError(); } - - public static final String ADMIN_COMPONENT_NAME = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME"; - public static final String WIFI_SSID = "android.app.extra.PROVISIONING_WIFI_SSID"; - public static final String WIFI_PASSWORD = "android.app.extra.PROVISIONING_WIFI_PASSWORD"; - public static final String WIFI_SECURITY = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE"; - public static final String SKIP_ENCRYPTION = "android.app.extra.PROVISIONING_SKIP_ENCRYPTION"; - public static final String CHECKSUM = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM"; - public static final String DOWNLOAD_URL = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION"; - public static final String ANDROID_EXTRA = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE"; - } - - public final class DefaultConfigs { - private DefaultConfigs() { throw new AssertionError(); } - - public static final String ACCESS_TOKEN = "android.app.extra.token"; - public static final String DEFAULT_OWNERSHIP = "android.app.extra.defaultOwner"; - public static final String SERVER_IP = "android.app.extra.serverIp"; - } - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApiRegistrationProfile.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApiRegistrationProfile.java deleted file mode 100644 index a88a907e7..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApiRegistrationProfile.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -public class ApiRegistrationProfile { - - private String applicationName; - private String tags[]; - private boolean isAllowedToAllDomains; - private boolean isMappingAnExistingOAuthApp; - - public String getApplicationName() { - return applicationName; - } - - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - public String[] getTags() { - return tags; - } - - public void setTags(String[] tags) { - this.tags = tags; - } - - public boolean isAllowedToAllDomains() { - return isAllowedToAllDomains; - } - - public void setAllowedToAllDomains(boolean allowedToAllDomains) { - isAllowedToAllDomains = allowedToAllDomains; - } - - public boolean isMappingAnExistingOAuthApp() { - return isMappingAnExistingOAuthApp; - } - - public void setMappingAnExistingOAuthApp(boolean mappingAnExistingOAuthApp) { - isMappingAnExistingOAuthApp = mappingAnExistingOAuthApp; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationRestriction.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationRestriction.java deleted file mode 100644 index 1ed7f1243..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ApplicationRestriction.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import java.io.Serializable; - -/** - * This class represents the information of sending application config operation. - */ -@ApiModel(value = "ApplicationRestriction", - description = "Details related to application config passed to device.") -public class ApplicationRestriction extends AndroidOperation implements Serializable { - private static final long serialVersionUID = 1995401458L; - - @ApiModelProperty(name = "appIdentifier", value = "The application identifier to be sent.", required = true) - private String appIdentifier; - - @ApiModelProperty(name = "restrictionPayload", value = "The restriction payload to be sent.", required = true) - private String restrictionPayload; - - public String getAppIdentifier() { - return appIdentifier; - } - - public void setAppIdentifier(String appIdentifier) { - this.appIdentifier = appIdentifier; - } - - public String getRestrictionPayload() { - return restrictionPayload; - } - - public void setRestrictionPayload(String restrictionPayload) { - this.restrictionPayload = restrictionPayload; - } -} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/BasicUserInfo.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/BasicUserInfo.java deleted file mode 100644 index 1f361b336..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/BasicUserInfo.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "BasicUserInfo", description = "Basic user information and the roles of the user.") -public class BasicUserInfo { - - @ApiModelProperty(name = "username", value = "The login name of the user.", required = true ) - private String username; - @ApiModelProperty(name = "firstname", value = "The first name of the user.", required = true ) - private String firstname; - @ApiModelProperty(name = "lastname", value = "The last name of the user.", required = true ) - private String lastname; - @ApiModelProperty(name = "emailAddress", value = "The email address of the user.", required = true ) - private String emailAddress; - @ApiModelProperty(name = "createdDate", value = "User creation date." ) - private String createdDate; - @ApiModelProperty(name = "modifiedDate", value = "User modifiedDate date." ) - private String modifiedDate; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getFirstname() { - return firstname; - } - - public void setFirstname(String firstname) { - this.firstname = firstname; - } - - public String getLastname() { - return lastname; - } - - public void setLastname(String lastname) { - this.lastname = lastname; - } - - public String getEmailAddress() { - return emailAddress; - } - - public void setEmailAddress(String emailAddress) { - this.emailAddress = emailAddress; - } - - public String getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(String createdDate) { - this.createdDate = createdDate; - } - - public String getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(String modifiedDate) { - this.modifiedDate = modifiedDate; - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DisplayMessage.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DisplayMessage.java deleted file mode 100644 index eda425738..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/DisplayMessage.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import java.io.Serializable; - -/** - * This class represents the information of configuring display message operation. - */ -@ApiModel(value = "LockScreenMessage", description = "This class represents the information of configuring wifi operation") -public class DisplayMessage extends AndroidOperation implements Serializable { - - @ApiModelProperty(name = "lockScreenMessage", value = "The message of the lock screen that you wish to configure", - required = true) - private String lockScreenMessage; - @ApiModelProperty(name = "settingAppSupportMessage", value = "The message of the administrators applications that you wish to configure", - required = true) - private String settingAppSupportMessage; - @ApiModelProperty(name = "disabledSettingSupportMessage", value = "The password to connect to the specified Wifi network", - required = true) - private String disabledSettingSupportMessage; - - public String getLockScreenMessage() { - return lockScreenMessage; - } - - public void setLockScreenMessage(String lockScreenMessage) { - this.lockScreenMessage = lockScreenMessage; - } - - public String getSettingAppSupportMessage() { - return settingAppSupportMessage; - } - - public void setSettingAppSupportMessage(String settingAppSupportMessage) { - this.settingAppSupportMessage = settingAppSupportMessage; - } - - public String getDisabledSettingSupportMessage() { - return disabledSettingSupportMessage; - } - - public void setDisabledSettingSupportMessage(String disabledSettingSupportMessage) { - this.disabledSettingSupportMessage = disabledSettingSupportMessage; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseConfigs.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseConfigs.java deleted file mode 100644 index 81d58ec42..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseConfigs.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -public class EnterpriseConfigs { - - String enterpriseId; - String esa; - ErrorResponse errorResponse; - - public ErrorResponse getErrorResponse() { - return errorResponse; - } - - public void setErrorResponse(ErrorResponse errorResponse) { - this.errorResponse = errorResponse; - } - - public String getEnterpriseId() { - return enterpriseId; - } - - public void setEnterpriseId(String enterpriseId) { - this.enterpriseId = enterpriseId; - } - - public String getEsa() { - return esa; - } - - public void setEsa(String esa) { - this.esa = esa; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStoreCluster.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStoreCluster.java deleted file mode 100644 index 59d2eff9c..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStoreCluster.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -import java.util.List; - -public class EnterpriseStoreCluster { - - String pageId; - String clusterId; - String name; - List products; - String orderInPage; - - public String getClusterId() { - return clusterId; - } - - public void setClusterId(String clusterId) { - this.clusterId = clusterId; - } - - public String getPageId() { - return pageId; - } - - public void setPageId(String pageId) { - this.pageId = pageId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getProducts() { - return products; - } - - public void setProducts(List products) { - this.products = products; - } - - public String getOrderInPage() { - return orderInPage; - } - - public void setOrderInPage(String orderInPage) { - this.orderInPage = orderInPage; - } - - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePackages.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePackages.java deleted file mode 100644 index 69dba56d9..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePackages.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - - -public class EnterpriseStorePackages { - - String packageId; - String iconUrl; - - public String getPackageId() { - return packageId; - } - - public void setPackageId(String packageId) { - this.packageId = packageId; - } - - public String getIconUrl() { - return iconUrl; - } - - public void setIconUrl(String iconUrl) { - this.iconUrl = iconUrl; - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePage.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePage.java deleted file mode 100644 index b6b578897..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePage.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -import java.util.List; - -public class EnterpriseStorePage { - - String locale; - String pageName; - String pageId; - List links; - - public String getPageId() { - return pageId; - } - - public void setPageId(String pageId) { - this.pageId = pageId; - } - - public List getLinks() { - return links; - } - - public void setLinks(List links) { - this.links = links; - } - - public String getLocale() { - return locale; - } - - public void setLocale(String locale) { - this.locale = locale; - } - - public String getPageName() { - return pageName; - } - - public void setPageName(String pageName) { - this.pageName = pageName; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePageLinks.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePageLinks.java deleted file mode 100644 index 73b514830..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseStorePageLinks.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -import java.util.List; - -public class EnterpriseStorePageLinks { - - String pageId; - List links; - - public String getPageId() { - return pageId; - } - - public void setPageId(String pageId) { - this.pageId = pageId; - } - - public List getLinks() { - return links; - } - - public void setLinks(List links) { - this.links = links; - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseTokenUrl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseTokenUrl.java deleted file mode 100644 index 7aaf2739d..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/EnterpriseTokenUrl.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -public class EnterpriseTokenUrl { - - String enterpriseId; - String parentHost; - boolean approveApps; - boolean searchEnabled; - boolean isPrivateAppsEnabled; - boolean isWebAppEnabled; - boolean isOrganizeAppPageVisible; - boolean isManagedConfigEnabled; - - public String getEnterpriseId() { - return enterpriseId; - } - - public void setEnterpriseId(String enterpriseId) { - this.enterpriseId = enterpriseId; - } - - public String getParentHost() { - return parentHost; - } - - public void setParentHost(String parentHost) { - this.parentHost = parentHost; - } - - public boolean isApproveApps() { - return approveApps; - } - - public void setApproveApps(boolean approveApps) { - this.approveApps = approveApps; - } - - public boolean isSearchEnabled() { - return searchEnabled; - } - - public void setSearchEnabled(boolean searchEnabled) { - this.searchEnabled = searchEnabled; - } - - public boolean isPrivateAppsEnabled() { - return isPrivateAppsEnabled; - } - - public void setPrivateAppsEnabled(boolean privateAppsEnabled) { - isPrivateAppsEnabled = privateAppsEnabled; - } - - public boolean isWebAppEnabled() { - return isWebAppEnabled; - } - - public void setWebAppEnabled(boolean webAppEnabled) { - isWebAppEnabled = webAppEnabled; - } - - public boolean isOrganizeAppPageVisible() { - return isOrganizeAppPageVisible; - } - - public void setOrganizeAppPageVisible(boolean organizeAppPageVisible) { - isOrganizeAppPageVisible = organizeAppPageVisible; - } - - public boolean isManagedConfigEnabled() { - return isManagedConfigEnabled; - } - - public void setManagedConfigEnabled(boolean managedConfigEnabled) { - isManagedConfigEnabled = managedConfigEnabled; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/GlobalProxy.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/GlobalProxy.java deleted file mode 100644 index 46fb31c73..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/GlobalProxy.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.apache.commons.lang.StringUtils; - -import java.io.Serializable; - -/** - * This class represents the information of setting up global proxy - */ - -@ApiModel( - value = "GlobalProxy", - description = "This class represents the information of setting up global proxy" -) -public class GlobalProxy extends AndroidOperation implements Serializable { - - @ApiModelProperty( - name = "proxyConfigType", - value = "Type of the proxy", - required = true - ) - private ProxyType proxyConfigType; - - @ApiModelProperty( - name = "proxyHost", - value = "The hostname of the proxy server" - ) - private String proxyHost; - - @ApiModelProperty( - name = "proxyPort", - value = "The port which the proxy server is running" - ) - private int proxyPort; - - @ApiModelProperty( - name = "proxyExclList", - value = "Hosts to exclude using the proxy on connections for. These hosts can use wildcards such as " + - "*.example.com" - ) - private String proxyExclList; - - @ApiModelProperty( - name = "proxyPacUrl", - value = "PAC file URL to auto config proxy" - ) - private String proxyPacUrl; - - public boolean validateRequest() { - if (ProxyType.MANUAL.equals(this.proxyConfigType)) { - if (StringUtils.isEmpty(this.proxyHost)) { - return false; - } - if (this.proxyPort < 0 || this.proxyPort > 65535) { - return false; - } - } else if (ProxyType.AUTO.equals(this.proxyConfigType)) { - if (StringUtils.isEmpty(proxyPacUrl)) { - return false; - } - } - return false; - } - - public ProxyType getProxyConfigType() { - return proxyConfigType; - } - - public void setProxyConfigType(ProxyType proxyConfigType) { - this.proxyConfigType = proxyConfigType; - } - - public String getProxyHost() { - return proxyHost; - } - - public void setProxyHost(String proxyHost) { - this.proxyHost = proxyHost; - } - - public int getProxyPort() { - return proxyPort; - } - - public void setProxyPort(int proxyPort) { - this.proxyPort = proxyPort; - } - - public String getProxyExclList() { - return proxyExclList; - } - - public void setProxyExclList(String proxyExclList) { - this.proxyExclList = proxyExclList; - } - - public String getProxyPacUrl() { - return proxyPacUrl; - } - - public void setProxyPacUrl(String proxyPacUrl) { - this.proxyPacUrl = proxyPacUrl; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/GoogleAppSyncResponse.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/GoogleAppSyncResponse.java deleted file mode 100644 index 896eeef08..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/GoogleAppSyncResponse.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -public class GoogleAppSyncResponse { - - int totalApps; - - public int getTotalApps() { - return totalApps; - } - - public void setTotalApps(int totalApps) { - this.totalApps = totalApps; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ProxyType.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ProxyType.java deleted file mode 100644 index d638b071f..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/ProxyType.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.wso2.carbon.device.mgt.mobile.android.common.bean; - -public enum ProxyType { - MANUAL, AUTO -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationRestrictionBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationRestrictionBeanWrapper.java deleted file mode 100644 index 0f6e8b979..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/ApplicationRestrictionBeanWrapper.java +++ /dev/null @@ -1,55 +0,0 @@ - -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ApplicationRestriction; - -import java.util.List; - -/** - * This class is used to wrap the Notification bean with devices. - */ -@ApiModel(value = "ApplicationRestrictionBeanWrapper", - description = "Mapping between application restriction operation and device list to be applied.") -public class ApplicationRestrictionBeanWrapper { - - @ApiModelProperty(name = "deviceIDs", value = "List of device Ids", required = true) - private List deviceIDs; - @ApiModelProperty(name = "operation", value = "The information of application restriction operation", - required = true) - private ApplicationRestriction operation; - - public List getDeviceIDs() { - return deviceIDs; - } - - public void setDeviceIDs(List deviceIDs) { - this.deviceIDs = deviceIDs; - } - - public ApplicationRestriction getOperation() { - return operation; - } - - public void setOperation(ApplicationRestriction operation) { - this.operation = operation; - } -} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DisplayMessageBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DisplayMessageBeanWrapper.java deleted file mode 100644 index ca1330b3c..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/DisplayMessageBeanWrapper.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DisplayMessage; - -import java.util.List; - -/** - * This class is used to wrap the Wifi bean with devices. - */ -@ApiModel(value = "DisplayMessageBeanWrapper", - description = "Mapping between display message operation and device list to be applied.") -public class DisplayMessageBeanWrapper { - - @ApiModelProperty(name = "operation", value = "Information of configuring display message operation", required = true) - private DisplayMessage operation; - @ApiModelProperty(name = "deviceIDs", value = "List of device Ids", required = true) - private List deviceIDs; - - public DisplayMessage getOperation() { - return operation; - } - - public void setOperation(DisplayMessage operation) { - this.operation = operation; - } - - public List getDeviceIDs() { - return deviceIDs; - } - - public void setDeviceIDs(List deviceIDs) { - this.deviceIDs = deviceIDs; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseApp.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseApp.java deleted file mode 100644 index 1d12d1d95..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseApp.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; - -import com.google.api.services.androidenterprise.model.VariableSet; - -import java.io.Serializable; -import java.util.List; - -public class EnterpriseApp implements Serializable { - private static final long serialVersionUID = 45598101734L; - - String productId; - String autoInstallMode; - int autoInstallPriority; - String chargingStateConstraint; - String deviceIdleStateConstraint; - String networkTypeConstraint; - - String mcmId; - List variableSet; - - public String getProductId() { - return productId; - } - - public void setProductId(String productId) { - this.productId = productId; - } - - public String getAutoInstallMode() { - return autoInstallMode; - } - - public void setAutoInstallMode(String autoInstallMode) { - this.autoInstallMode = autoInstallMode; - } - - public int getAutoInstallPriority() { - return autoInstallPriority; - } - - public void setAutoInstallPriority(int autoInstallPriority) { - this.autoInstallPriority = autoInstallPriority; - } - - public String getChargingStateConstraint() { - return chargingStateConstraint; - } - - public void setChargingStateConstraint(String chargingStateConstraint) { - this.chargingStateConstraint = chargingStateConstraint; - } - - public String getDeviceIdleStateConstraint() { - return deviceIdleStateConstraint; - } - - public void setDeviceIdleStateConstraint(String deviceIdleStateConstraint) { - this.deviceIdleStateConstraint = deviceIdleStateConstraint; - } - - public String getNetworkTypeConstraint() { - return networkTypeConstraint; - } - - public void setNetworkTypeConstraint(String networkTypeConstraint) { - this.networkTypeConstraint = networkTypeConstraint; - } - - public String getMcmId() { - return mcmId; - } - - public void setMcmId(String mcmId) { - this.mcmId = mcmId; - } - - public List getVariableSet() { - return variableSet; - } - - public void setVariableSet(List variableSet) { - this.variableSet = variableSet; - } -} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseInstallPolicy.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseInstallPolicy.java deleted file mode 100644 index fe659659b..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseInstallPolicy.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; - -import java.io.Serializable; -import java.util.List; - -public class EnterpriseInstallPolicy implements Serializable { - private static final long serialVersionUID = 15598101712L; - - String username; - String managementType; - String kind; - String androidId; - String autoUpdatePolicy; - String productAvailabilityPolicy; - String productSetBehavior; - List apps; - - public String getProductSetBehavior() { - return productSetBehavior; - } - - public void setProductSetBehavior(String productSetBehavior) { - this.productSetBehavior = productSetBehavior; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getManagementType() { - return managementType; - } - - public void setManagementType(String managementType) { - this.managementType = managementType; - } - - public String getKind() { - return kind; - } - - public void setKind(String kind) { - this.kind = kind; - } - - public String getAndroidId() { - return androidId; - } - - public void setAndroidId(String androidId) { - this.androidId = androidId; - } - - public String getAutoUpdatePolicy() { - return autoUpdatePolicy; - } - - public void setAutoUpdatePolicy(String autoUpdatePolicy) { - this.autoUpdatePolicy = autoUpdatePolicy; - } - - public String getProductAvailabilityPolicy() { - return productAvailabilityPolicy; - } - - public void setProductAvailabilityPolicy(String productAvailabilityPolicy) { - this.productAvailabilityPolicy = productAvailabilityPolicy; - } - - public List getApps() { - return apps; - } - - public void setApps(List apps) { - this.apps = apps; - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseUser.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseUser.java deleted file mode 100644 index ff9bc4b38..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/EnterpriseUser.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; - -public class EnterpriseUser { - - String token; - String emmDeviceIdentifier; - String androidPlayDeviceId; - - public String getEmmDeviceIdentifier() { - return emmDeviceIdentifier; - } - - public void setEmmDeviceIdentifier(String emmDeviceIdentifier) { - this.emmDeviceIdentifier = emmDeviceIdentifier; - } - - public String getAndroidPlayDeviceId() { - return androidPlayDeviceId; - } - - public void setAndroidPlayDeviceId(String androidPlayDeviceId) { - this.androidPlayDeviceId = androidPlayDeviceId; - } - - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/GlobalProxyBeanWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/GlobalProxyBeanWrapper.java deleted file mode 100644 index 09c3bc0e3..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/GlobalProxyBeanWrapper.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.GlobalProxy; - -import java.util.List; - -/** - * This class is used to wrap the GlobalProxyPolicy bean with devices. - */ - -@ApiModel( - value = "GlobalProxyBeanWrapper", - description = "Mapping between global proxy settings and devices" -) -public class GlobalProxyBeanWrapper { - @ApiModelProperty( - name = "operation", - value = "Information of setting up global proxy", - required = true - ) - private GlobalProxy operation; - - @ApiModelProperty( - name = "deviceIDs", - value = "List of device Ids", - required = true) - private List deviceIDs; - - public GlobalProxy getOperation() { - return operation; - } - - public void setOperation(GlobalProxy operation) { - this.operation = operation; - } - - public List getDeviceIDs() { - return deviceIDs; - } - - public void setDeviceIDs(List deviceIDs) { - this.deviceIDs = deviceIDs; - } -} - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/TokenWrapper.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/TokenWrapper.java deleted file mode 100644 index 7bf731e18..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/bean/wrapper/TokenWrapper.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper; - -public class TokenWrapper { - - String token; - - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/AndroidDBConfigurations.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/AndroidDBConfigurations.java deleted file mode 100644 index 3938a1ba8..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/AndroidDBConfigurations.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.config.datasource; - - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "AndroidDBConfigurations") -public class AndroidDBConfigurations { - - private MobileDataSourceConfig DataSourceConfiguration; - @XmlElement(name = "DataSourceConfiguration") - public MobileDataSourceConfig getDataSourceConfiguration() { - return DataSourceConfiguration; - } - - public void setDataSourceConfiguration(MobileDataSourceConfig DataSourceConfiguration) { - this.DataSourceConfiguration = DataSourceConfiguration; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/AndroidEnterpriseManagedConfig.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/AndroidEnterpriseManagedConfig.java deleted file mode 100644 index 30e717dc7..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/AndroidEnterpriseManagedConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.dto; - -public class AndroidEnterpriseManagedConfig { - - String mcmId; - String profileName; - String packageName; - int tenantID; - String lastUpdatedTime; - int id; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getMcmId() { - return mcmId; - } - - public void setMcmId(String mcmId) { - this.mcmId = mcmId; - } - - public String getProfileName() { - return profileName; - } - - public void setProfileName(String profileName) { - this.profileName = profileName; - } - - public String getPackageName() { - return packageName; - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public int getTenantID() { - return tenantID; - } - - public void setTenantID(int tenantID) { - this.tenantID = tenantID; - } - - public String getLastUpdatedTime() { - return lastUpdatedTime; - } - - public void setLastUpdatedTime(String lastUpdatedTime) { - this.lastUpdatedTime = lastUpdatedTime; - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/AndroidEnterpriseUser.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/AndroidEnterpriseUser.java deleted file mode 100644 index afd64a12e..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/AndroidEnterpriseUser.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.dto; - -public class AndroidEnterpriseUser { - String emmUsername; - int tenantId; - String enterpriseId;//from configs - String googleUserId;// generated internally - String androidPlayDeviceId; //sent by device - String emmDeviceId; //set internally - String lastUpdatedTime; //set internally - - public String getLastUpdatedTime() { - return lastUpdatedTime; - } - - public void setLastUpdatedTime(String lastUpdatedTime) { - this.lastUpdatedTime = lastUpdatedTime; - } - - public String getEmmUsername() { - return emmUsername; - } - - public void setEmmUsername(String emmUsername) { - this.emmUsername = emmUsername; - } - - public int getTenantId() { - return tenantId; - } - - public void setTenantId(int tenantId) { - this.tenantId = tenantId; - } - - public String getEnterpriseId() { - return enterpriseId; - } - - public void setEnterpriseId(String enterpriseId) { - this.enterpriseId = enterpriseId; - } - - public String getGoogleUserId() { - return googleUserId; - } - - public void setGoogleUserId(String googleUserId) { - this.googleUserId = googleUserId; - } - - public String getAndroidPlayDeviceId() { - return androidPlayDeviceId; - } - - public void setAndroidPlayDeviceId(String androidPlayDeviceId) { - this.androidPlayDeviceId = androidPlayDeviceId; - } - - public String getEmmDeviceId() { - return emmDeviceId; - } - - public void setEmmDeviceId(String emmDeviceId) { - this.emmDeviceId = emmDeviceId; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/BadRequestException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/BadRequestException.java deleted file mode 100644 index 3ca97f7f6..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/BadRequestException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.exception; - -/** - * Represents the exception thrown during validating the request. - */ -public class BadRequestException extends AndroidDeviceMgtPluginException { - - public BadRequestException(String message, Throwable ex) { - super(message, ex); - } - - public BadRequestException(String message) { - super(message); - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/EnterpriseManagementDAOException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/EnterpriseManagementDAOException.java deleted file mode 100644 index 4b8c17276..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/EnterpriseManagementDAOException.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.exception; - -/** - * Custom exception class for enterprise specific data access related exceptions. - */ -public class EnterpriseManagementDAOException extends Exception { - - private String message; - private static final long serialVersionUID = 2021891702072938865L; - - /** - * Constructs a new EnterpriseManagementDAOException with the specified detail message and - * nested exception. - * - * @param message error message - * @param nestedException exception - */ - public EnterpriseManagementDAOException(String message, Exception nestedException) { - super(message, nestedException); - setErrorMessage(message); - } - - /** - * Constructs a new EnterpriseManagementDAOException with the specified detail message - * and cause. - * - * @param message the detail message. - * @param cause the cause of this exception. - */ - public EnterpriseManagementDAOException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - /** - * Constructs a new EnterpriseManagementDAOException with the specified detail message. - * - * @param message the detail message. - */ - public EnterpriseManagementDAOException(String message) { - super(message); - setErrorMessage(message); - } - - /** - * Constructs a new EnterpriseManagementDAOException with the specified and cause. - * - * @param cause the cause of this exception. - */ - public EnterpriseManagementDAOException(Throwable cause) { - super(cause); - } - - public String getMessage() { - return message; - } - - public void setErrorMessage(String errorMessage) { - this.message = errorMessage; - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/EnterpriseServiceException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/EnterpriseServiceException.java deleted file mode 100644 index 9153f5948..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/EnterpriseServiceException.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.exception; - -/** - * Custom exception class for enterprise specific data access related exceptions. - */ -public class EnterpriseServiceException extends Exception { - - private String message; - private static final long serialVersionUID = 2021891706072918865L; - - /** - * Constructs a new EnterpriseServiceException with the specified detail message and - * nested exception. - * - * @param message error message - * @param nestedException exception - */ - public EnterpriseServiceException(String message, Exception nestedException) { - super(message, nestedException); - setErrorMessage(message); - } - - /** - * Constructs a new EnterpriseServiceException with the specified detail message - * and cause. - * - * @param message the detail message. - * @param cause the cause of this exception. - */ - public EnterpriseServiceException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - /** - * Constructs a new EnterpriseServiceException with the specified detail message. - * - * @param message the detail message. - */ - public EnterpriseServiceException(String message) { - super(message); - setErrorMessage(message); - } - - /** - * Constructs a new EnterpriseServiceException with the specified and cause. - * - * @param cause the cause of this exception. - */ - public EnterpriseServiceException(Throwable cause) { - super(cause); - } - - public String getMessage() { - return message; - } - - public void setErrorMessage(String errorMessage) { - this.message = errorMessage; - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/NotFoundException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/NotFoundException.java deleted file mode 100644 index 0a9679f61..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/NotFoundException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.exception; - -/** - * Represents the exception thrown during validating the request. - */ -public class NotFoundException extends AndroidDeviceMgtPluginException { - - public NotFoundException(String message, Throwable ex) { - super(message, ex); - } - - public NotFoundException(String message) { - super(message); - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/UnexpectedServerErrorException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/UnexpectedServerErrorException.java deleted file mode 100644 index d6490f761..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/UnexpectedServerErrorException.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.wso2.carbon.device.mgt.mobile.android.common.exception; - -public class UnexpectedServerErrorException extends AndroidDeviceMgtPluginException{ - - public UnexpectedServerErrorException(String message, Throwable ex) { - super(message, ex); - } - - public UnexpectedServerErrorException(String message) { - super(message); - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/spi/AndroidGoogleEnterpriseService.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/spi/AndroidGoogleEnterpriseService.java deleted file mode 100644 index d964ab6bd..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/spi/AndroidGoogleEnterpriseService.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.spi; - -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseManagedConfig; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseServiceException; - -import java.util.List; - -public interface AndroidGoogleEnterpriseService { - - void addEnterpriseUser(AndroidEnterpriseUser androidEnterpriseUser) throws EnterpriseServiceException; - - List getEnterpriseUser(String username) throws EnterpriseServiceException; - - AndroidEnterpriseUser getEnterpriseUserByDevice(String deviceId) throws EnterpriseServiceException; - - AndroidEnterpriseManagedConfig getConfigByPackageName(String packageName) throws EnterpriseServiceException; - - void addConfig(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseServiceException; - - boolean updateMobileDevice(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseServiceException; - - boolean deleteMobileDevice(String id) throws EnterpriseServiceException; - - List getAllEnterpriseDevices(String enterpriseId) - throws EnterpriseServiceException ; -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/spi/AndroidService.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/spi/AndroidService.java deleted file mode 100644 index 013a70936..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/spi/AndroidService.java +++ /dev/null @@ -1,476 +0,0 @@ -/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.spi; - -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; - -import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; -import org.wso2.carbon.device.mgt.mobile.android.common.Message; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.AndroidPlatformConfiguration; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceState; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.*; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; - -import javax.ws.rs.core.Response; -import java.util.List; - -public interface AndroidService { - - /** - * Method to retrieve platform configurations - * - * @return {@link PlatformConfiguration} - * @throws {@link DeviceManagementException} If some unusual behaviour is observed while getting platform configurations - */ - PlatformConfiguration getPlatformConfig() throws DeviceManagementException; - - /** - * Method to update configurations - * - * @param androidPlatformConfiguration - * @throws {@link AndroidDeviceMgtPluginException} - */ - void updateConfiguration(AndroidPlatformConfiguration androidPlatformConfiguration) - throws AndroidDeviceMgtPluginException; - - /** - * Method for file transfer operation - * - * @param fileTransferBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} If some unusual behaviour is observed while executing file transfer operation - */ - Activity fileTransfer(FileTransferBeanWrapper fileTransferBeanWrapper) - throws AndroidDeviceMgtPluginException, OperationManagementException; - - /** - * Method for device lock operation - * - * @param deviceLockBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} If some unusual behaviour is observed while executing device lock operation - */ - Activity configureDeviceLock(DeviceLockBeanWrapper deviceLockBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for device unlock operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity configureDeviceUnlock(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for get device location operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity getDeviceLocation(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for remove password operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity removePassword(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for configure camera operation - * - * @param cameraBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity configureCamera(CameraBeanWrapper cameraBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method to get device information - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity getDeviceInformation(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method to get device logcat - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity getDeviceLogcat(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for wipe device operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity wipeDevice(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for wipe data operation - * - * @param wipeDataBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity wipeData(WipeDataBeanWrapper wipeDataBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for get applications operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity getApplications(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for ring device operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity ringDevice(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for reboot device operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity rebootDevice(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for change lock task operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity changeLockTask(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for mute device operation - * - * @param deviceIDs A list of device IDs - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity muteDevice(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for install application operation - * - * @param applicationInstallationBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity installApplication(ApplicationInstallationBeanWrapper applicationInstallationBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for update application operation - * - * @param applicationUpdateBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity updateApplication(ApplicationUpdateBeanWrapper applicationUpdateBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for uninstall application operation - * - * @param applicationUninstallationBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity uninstallApplication(ApplicationUninstallationBeanWrapper applicationUninstallationBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for blacklist application operation - * - * @param blacklistApplicationsBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity blacklistApplications(BlacklistApplicationsBeanWrapper blacklistApplicationsBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for upgrade firmware operation - * - * @param upgradeFirmwareBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity upgradeFirmware(UpgradeFirmwareBeanWrapper upgradeFirmwareBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for configure vpn operation - * - * @param vpnConfiguration - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity configureVPN(VpnBeanWrapper vpnConfiguration) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for send notification operation - * - * @param notificationBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity sendNotification(NotificationBeanWrapper notificationBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for configure wifi operation - * - * @param wifiBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity configureWifi(WifiBeanWrapper wifiBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for encypt storage operation - * - * @param encryptionBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity encryptStorage(EncryptionBeanWrapper encryptionBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for change lock code operation - * - * @param lockCodeBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity changeLockCode(LockCodeBeanWrapper lockCodeBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for set password policy operation - * - * @param passwordPolicyBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity setPasswordPolicy(PasswordPolicyBeanWrapper passwordPolicyBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for set webclip operation - * - * @param webClipBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity setWebClip(WebClipBeanWrapper webClipBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for set recommended global proxy operation - * - * @param globalProxyBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity setRecommendedGlobalProxy(GlobalProxyBeanWrapper globalProxyBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for send application configuration operation - * - * @param applicationRestrictionBeanWrapper - * @return - * @throws {@link AndroidDeviceMgtPluginException} - */ - ProfileOperation sendApplicationConfiguration( - ApplicationRestrictionBeanWrapper applicationRestrictionBeanWrapper) - throws AndroidDeviceMgtPluginException; - - /** - * method for configure display message operation - * - * @param displayMessageBeanWrapper - * @return {@link Activity} - * @throws {@link AndroidDeviceMgtPluginException} - * @throws {@link OperationManagementException} - */ - Activity configureDisplayMessage(DisplayMessageBeanWrapper displayMessageBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException; - - /** - * Method for update application list - * - * @param id Id of the device to update application list - * @param androidApplications List of AndroidApplication objects to update - * @return {@link Message} - * @throws {@link ApplicationManagementException} - */ - Message updateApplicationList(String id, List androidApplications) - throws ApplicationManagementException; - - /** - * Method for get pending operations - * - * @param deviceIdentifier Device Identifier of the device to get pending operations - * @param resultOperations Result operations list - * @return - * @throws {@link DeviceManagementException} - * @throws {@link InvalidDeviceException} - */ - List getPendingOperations - (DeviceIdentifier deviceIdentifier, List resultOperations) - throws DeviceManagementException, InvalidDeviceException, AndroidDeviceMgtPluginException; - - /** - * Method to enroll device - * - * @param androidDevice Instance of AndroidDevice to enroll - * @return {@link Response} - * @throws {@link DeviceManagementException} - */ - Message enrollDevice(AndroidDevice androidDevice) throws DeviceManagementException, AndroidDeviceMgtPluginException; - - /** - * Method to check if a device is enrolled - * - * @param id Id of the device to check - * @param deviceIdentifier Device Identifier of the device to check - * @return {@link Message} - * @throws {@link DeviceManagementException} - */ - Message isEnrolled(String id, DeviceIdentifier deviceIdentifier) throws DeviceManagementException; - - /** - * Method to modify enrollment - * - * @param id Id of the device to modify enrollement - * @param androidDevice AndroidDevice object of the device to modify enrollment - * @return - * @throws {@link DeviceManagementException} - * @throws {@link AndroidDeviceMgtPluginException} - */ - boolean modifyEnrollment(String id, AndroidDevice androidDevice) - throws DeviceManagementException, AndroidDeviceMgtPluginException; - - /** - * Method to disenroll a device - * - * @param id Id of the device to disenroll - * @return - * @throws {@link DeviceManagementException} - */ - boolean disEnrollDevice(String id) throws DeviceManagementException; - - /** - * Method to publish events - * - * @param eventBeanWrapper - * @return {@link Device} - * @throws {@link DeviceManagementException} - */ - Message publishEvents(EventBeanWrapper eventBeanWrapper) - throws DeviceManagementException, AndroidDeviceMgtPluginException; - - /** - * Method to retrieve alerts - * - * @param deviceId Id of the device to retrieve alerts - * @param from Start date to retrieve alerts - * @param to End date to retrieve alerts - * @param type Type to retrieve alerts - * @param ifModifiedSince - * @return {@link Response} - * @throws {@link AndroidDeviceMgtPluginException} - */ - List retrieveAlerts(String deviceId, long from, long to, String type, String ifModifiedSince) - throws AndroidDeviceMgtPluginException; -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/pom.xml deleted file mode 100644 index ebd48b603..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/pom.xml +++ /dev/null @@ -1,427 +0,0 @@ - - - - - - - android-plugin - org.wso2.carbon.devicemgt-plugins - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.carbon.device.mgt.mobile.android.core - bundle - WSO2 Carbon - Mobile Device Management Android Core Impl - WSO2 Carbon - Mobile Device Management Android Core Implementation - http://wso2.org - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - org.apache.felix - maven-scr-plugin - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - ${project.artifactId} - ${carbon.devicemgt.plugins.version} - Device Management Mobile Android Impl Bundle - org.wso2.carbon.device.mgt.mobile.android.core.internal - - org.osgi.framework, - org.osgi.service.component, - org.apache.commons.logging, - javax.xml, - javax.xml.stream, - javax.xml.bind.*, - javax.sql, - javax.xml.parsers; version=0.0.0, - org.w3c.dom, - javax.naming, - org.wso2.carbon.context, - org.wso2.carbon.utils.*, - org.wso2.carbon.device.mgt.mobile.android.common.*, - org.wso2.carbon.device.mgt.common.*, - org.wso2.carbon.device.mgt.core.*, - org.wso2.carbon.ndatasource.core, - org.wso2.carbon.policy.mgt.common.*, - org.wso2.carbon.policy.mgt.core, - org.wso2.carbon.registry.core, - org.wso2.carbon.registry.core.session, - org.wso2.carbon.registry.core.service, - org.wso2.carbon.registry.api, - org.wso2.carbon.device.mgt.extensions.license.mgt.registry, - org.wso2.carbon.apimgt.application.extension.*, - org.wso2.carbon.analytics.datasource.commons.*, - org.wso2.carbon.base, - org.wso2.carbon.analytics.api, - org.wso2.carbon.device.mgt.analytics.data.publisher.service, - com.google.gson.*, - org.wso2.carbon.device.application.mgt.common.*, - org.wso2.carbon.user.core.*, - org.wso2.carbon.user.api.*, - org.wso2.carbon.identity.jwt.client.extension.*, - org.apache.commons.httpclient, - org.apache.http, - org.apache.http.client.methods, - org.wso2.carbon.device.mgt.analytics.data.publisher.* - - - !org.wso2.carbon.device.mgt.mobile.android.core.internal, - org.wso2.carbon.device.mgt.mobile.android.core.* - - - - - - org.jacoco - jacoco-maven-plugin - - ${basedir}/target/coverage-reports/jacoco-unit.exec - - - - jacoco-initialize - - prepare-agent - - - - jacoco-site - test - - report - - - ${basedir}/target/coverage-reports/jacoco-unit.exec - ${basedir}/target/coverage-reports/site - - - - - - - - - - org.eclipse.osgi - org.eclipse.osgi - - - org.eclipse.osgi - org.eclipse.osgi.services - - - org.wso2.carbon - org.wso2.carbon.core - - - org.wso2.carbon - org.wso2.carbon.logging - - - org.wso2.carbon - org.wso2.carbon.utils - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.extensions - - - woodstox-core-asl - org.codehaus.woodstox - - - - - org.wso2.carbon - org.wso2.carbon.ndatasource.core - - - commons-logging - commons-logging - - - - - org.wso2.carbon - org.wso2.carbon.registry.api - - - org.wso2.carbon - org.wso2.carbon.registry.core - - - org.apache.tomcat.wso2 - jdbc-pool - - - com.google.code.gson - gson - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.common - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.application.mgt.common - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - - - org.slf4j - slf4j-api - - - axis2-client - org.apache.axis2.wso2 - - - axiom-api - org.apache.ws.commons.axiom - - - httpcore - org.apache.httpcomponents - - - commons-logging - commons-logging - - - - - org.wso2.carbon.devicemgt - org.wso2.carbon.policy.mgt.common - - - org.wso2.carbon.devicemgt - org.wso2.carbon.policy.mgt.core - - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.application.extension - - - commons-logging - commons-logging - - - slf4j-api - org.slf4j - - - geronimo-stax-api_1.0_spec - org.apache.geronimo.specs.wso2 - - - xml-apis - xml-apis - - - jackson-core - com.fasterxml.jackson.core - - - validation-api - javax.validation - - - jackson-mapper-asl - org.codehaus.jackson - - - axiom-api - org.apache.ws.commons.axiom - - - axiom-impl - org.apache.ws.commons.axiom - - - xercesImpl - xerces - - - commons-httpclient - commons-httpclient - - - jackson-databind - com.fasterxml.jackson.core - - - commons-beanutils - commons-beanutils - - - org.eclipse.core.runtime - org.eclipse.core - - - commons-pool - commons-pool - - - XmlSchema - org.apache.ws.commons.schema - - - tomcat - org.wso2.tomcat - - - guava - com.google.guava - - - codemodel - com.sun.codemodel - - - hibernate - org.hibernate - - - asm - asm - - - geronimo-jta_1.1_spec - org.apache.geronimo.specs - - - wstx-asl - org.codehaus.woodstox - - - wsdl4j - wsdl4j.wso2 - - - commons-fileupload - commons-fileupload - - - org.wso2.carbon.ntask.core - org.wso2.carbon.commons - - - org.wso2.securevault - org.wso2.securevault - - - maven-scm-provider-svnexe - org.apache.maven.scm - - - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - - - guava - com.google.guava - - - objenesis - org.objenesis - - - commons-logging - commons-logging - - - org.wso2.carbon.feature.mgt.core - org.wso2.carbon - - - - - org.wso2.carbon.devicemgt - org.wso2.carbon.apimgt.annotations - - - org.testng - testng - test - - - org.powermock - powermock-module-testng - test - - - objenesis - org.objenesis - - - - - org.powermock - powermock-api-mockito - test - - - com.h2database.wso2 - h2-database-engine - test - - - org.wso2.carbon - org.wso2.carbon.queuing - test - - - commons-dbcp.wso2 - commons-dbcp - test - - - commons-pool.wso2 - commons-pool - test - - - org.wso2.carbon - javax.cache.wso2 - test - - - javassist - javassist - test - - - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/MobileDeviceConfigFactory.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/MobileDeviceConfigFactory.java deleted file mode 100644 index b2250c3b0..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/MobileDeviceConfigFactory.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.device.mgt.mobile.android.core; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.mobile.android.common.config.datasource.AndroidDBConfigurations; -import org.wso2.carbon.utils.CarbonUtils; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; - -public class MobileDeviceConfigFactory { - - private static final Log log = LogFactory.getLog(MobileDeviceConfigFactory.class); - - public static final String ANDROID_DB_CONFIG_PATH = CarbonUtils.getCarbonConfigDirPath() + File.separator + - "/android-dbconfig.xml"; - public static AndroidDBConfigurations androidDBConfigurations; - - public static AndroidDBConfigurations getDataSourceConfigurations() { - return androidDBConfigurations; - } - - public static synchronized void init() throws DeviceManagementException { - try { - File mobileDeviceMgtConfig = new File(ANDROID_DB_CONFIG_PATH); - Document doc = convertToDocuments(mobileDeviceMgtConfig); - JAXBContext androidDeviceMgtContext = JAXBContext.newInstance(AndroidDBConfigurations.class); - Unmarshaller unmarshaller = androidDeviceMgtContext.createUnmarshaller(); - androidDBConfigurations = (AndroidDBConfigurations) unmarshaller.unmarshal(doc); - } catch (Exception e) { - String msg = "Error occurred while initializing Mobile Device Management config"; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - } - - public static Document convertToDocuments(File file) throws DeviceManagementException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - return docBuilder.parse(file); - } catch (Exception e) { - String msg = "Error occurred while parsing file, while converting " + - "to a org.w3c.dom.Document : " + e.getMessage(); - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/EnterpriseDAO.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/EnterpriseDAO.java deleted file mode 100644 index 931f184f8..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/EnterpriseDAO.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.dao; - -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseManagedConfig; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseManagementDAOException; - -import java.util.List; - -/** - * This class represents the key operations associated with working with Enterprise data - */ -public interface EnterpriseDAO { - - /** - * Add a new user to Enterprise. - * - * @param androidEnterpriseUser Enterprise user and device details. - * @return User addition status. - * @throws EnterpriseManagementDAOException - */ - boolean addUser(AndroidEnterpriseUser androidEnterpriseUser) throws EnterpriseManagementDAOException; - - List getUser(String username, int tenantId) throws EnterpriseManagementDAOException; - - AndroidEnterpriseUser getUserByDevice(String deviceId, int tenantId) throws EnterpriseManagementDAOException; - - AndroidEnterpriseManagedConfig getConfigByPackageName(String packageName, int tenantId) - throws EnterpriseManagementDAOException; - - boolean addConfig(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseManagementDAOException; - - boolean updateConfig(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseManagementDAOException; - - boolean deleteConfig(String id, int tenantId) throws EnterpriseManagementDAOException; - - List getAllEnterpriseDevices(int tenantId, String enterpriseId) throws - EnterpriseManagementDAOException; -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/impl/EnterpriseDAOImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/impl/EnterpriseDAOImpl.java deleted file mode 100644 index 4e4f47e03..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/impl/EnterpriseDAOImpl.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.dao.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseManagedConfig; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseManagementDAOException; -import org.wso2.carbon.device.mgt.mobile.android.core.dao.AndroidDAOFactory; -import org.wso2.carbon.device.mgt.mobile.android.core.dao.EnterpriseDAO; -import org.wso2.carbon.device.mgt.mobile.android.core.dao.util.MobileDeviceManagementDAOUtil; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * Implements EnterpriseDAO for Android Devices. - */ -public class EnterpriseDAOImpl implements EnterpriseDAO { - - private static final Log log = LogFactory.getLog(EnterpriseDAOImpl.class); - - public List getUser(String username, int tenantId) throws EnterpriseManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - List enterpriseUsers = new ArrayList<>(); - ResultSet rs = null; - try { - conn = AndroidDAOFactory.getConnection(); - String selectDBQuery = - "SELECT * FROM AD_ENTERPRISE_USER_DEVICE WHERE EMM_USERNAME = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(selectDBQuery); - stmt.setString(1, username); - stmt.setInt(2, tenantId); - - rs = stmt.executeQuery(); - - while (rs.next()) { - AndroidEnterpriseUser enterpriseUser = new AndroidEnterpriseUser(); - enterpriseUser.setEmmUsername(rs.getString("EMM_USERNAME")); - enterpriseUser.setTenantId(rs.getInt("TENANT_ID")); - enterpriseUser.setLastUpdatedTime(rs.getString("LAST_UPDATED_TIMESTAMP")); - enterpriseUser.setAndroidPlayDeviceId(rs.getString("ANDROID_PLAY_DEVICE_ID")); - enterpriseUser.setEnterpriseId(rs.getString("ENTERPRISE_ID")); - enterpriseUser.setGoogleUserId(rs.getString("GOOGLE_USER_ID")); - enterpriseUser.setEmmDeviceId(rs.getString("EMM_DEVICE_ID")); - enterpriseUsers.add(enterpriseUser); - } - } catch (SQLException e) { - String msg = "Error occurred while fetching user : '" + username + "'"; - log.error(msg, e); - throw new EnterpriseManagementDAOException(msg, e); - } finally { - MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); - AndroidDAOFactory.closeConnection(); - } - - return enterpriseUsers; - } - - public AndroidEnterpriseUser getUserByDevice(String deviceId, int tenantId) throws - EnterpriseManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - AndroidEnterpriseUser enterpriseUser = null; - ResultSet rs = null; - try { - conn = AndroidDAOFactory.getConnection(); - String selectDBQuery = - "SELECT * FROM AD_ENTERPRISE_USER_DEVICE WHERE EMM_DEVICE_ID = ? AND TENANT_ID = ? " + - "ORDER BY LAST_UPDATED_TIMESTAMP DESC"; - stmt = conn.prepareStatement(selectDBQuery); - stmt.setString(1, deviceId); - stmt.setInt(2, tenantId); - - rs = stmt.executeQuery(); - - if (rs.next()) { - enterpriseUser = new AndroidEnterpriseUser(); - enterpriseUser.setEmmUsername(rs.getString("EMM_USERNAME")); - enterpriseUser.setTenantId(rs.getInt("TENANT_ID")); - enterpriseUser.setLastUpdatedTime(rs.getString("LAST_UPDATED_TIMESTAMP")); - enterpriseUser.setAndroidPlayDeviceId(rs.getString("ANDROID_PLAY_DEVICE_ID")); - enterpriseUser.setEnterpriseId(rs.getString("ENTERPRISE_ID")); - enterpriseUser.setGoogleUserId(rs.getString("GOOGLE_USER_ID")); - enterpriseUser.setEmmDeviceId(rs.getString("EMM_DEVICE_ID")); - } - } catch (SQLException e) { - String msg = "Error occurred while fetching user for device : '" + deviceId + "'"; - log.error(msg, e); - throw new EnterpriseManagementDAOException(msg, e); - } finally { - MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); - AndroidDAOFactory.closeConnection(); - } - - return enterpriseUser; - } - - public boolean addUser(AndroidEnterpriseUser androidEnterpriseUser) throws EnterpriseManagementDAOException { - boolean status = false; - Connection conn; - PreparedStatement stmt = null; - try { - conn = AndroidDAOFactory.getConnection(); - String createDBQuery = - "INSERT INTO AD_ENTERPRISE_USER_DEVICE(EMM_USERNAME, TENANT_ID, LAST_UPDATED_TIMESTAMP" + - ", ANDROID_PLAY_DEVICE_ID, ENTERPRISE_ID, GOOGLE_USER_ID, EMM_DEVICE_ID)" - + " VALUES (?, ?, ?, ?, ?, ?, ?)"; - - stmt = conn.prepareStatement(createDBQuery); - stmt.setString(1, androidEnterpriseUser.getEmmUsername()); - stmt.setInt(2, androidEnterpriseUser.getTenantId()); - stmt.setTimestamp(3, new Timestamp(new Date().getTime())); - stmt.setString(4, androidEnterpriseUser.getAndroidPlayDeviceId()); - stmt.setString(5, androidEnterpriseUser.getEnterpriseId()); - stmt.setString(6, androidEnterpriseUser.getGoogleUserId()); - stmt.setString(7, androidEnterpriseUser.getEmmDeviceId()); - - int rows = stmt.executeUpdate(); - if (rows > 0) { - status = true; - if (log.isDebugEnabled()) { - log.debug("Added user " + androidEnterpriseUser.getEmmUsername()); - } - } - } catch (SQLException e) { - throw new EnterpriseManagementDAOException("Error occurred while adding the user " - + androidEnterpriseUser.getEmmUsername(), e); - } finally { - MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); - } - return status; - } - - public AndroidEnterpriseManagedConfig getConfigByPackageName(String packageName, int tenantId) - throws EnterpriseManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - AndroidEnterpriseManagedConfig managedConfig = null; - try { - conn = AndroidDAOFactory.getConnection(); - String selectDBQuery = - "SELECT * FROM AD_ENTERPRISE_MANAGED_CONFIGS WHERE PACKAGE_NAME = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(selectDBQuery); - stmt.setString(1, packageName); - stmt.setInt(2, tenantId); - - rs = stmt.executeQuery(); - - if (rs.next()) { - managedConfig = new AndroidEnterpriseManagedConfig(); - managedConfig.setId(rs.getInt("ID")); - managedConfig.setMcmId(rs.getString("MCM_ID")); - managedConfig.setProfileName(rs.getString("PROFILE_NAME")); - managedConfig.setPackageName(rs.getString("PACKAGE_NAME")); - managedConfig.setTenantID(rs.getInt("TENANT_ID")); - managedConfig.setLastUpdatedTime(rs.getString("LAST_UPDATED_TIMESTAMP")); - } - } catch (SQLException e) { - String msg = "Error occurred while fetching config for package name : '" + packageName + "'"; - log.error(msg, e); - throw new EnterpriseManagementDAOException(msg, e); - } finally { - MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); - AndroidDAOFactory.closeConnection(); - } - return managedConfig; - } - - public boolean addConfig(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseManagementDAOException { - boolean status = false; - Connection conn; - PreparedStatement stmt = null; - try { - conn = AndroidDAOFactory.getConnection(); - String createDBQuery = - "INSERT INTO AD_ENTERPRISE_MANAGED_CONFIGS(MCM_ID, PROFILE_NAME, PACKAGE_NAME" + - ", TENANT_ID, LAST_UPDATED_TIMESTAMP) VALUES (?, ?, ?, ?, ?)"; - - stmt = conn.prepareStatement(createDBQuery); - stmt.setString(1, managedConfig.getMcmId()); - stmt.setString(2, managedConfig.getProfileName()); - stmt.setString(3, managedConfig.getPackageName()); - stmt.setInt(4, managedConfig.getTenantID()); - stmt.setTimestamp(5, new Timestamp(new Date().getTime())); - - int rows = stmt.executeUpdate(); - if (rows > 0) { - status = true; - if (log.isDebugEnabled()) { - log.debug("Added config for package " + managedConfig.getPackageName()); - } - } - } catch (SQLException e) { - throw new EnterpriseManagementDAOException("Error occurred while adding the config for package " - + managedConfig.getPackageName(), e); - } finally { - MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); - } - return status; - } - - public boolean updateConfig(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseManagementDAOException { - boolean status = false; - Connection conn; - PreparedStatement stmt = null; - try { - conn = AndroidDAOFactory.getConnection(); - String updateDBQuery = - "UPDATE AD_ENTERPRISE_MANAGED_CONFIGS SET PROFILE_NAME = ?, LAST_UPDATED_TIMESTAMP = ?" + - " WHERE MCM_ID = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(updateDBQuery); - - stmt.setString(1, managedConfig.getProfileName()); - stmt.setString(2, managedConfig.getLastUpdatedTime()); - stmt.setString(3, managedConfig.getMcmId()); - stmt.setInt(4, managedConfig.getTenantID()); - int rows = stmt.executeUpdate(); - if (rows > 0) { - status = true; - if (log.isDebugEnabled()) { - log.debug("Managed config for mcm id " + managedConfig.getMcmId() + " data has been" + - " modified."); - } - } - } catch (SQLException e) { - String msg = "Error occurred while modifying the details for mcm id '" + - managedConfig.getMcmId() + "' data."; - log.error(msg, e); - throw new EnterpriseManagementDAOException(msg, e); - } finally { - MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); - } - return status; - } - - public boolean deleteConfig(String id, int tenantId) - throws EnterpriseManagementDAOException { - boolean status = false; - Connection conn; - PreparedStatement stmt = null; - try { - conn = AndroidDAOFactory.getConnection(); - String deleteDBQuery = - "DELETE FROM AD_ENTERPRISE_MANAGED_CONFIGS WHERE MCM_ID = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(deleteDBQuery); - stmt.setString(1, id); - stmt.setInt(2, tenantId); - int rows = stmt.executeUpdate(); - if (rows > 0) { - status = true; - if (log.isDebugEnabled()) { - log.debug("Error when deleting MCM ID " + id); - } - } - } catch (SQLException e) { - throw new EnterpriseManagementDAOException("Error occurred while deleting MCM ID '" + id + "'", e); - } finally { - MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); - } - return status; - } - - public List getAllEnterpriseDevices(int tenantId, String enterpriseId) - throws EnterpriseManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - List enterpriseUsers = new ArrayList<>(); - ResultSet rs = null; - try { - conn = AndroidDAOFactory.getConnection(); - String selectDBQuery = - "SELECT * FROM AD_ENTERPRISE_USER_DEVICE WHERE ENTERPRISE_ID = ? AND TENANT_ID = ?"; - stmt = conn.prepareStatement(selectDBQuery); - stmt.setString(1, enterpriseId); - stmt.setInt(2, tenantId); - - rs = stmt.executeQuery(); - - while (rs.next()) { - AndroidEnterpriseUser enterpriseUser = new AndroidEnterpriseUser(); - enterpriseUser.setEmmUsername(rs.getString("EMM_USERNAME")); - enterpriseUser.setTenantId(rs.getInt("TENANT_ID")); - enterpriseUser.setLastUpdatedTime(rs.getString("LAST_UPDATED_TIMESTAMP")); - enterpriseUser.setAndroidPlayDeviceId(rs.getString("ANDROID_PLAY_DEVICE_ID")); - enterpriseUser.setEnterpriseId(rs.getString("ENTERPRISE_ID")); - enterpriseUser.setGoogleUserId(rs.getString("GOOGLE_USER_ID")); - enterpriseUser.setEmmDeviceId(rs.getString("EMM_DEVICE_ID")); - enterpriseUsers.add(enterpriseUser); - } - } catch (SQLException e) { - String msg = "Error occurred while fetching user of enterprise: '" + enterpriseId + "'"; - log.error(msg, e); - throw new EnterpriseManagementDAOException(msg, e); - } finally { - MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); - AndroidDAOFactory.closeConnection(); - } - - return enterpriseUsers; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/AndroidGoogleEnterpriseServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/AndroidGoogleEnterpriseServiceImpl.java deleted file mode 100644 index c6e4a8da4..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/AndroidGoogleEnterpriseServiceImpl.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseManagedConfig; -import org.wso2.carbon.device.mgt.mobile.android.common.dto.AndroidEnterpriseUser; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseManagementDAOException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseServiceException; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService; -import org.wso2.carbon.device.mgt.mobile.android.core.dao.AndroidDAOFactory; -import org.wso2.carbon.device.mgt.mobile.android.core.dao.EnterpriseDAO; - -import java.util.List; - -/** - * This represents the Android implementation of DeviceManagerService. - */ -public class AndroidGoogleEnterpriseServiceImpl implements AndroidGoogleEnterpriseService { - - private static final Log log = LogFactory.getLog(AndroidGoogleEnterpriseServiceImpl.class); - private EnterpriseDAO enterpriseDAO; - - public AndroidGoogleEnterpriseServiceImpl() { - enterpriseDAO = AndroidDAOFactory.getEnterpriseDAO(); - } - - @Override - public void addEnterpriseUser(AndroidEnterpriseUser androidEnterpriseUser) throws EnterpriseServiceException { - if (log.isDebugEnabled()) { - log.debug("Calling add user service by device identifier: " + androidEnterpriseUser.getEmmDeviceId()); - } - try { - AndroidDAOFactory.beginTransaction(); - this.enterpriseDAO.addUser(androidEnterpriseUser); - AndroidDAOFactory.commitTransaction(); - } catch (EnterpriseManagementDAOException e) { - String msg = "Error occurred while adding the user " - + CarbonContext.getThreadLocalCarbonContext().getUsername(); - log.error(msg, e); - AndroidDAOFactory.rollbackTransaction(); - throw new EnterpriseServiceException(msg, e); - } finally { - AndroidDAOFactory.closeConnection(); - } - } - - @Override - public List getEnterpriseUser(String username) throws EnterpriseServiceException { - - List androidEnterpriseUsers; - if (log.isDebugEnabled()) { - log.debug("Calling get user service by device identifier: " + CarbonContext - .getThreadLocalCarbonContext().getUsername()); - } - try { - AndroidDAOFactory.openConnection(); - androidEnterpriseUsers = this.enterpriseDAO.getUser(username, CarbonContext.getThreadLocalCarbonContext() - .getTenantId()); - - } catch (EnterpriseManagementDAOException e) { - String msg = "Error occurred while adding the user " - + CarbonContext.getThreadLocalCarbonContext().getUsername(); - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } finally { - AndroidDAOFactory.closeConnection(); - } - return androidEnterpriseUsers; - } - - @Override - public AndroidEnterpriseUser getEnterpriseUserByDevice(String deviceId) throws EnterpriseServiceException { - - AndroidEnterpriseUser androidEnterpriseUsers; - if (log.isDebugEnabled()) { - log.debug("Calling get user service by device identifier: " + CarbonContext - .getThreadLocalCarbonContext().getUsername()); - } - try { - AndroidDAOFactory.openConnection(); - androidEnterpriseUsers = this.enterpriseDAO.getUserByDevice(deviceId, CarbonContext.getThreadLocalCarbonContext() - .getTenantId()); - - } catch (EnterpriseManagementDAOException e) { - String msg = "Error occurred while adding the user " - + CarbonContext.getThreadLocalCarbonContext().getUsername(); - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } finally { - AndroidDAOFactory.closeConnection(); - } - return androidEnterpriseUsers; - } - - @Override - public AndroidEnterpriseManagedConfig getConfigByPackageName(String packageName) throws EnterpriseServiceException { - AndroidEnterpriseManagedConfig enterpriseManagedConfig; - if (log.isDebugEnabled()) { - log.debug("Calling get user service by device identifier: " + CarbonContext - .getThreadLocalCarbonContext().getUsername()); - } - try { - AndroidDAOFactory.openConnection(); - enterpriseManagedConfig = this.enterpriseDAO.getConfigByPackageName(packageName, CarbonContext - .getThreadLocalCarbonContext().getTenantId()); - - } catch (EnterpriseManagementDAOException e) { - String msg = "Error occurred while getting configs for the package " + packageName; - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } finally { - AndroidDAOFactory.closeConnection(); - } - return enterpriseManagedConfig; - } - - @Override - public void addConfig(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseServiceException { - if (log.isDebugEnabled()) { - log.debug("Calling add managed config for package : " + managedConfig.getPackageName()); - } - - // Block from fetching other tenants data. - managedConfig.setTenantID(CarbonContext.getThreadLocalCarbonContext().getTenantId()); - try { - AndroidDAOFactory.beginTransaction(); - this.enterpriseDAO.addConfig(managedConfig); - AndroidDAOFactory.commitTransaction(); - } catch (EnterpriseManagementDAOException e) { - String msg = "Error occurred while adding managed configs for package " + managedConfig.getPackageName(); - log.error(msg, e); - AndroidDAOFactory.rollbackTransaction(); - throw new EnterpriseServiceException(msg, e); - } finally { - AndroidDAOFactory.closeConnection(); - } - } - - @Override - public boolean updateMobileDevice(AndroidEnterpriseManagedConfig managedConfig) throws EnterpriseServiceException { - boolean status; - if (log.isDebugEnabled()) { - log.debug("Calling update managed config for mcm id : " + managedConfig.getMcmId()); - } - - // Block from fetching other tenants data. - managedConfig.setTenantID(CarbonContext.getThreadLocalCarbonContext().getTenantId()); - try { - AndroidDAOFactory.beginTransaction(); - status = this.enterpriseDAO.updateConfig(managedConfig); - AndroidDAOFactory.commitTransaction(); - } catch (EnterpriseManagementDAOException e) { - String msg = "Error occurred while updating managed configs for mcm id " + managedConfig.getMcmId(); - log.error(msg, e); - AndroidDAOFactory.rollbackTransaction(); - throw new EnterpriseServiceException(msg, e); - } finally { - AndroidDAOFactory.closeConnection(); - } - return status; - } - - @Override - public boolean deleteMobileDevice(String id) throws EnterpriseServiceException { - boolean status; - if (log.isDebugEnabled()) { - log.debug("Calling update managed config for mcm id : " + id); - } - - try { - AndroidDAOFactory.beginTransaction(); - status = this.enterpriseDAO.deleteConfig(id,CarbonContext.getThreadLocalCarbonContext().getTenantId()); - AndroidDAOFactory.commitTransaction(); - } catch (EnterpriseManagementDAOException e) { - String msg = "Error occurred while updating managed configs for mcm id " + id; - log.error(msg, e); - AndroidDAOFactory.rollbackTransaction(); - throw new EnterpriseServiceException(msg, e); - } finally { - AndroidDAOFactory.closeConnection(); - } - return status; - } - - @Override - public List getAllEnterpriseDevices(String enterpriseId) - throws EnterpriseServiceException { - - List androidEnterpriseUsers; - if (log.isDebugEnabled()) { - log.debug("Calling get enterprise device service by enterprise identifier: " + enterpriseId); - } - try { - AndroidDAOFactory.openConnection(); - androidEnterpriseUsers = this.enterpriseDAO.getAllEnterpriseDevices(CarbonContext - .getThreadLocalCarbonContext() - .getTenantId(), enterpriseId); - - } catch (EnterpriseManagementDAOException e) { - String msg = "Error occurred while adding the user " - + CarbonContext.getThreadLocalCarbonContext().getUsername(); - log.error(msg, e); - throw new EnterpriseServiceException(msg, e); - } finally { - AndroidDAOFactory.closeConnection(); - } - return androidEnterpriseUsers; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/AndroidServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/AndroidServiceImpl.java deleted file mode 100644 index 2b661dced..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/AndroidServiceImpl.java +++ /dev/null @@ -1,1415 +0,0 @@ -/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.impl; - -import com.google.api.client.http.HttpStatusCodes; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; -import org.wso2.carbon.base.ServerConfiguration; - -import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.app.mgt.Application; -import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.license.mgt.License; -import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; -import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; -import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; -import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.Message; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.*; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.*; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.*; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; -import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder; -import org.wso2.carbon.device.mgt.mobile.android.core.util.MobileDeviceManagementUtil; -import org.wso2.carbon.policy.mgt.common.PolicyManagementException; -import org.wso2.carbon.policy.mgt.core.PolicyManagerService; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.List; - -import static com.hazelcast.aws.impl.Constants.DATE_FORMAT; - -public class AndroidServiceImpl implements AndroidService { - - private static final Log log = LogFactory.getLog(AndroidServiceImpl.class); - - private static final String OPERATION_ERROR_STATUS = "ERROR"; - private static final String EVENT_STREAM_DEFINITION = "org.wso2.iot.LocationStream"; - - private Gson gson = new Gson(); - private static final String LONGITUDE = "longitude"; - private static final String LATITUDE = "latitude"; - private static final String ALTITUDE = "altitude"; - private static final String SPEED = "speed"; - private static final String DISTANCE = "distance"; - private static final String BEARING = "bearing"; - private static final String TIME_STAMP = "timeStamp"; - private static final String LOCATION_EVENT_TYPE = "location"; - - @Override - public PlatformConfiguration getPlatformConfig() throws DeviceManagementException { - List configs; - PlatformConfiguration platformConfiguration; - - DeviceManagementProviderService deviceManagementProviderService = AndroidDeviceManagementDataHolder - .getInstance().getDeviceManagementProviderService(); - platformConfiguration = deviceManagementProviderService. - getConfiguration(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - if (platformConfiguration != null) { - configs = platformConfiguration.getConfiguration(); - } else { - platformConfiguration = new PlatformConfiguration(); - configs = new ArrayList<>(); - } - - if (configs != null) { - ConfigurationEntry versionEntry = new ConfigurationEntry(); - versionEntry.setContentType(AndroidConstants.TenantConfigProperties.CONTENT_TYPE_TEXT); - versionEntry.setName(AndroidConstants.TenantConfigProperties.SERVER_VERSION); - versionEntry.setValue(ServerConfiguration.getInstance().getFirstProperty("Version")); - configs.add(versionEntry); - - License license = deviceManagementProviderService - .getLicense(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, - AndroidConstants. - TenantConfigProperties.LANGUAGE_US); - if (license != null) { - ConfigurationEntry entry = new ConfigurationEntry(); - entry.setContentType(AndroidConstants.TenantConfigProperties.CONTENT_TYPE_TEXT); - entry.setName(AndroidConstants.TenantConfigProperties.LICENSE_KEY); - entry.setValue(license.getText()); - configs.add(entry); - } - platformConfiguration.setConfiguration(configs); - } - return platformConfiguration; - } - - @Override - public void updateConfiguration(AndroidPlatformConfiguration androidPlatformConfiguration) throws - AndroidDeviceMgtPluginException { - ConfigurationEntry licenseEntry = null; - PlatformConfiguration configuration = new PlatformConfiguration(); - if (androidPlatformConfiguration == null) { - String errorMessage = "The payload of the android platform configuration is null."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - configuration.setConfiguration(androidPlatformConfiguration.getConfiguration()); - try { - DeviceManagementProviderService deviceManagementProviderService = AndroidDeviceManagementDataHolder - .getInstance().getDeviceManagementProviderService(); - configuration.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - List configs = configuration.getConfiguration(); - NotifierFrequency notifierFrequency = new NotifierFrequency(); - for (ConfigurationEntry entry : configs) { - if (AndroidConstants.TenantConfigProperties.LICENSE_KEY.equals(entry.getName())) { - License license = new License(); - license.setName(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - license.setLanguage(AndroidConstants.TenantConfigProperties.LANGUAGE_US); - license.setVersion("1.0.0"); - license.setText(entry.getValue().toString()); - deviceManagementProviderService.addLicense(DeviceManagementConstants. - MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, license); - licenseEntry = entry; - } else if (AndroidConstants.TenantConfigProperties.NOTIFIER_FREQUENCY.equals(entry.getName())) { - if (entry.getValue() != null) { - notifierFrequency.setValue(Integer.parseInt(entry.getValue().toString())); - } else { - String msg = "No value specified for notifierFrequency."; - log.error(msg); - throw new BadRequestException(msg); - } - } else if (AndroidConstants.TenantConfigProperties.NOTIFIER_TYPE.equals(entry.getName())) { - if (entry.getValue() != null) { - notifierFrequency.setType(Integer.parseInt(entry.getValue().toString())); - } else { - String msg = "No value specified for notifierType."; - log.error(msg); - throw new BadRequestException(msg); - } - } - } - - if (licenseEntry != null) { - configs.remove(licenseEntry); - } - configuration.setConfiguration(configs); - deviceManagementProviderService.saveConfiguration(configuration); - notifyDevices(notifierFrequency); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting device management service to modify Android config settings"; - log.error(msg, e); - throw new AndroidDeviceMgtPluginException(msg, e); - } catch (NumberFormatException e) { - String msg = "Error occurred while reading notification frequency."; - log.error(msg, e); - throw new AndroidDeviceMgtPluginException(msg, e); - } catch (OperationManagementException e) { - String msg = "Error occurred while modifying configuration settings of Android platform."; - log.error(msg, e); - throw new AndroidDeviceMgtPluginException(msg, e); - } catch (InvalidDeviceException e) { - String msg = "Error occurred with the device."; - log.error(msg, e); - throw new AndroidDeviceMgtPluginException(msg, e); - } - } - - private void notifyDevices(NotifierFrequency notifierFrequency) throws DeviceManagementException, - OperationManagementException, InvalidDeviceException { - List deviceList = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .getAllDevices(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, false); - List deviceIdList = new ArrayList<>(); - for (Device device : deviceList) { - if (EnrolmentInfo.Status.REMOVED != device.getEnrolmentInfo().getStatus()) { - deviceIdList.add(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); - } - } - if (!deviceIdList.isEmpty()) { - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.NOTIFIER_FREQUENCY); - operation.setPayLoad(notifierFrequency.toJSON()); - operation.setEnabled(true); - AndroidDeviceManagementDataHolder - .getInstance().getDeviceManagementProviderService().addOperation( - DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, - operation, deviceIdList); - } - } - - @Override - public Message isEnrolled(String id, DeviceIdentifier deviceIdentifier) throws DeviceManagementException { - Device device = AndroidDeviceManagementDataHolder - .getInstance().getDeviceManagementProviderService().getDevice(deviceIdentifier); - if (device != null) { - String status = String.valueOf(device.getEnrolmentInfo().getStatus()); - Message responseMessage = new Message(); - responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_OK)); - responseMessage - .setResponseMessage("Status of android device that carries the id '" + id + "' is " + status); - return responseMessage; - } else { - Message responseMessage = new Message(); - responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_NOT_FOUND)); - responseMessage.setResponseMessage("No Android device is found upon the id '" + id + "'"); - return responseMessage; - } - } - - @Override - public Activity fileTransfer(FileTransferBeanWrapper fileTransferBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - if (fileTransferBeanWrapper == null || fileTransferBeanWrapper.getOperation() == null - || fileTransferBeanWrapper.getDeviceIDs() == null) { - String errorMessage = "The payload of the file transfer operation is incorrect."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - if (log.isDebugEnabled()) { - log.debug("Invoking Android file transfer operation for " + fileTransferBeanWrapper.getDeviceIDs()); - } - FileTransfer file = fileTransferBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - if (fileTransferBeanWrapper.isUpload()) { - operation.setCode(AndroidConstants.OperationCodes.FILE_DOWNLOAD); - } else { - operation.setCode(AndroidConstants.OperationCodes.FILE_UPLOAD); - } - operation.setType(Operation.Type.PROFILE); - operation.setEnabled(true); - operation.setPayLoad(file.toJSON()); - - try { - return MobileDeviceManagementUtil.getOperationResponse(fileTransferBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers ( " + fileTransferBeanWrapper.getDeviceIDs() + " ) found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity configureDeviceLock(DeviceLockBeanWrapper deviceLockBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - if (deviceLockBeanWrapper == null || deviceLockBeanWrapper.getOperation() == null) { - String errorMessage = "Lock bean is empty."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - DeviceLock lock = deviceLockBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.DEVICE_LOCK); - operation.setType(Operation.Type.PROFILE); - operation.setEnabled(true); - operation.setPayLoad(lock.toJSON()); - - try { - return MobileDeviceManagementUtil.getOperationResponse(deviceLockBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity configureDeviceUnlock(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.DEVICE_UNLOCK); - operation.setType(Operation.Type.COMMAND); - operation.setEnabled(true); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity getDeviceLocation(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.DEVICE_LOCATION); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity removePassword(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.CLEAR_PASSWORD); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity configureCamera(CameraBeanWrapper cameraBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (cameraBeanWrapper == null || cameraBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the configure camera operation is incorrect."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - Camera camera = cameraBeanWrapper.getOperation(); - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.CAMERA); - operation.setType(Operation.Type.COMMAND); - operation.setEnabled(camera.isEnabled()); - return MobileDeviceManagementUtil.getOperationResponse(cameraBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity getDeviceInformation(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.DEVICE_INFO); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity getDeviceLogcat(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.LOGCAT); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity wipeDevice(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.ENTERPRISE_WIPE); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity wipeData(WipeDataBeanWrapper wipeDataBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (wipeDataBeanWrapper == null || wipeDataBeanWrapper.getOperation() == null) { - String errorMessage = "WipeData bean is empty."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - WipeData wipeData = wipeDataBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.WIPE_DATA); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(wipeData.toJSON()); - return MobileDeviceManagementUtil.getOperationResponse(wipeDataBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity getApplications(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.APPLICATION_LIST); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity ringDevice(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.DEVICE_RING); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity rebootDevice(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.DEVICE_REBOOT); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity changeLockTask(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_TASK_MODE); - operation.setType(Operation.Type.COMMAND); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity muteDevice(List deviceIDs) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.DEVICE_MUTE); - operation.setType(Operation.Type.COMMAND); - operation.setEnabled(true); - return MobileDeviceManagementUtil.getOperationResponse(deviceIDs, operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity installApplication(ApplicationInstallationBeanWrapper applicationInstallationBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (applicationInstallationBeanWrapper == null || applicationInstallationBeanWrapper.getOperation() == - null) { - String errorMessage = "The payload of the application installing operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - - ApplicationInstallation applicationInstallation = applicationInstallationBeanWrapper.getOperation(); - validateApplicationUrl(applicationInstallation.getUrl()); - validateApplicationType(applicationInstallation.getType()); - validateScheduleDate(applicationInstallation.getSchedule()); - - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.INSTALL_APPLICATION); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(applicationInstallation.toJSON()); - return MobileDeviceManagementUtil - .getOperationResponse(applicationInstallationBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity updateApplication(ApplicationUpdateBeanWrapper applicationUpdateBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (applicationUpdateBeanWrapper == null || applicationUpdateBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the application update operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - ApplicationUpdate applicationUpdate = applicationUpdateBeanWrapper.getOperation(); - validateApplicationUrl(applicationUpdate.getUrl()); - validateApplicationType(applicationUpdate.getType()); - validateScheduleDate(applicationUpdate.getSchedule()); - - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.UPDATE_APPLICATION); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(applicationUpdate.toJSON()); - - return MobileDeviceManagementUtil - .getOperationResponse(applicationUpdateBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity uninstallApplication(ApplicationUninstallationBeanWrapper applicationUninstallationBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (applicationUninstallationBeanWrapper == null || - applicationUninstallationBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the application uninstalling operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - ApplicationUninstallation applicationUninstallation = applicationUninstallationBeanWrapper.getOperation(); - validateApplicationType(applicationUninstallation.getType()); - - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.UNINSTALL_APPLICATION); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(applicationUninstallation.toJSON()); - return MobileDeviceManagementUtil - .getOperationResponse(applicationUninstallationBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity blacklistApplications(BlacklistApplicationsBeanWrapper blacklistApplicationsBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (blacklistApplicationsBeanWrapper == null || blacklistApplicationsBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the blacklisting apps operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - BlacklistApplications blacklistApplications = blacklistApplicationsBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.BLACKLIST_APPLICATIONS); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(blacklistApplications.toJSON()); - return MobileDeviceManagementUtil - .getOperationResponse(blacklistApplicationsBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity upgradeFirmware(UpgradeFirmwareBeanWrapper upgradeFirmwareBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (upgradeFirmwareBeanWrapper == null || upgradeFirmwareBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the upgrade firmware operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - UpgradeFirmware upgradeFirmware = upgradeFirmwareBeanWrapper.getOperation(); - validateScheduleDate(upgradeFirmware.getSchedule()); - - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.UPGRADE_FIRMWARE); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(upgradeFirmware.toJSON()); - return MobileDeviceManagementUtil - .getOperationResponse(upgradeFirmwareBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity configureVPN(VpnBeanWrapper vpnConfiguration) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (vpnConfiguration == null || vpnConfiguration.getOperation() == null) { - String errorMessage = "The payload of the VPN operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - Vpn vpn = vpnConfiguration.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.VPN); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(vpn.toJSON()); - return MobileDeviceManagementUtil.getOperationResponse(vpnConfiguration.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity sendNotification(NotificationBeanWrapper notificationBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (notificationBeanWrapper == null || notificationBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the notification operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - Notification notification = notificationBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.NOTIFICATION); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(notification.toJSON()); - return MobileDeviceManagementUtil.getOperationResponse(notificationBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity configureWifi(WifiBeanWrapper wifiBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (wifiBeanWrapper == null || wifiBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the wifi operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - Wifi wifi = wifiBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.WIFI); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(wifi.toJSON()); - - return MobileDeviceManagementUtil.getOperationResponse(wifiBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity encryptStorage(EncryptionBeanWrapper encryptionBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (encryptionBeanWrapper == null || encryptionBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the device encryption operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - DeviceEncryption deviceEncryption = encryptionBeanWrapper.getOperation(); - CommandOperation operation = new CommandOperation(); - operation.setCode(AndroidConstants.OperationCodes.ENCRYPT_STORAGE); - operation.setType(Operation.Type.COMMAND); - operation.setEnabled(deviceEncryption.isEncrypted()); - return MobileDeviceManagementUtil.getOperationResponse(encryptionBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity changeLockCode(LockCodeBeanWrapper lockCodeBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (lockCodeBeanWrapper == null || lockCodeBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the change lock code operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - LockCode lockCode = lockCodeBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.CHANGE_LOCK_CODE); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(lockCode.toJSON()); - return MobileDeviceManagementUtil.getOperationResponse(lockCodeBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity setPasswordPolicy(PasswordPolicyBeanWrapper passwordPolicyBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (passwordPolicyBeanWrapper == null || passwordPolicyBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the change password policy operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - PasscodePolicy passcodePolicy = passwordPolicyBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.PASSCODE_POLICY); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(passcodePolicy.toJSON()); - - return MobileDeviceManagementUtil - .getOperationResponse(passwordPolicyBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity setWebClip(WebClipBeanWrapper webClipBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - - if (webClipBeanWrapper == null || webClipBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the add webclip operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - WebClip webClip = webClipBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.WEBCLIP); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(webClip.toJSON()); - - return MobileDeviceManagementUtil.getOperationResponse(webClipBeanWrapper.getDeviceIDs(), operation); - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public Activity setRecommendedGlobalProxy(GlobalProxyBeanWrapper globalProxyBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (globalProxyBeanWrapper == null || globalProxyBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the global proxy operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - - GlobalProxy globalProxy = globalProxyBeanWrapper.getOperation(); - if (globalProxy.validateRequest()) { - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.GLOBAL_PROXY); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(globalProxy.toJSON()); - - return MobileDeviceManagementUtil - .getOperationResponse(globalProxyBeanWrapper.getDeviceIDs(), operation); - } else { - String errorMessage = "The payload of the global proxy operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - @Override - public ProfileOperation sendApplicationConfiguration(ApplicationRestrictionBeanWrapper applicationRestrictionBeanWrapper) - throws AndroidDeviceMgtPluginException { - try { - if (applicationRestrictionBeanWrapper == null || applicationRestrictionBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the application configuration operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - ApplicationRestriction applicationRestriction = applicationRestrictionBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.REMOTE_APP_CONFIG); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(applicationRestriction.toJSON()); - return operation; - } catch (BadRequestException e) { - String errorMessage = "Issue in retrieving device management service instance"; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - - @Override - public Activity configureDisplayMessage(DisplayMessageBeanWrapper displayMessageBeanWrapper) - throws OperationManagementException, AndroidDeviceMgtPluginException { - try { - if (displayMessageBeanWrapper == null || displayMessageBeanWrapper.getOperation() == null) { - String errorMessage = "The payload of the display message operation is incorrect"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - DisplayMessage configureDisplayMessage = displayMessageBeanWrapper.getOperation(); - ProfileOperation operation = new ProfileOperation(); - operation.setCode(AndroidConstants.OperationCodes.DISPLAY_MESSAGE_CONFIGURATION); - operation.setType(Operation.Type.PROFILE); - operation.setPayLoad(configureDisplayMessage.toJSON()); - - return MobileDeviceManagementUtil.getOperationResponse(displayMessageBeanWrapper. - getDeviceIDs(), operation); - - } catch (InvalidDeviceException e) { - String errorMessage = "Invalid Device Identifiers found."; - log.error(errorMessage, e); - throw new BadRequestException(errorMessage, e); - } - } - - - @Override - public Message updateApplicationList(String id, List androidApplications) - throws org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException { - Application application; - List applications = new ArrayList<>(); - for (AndroidApplication androidApplication : androidApplications) { - application = new Application(); - application.setPlatform(androidApplication.getPlatform()); - application.setCategory(androidApplication.getCategory()); - application.setName(androidApplication.getName()); - application.setLocationUrl(androidApplication.getLocationUrl()); - application.setImageUrl(androidApplication.getImageUrl()); - application.setVersion(androidApplication.getVersion()); - application.setType(androidApplication.getType()); - application.setAppProperties(androidApplication.getAppProperties()); - application.setApplicationIdentifier(androidApplication.getApplicationIdentifier()); - application.setMemoryUsage(androidApplication.getMemoryUsage()); - applications.add(application); - } - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(id); - deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - - AndroidDeviceManagementDataHolder.getInstance().getApplicationManagementProviderService() - .updateApplicationListInstalledInDevice(deviceIdentifier, applications); - Message responseMessage = new Message(); - responseMessage.setResponseMessage("Device information has modified successfully."); - return responseMessage; - } - - @Override - public List getPendingOperations(DeviceIdentifier deviceIdentifier, - List resultOperations) - throws DeviceManagementException, InvalidDeviceException { - Device device; - try { - device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .getDevice(deviceIdentifier, false); - if (!MobileDeviceManagementUtil.isValidDeviceIdentifier(device)) { - String msg = "Device not found for identifier '" + deviceIdentifier.getId() + "'"; - log.error(msg); - throw new InvalidDeviceException(msg); - } - if (log.isDebugEnabled()) { - log.debug("Invoking Android pending operations:" + deviceIdentifier.getId()); - } - if (resultOperations != null && !resultOperations.isEmpty()) { - updateOperations(device, resultOperations); - } - } catch (OperationManagementException e) { - String msg = "Issue in retrieving operation management service instance"; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } catch (PolicyComplianceException e) { - String msg = "Issue in updating Monitoring operation"; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } catch (NotificationManagementException e) { - String msg = "Issue in retrieving Notification management service instance"; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } catch (org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException e) { - String msg = "Issue in retrieving application management service instance"; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - try { - return MobileDeviceManagementUtil.getPendingOperations(device, deviceIdentifier); - } catch (OperationManagementException e) { - String msg = "Issue in retrieving operation management service instance"; - log.error(msg, e); - throw new UnexpectedServerErrorException(msg, e); - } - } - - private void updateOperations(Device device, List operations) - throws OperationManagementException, PolicyComplianceException, NotificationManagementException, - org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException { - for (org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation : operations) { - MobileDeviceManagementUtil.updateOperation(device, operation); - if (OPERATION_ERROR_STATUS.equals(operation.getStatus().toString())) { - org.wso2.carbon.device.mgt.common.notification.mgt.Notification notification = new - org.wso2.carbon.device.mgt.common.notification.mgt.Notification(); - DeviceIdentifier id = new DeviceIdentifier(); - id.setId(device.getDeviceIdentifier()); - id.setType(AndroidConstants.DEVICE_TYPE_ANDROID); - notification.setOperationId(operation.getId()); - notification.setStatus(org.wso2.carbon.device.mgt.common.notification.mgt.Notification. - Status.NEW.toString()); - notification.setDescription(operation.getCode() + " operation failed to execute on device " + - device.getName() + " (ID: " + device.getDeviceIdentifier() + ")"); - AndroidDeviceManagementDataHolder.getInstance().getNotificationManagementService() - .addNotification(id, notification); - } - if (log.isDebugEnabled()) { - log.debug("Updating operation '" + operation.toString() + "'"); - } - } - } - - @Override - public Message enrollDevice(AndroidDevice androidDevice) - throws DeviceManagementException { - try { - Device device = new Device(); - device.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - device.setEnrolmentInfo(androidDevice.getEnrolmentInfo()); - device.getEnrolmentInfo().setOwner(MobileDeviceManagementUtil.getAuthenticatedUser()); - device.setDeviceInfo(androidDevice.getDeviceInfo()); - device.setDeviceIdentifier(androidDevice.getDeviceIdentifier()); - device.setDescription(androidDevice.getDescription()); - device.setName(androidDevice.getName()); - device.setFeatures(androidDevice.getFeatures()); - device.setProperties(androidDevice.getProperties()); - - boolean status = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .enrollDevice(device); - if (status) { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(androidDevice.getDeviceIdentifier(), - device.getType()); - - //Immediately update location information from initial payload - DeviceLocation deviceLocation = extractLocation(deviceIdentifier, androidDevice.getProperties()); - if (deviceLocation != null) { - try { - DeviceInformationManager informationManager = AndroidDeviceManagementDataHolder.getInstance() - .getDeviceInformationManager(); - informationManager.addDeviceLocation(deviceLocation); - } catch (DeviceDetailsMgtException e) { - String msg = "Error occurred while updating the device location upon android " + - "', which carries the id '" + androidDevice.getDeviceIdentifier() + "'"; - log.error(msg, e); - throw new UnexpectedServerErrorException(msg, e); - } - } - - //Adding Tasks to get device information - List deviceIdentifiers = new ArrayList<>(); - deviceIdentifiers.add(deviceIdentifier); - - List taskOperaions = new ArrayList<>(); - taskOperaions.add(AndroidConstants.OperationCodes.APPLICATION_LIST); - taskOperaions.add(AndroidConstants.OperationCodes.DEVICE_INFO); - taskOperaions.add(AndroidConstants.OperationCodes.DEVICE_LOCATION); - - for (String str : taskOperaions) { - CommandOperation operation = new CommandOperation(); - operation.setEnabled(true); - operation.setType(Operation.Type.COMMAND); - operation.setCode(str); - AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .addOperation(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, - operation, deviceIdentifiers); - } - PolicyManagerService policyManagerService = AndroidDeviceManagementDataHolder.getInstance() - .getPolicyManagerService(); - Policy effectivePolicy = policyManagerService. - getEffectivePolicy(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType())); - - if (effectivePolicy != null) { - List effectiveProfileFeatures = effectivePolicy.getProfile(). - getProfileFeaturesList(); - for (ProfileFeature feature : effectiveProfileFeatures) { - if (AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_FEATURE_CODE - .equals(feature.getFeatureCode())) { - MobileDeviceManagementUtil.installEnrollmentApplications(feature, deviceIdentifier); - break; - } - } - } - - Message responseMessage = new Message(); - responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_OK)); - responseMessage.setResponseMessage("Android device, which carries the id '" + - androidDevice.getDeviceIdentifier() + "' has successfully been enrolled"); - return responseMessage; - } else { - String msg = "Failed to enroll '" + device.getType() + "' device, which carries the id '" + - androidDevice.getDeviceIdentifier() + "'"; - log.error(msg); - throw new DeviceManagementException(msg); - } - } catch (PolicyManagementException | InvalidDeviceException | OperationManagementException e) { - String msg = "Error occurred while enforcing default enrollment policy upon android " + - "', which carries the id '" + - androidDevice.getDeviceIdentifier() + "'"; - log.error(msg, e); - throw new UnexpectedServerErrorException(msg, e); - } - } - - @Override - public boolean modifyEnrollment(String id, AndroidDevice androidDevice) - throws DeviceManagementException { - Device device; - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(id); - deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); - try { - device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .getDevice(deviceIdentifier); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting enrollment details of the Android device that carries the id '" + - id + "'"; - log.error(msg, e); - throw new UnexpectedServerErrorException(msg, e); - } - - if (androidDevice == null) { - String errorMessage = "The payload of the android device enrollment is incorrect."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - if (device == null) { - String errorMessage = "The device to be modified doesn't exist."; - log.error(errorMessage); - throw new NotFoundException(errorMessage); - } - if (androidDevice.getEnrolmentInfo() != null) { - device.setEnrolmentInfo(device.getEnrolmentInfo()); - } - device.getEnrolmentInfo().setOwner(MobileDeviceManagementUtil.getAuthenticatedUser()); - if (androidDevice.getDeviceInfo() != null) { - device.setDeviceInfo(androidDevice.getDeviceInfo()); - } - device.setDeviceIdentifier(androidDevice.getDeviceIdentifier()); - if (androidDevice.getDescription() != null) { - device.setDescription(androidDevice.getDescription()); - } - if (androidDevice.getName() != null) { - device.setName(androidDevice.getName()); - } - if (androidDevice.getFeatures() != null) { - device.setFeatures(androidDevice.getFeatures()); - } - if (androidDevice.getProperties() != null) { - device.setProperties(androidDevice.getProperties()); - } - return AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .modifyEnrollment(device); - } - - @Override - public boolean disEnrollDevice(String id) throws DeviceManagementException { - DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(id); - Device device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .getDevice(deviceIdentifier, false); - MobileDeviceManagementUtil.updateDisEnrollOperationStatus(device); - return AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .disenrollDevice(deviceIdentifier); - } - - @Override - public Message publishEvents(EventBeanWrapper eventBeanWrapper) throws AndroidDeviceMgtPluginException { - if (log.isDebugEnabled()) { - log.debug("Invoking Android device event logging."); - } - Device device; - try { - if (!DeviceManagerUtil.isPublishLocationResponseEnabled()) { - Message responseMessage = new Message(); - responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_ACCEPTED)); - responseMessage.setResponseMessage("Event is publishing has not enabled."); - return responseMessage; - } - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(eventBeanWrapper.getDeviceIdentifier(), - AndroidConstants.DEVICE_TYPE_ANDROID); - device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .getDevice(deviceIdentifier); - if (device != null && EnrolmentInfo.Status.ACTIVE != device.getEnrolmentInfo().getStatus()) { - Message responseMessage = new Message(); - responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_ACCEPTED)); - responseMessage.setResponseMessage("Device is not in Active state."); - return responseMessage; - } else if (device == null) { - Message responseMessage = new Message(); - responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_ACCEPTED)); - responseMessage.setResponseMessage("Device is not enrolled yet."); - return responseMessage; - } - } catch (DeviceManagementException e) { - log.error("Error occurred while checking Operation Analytics is Enabled.", e); - Message responseMessage = new Message(); - responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_SERVER_ERROR)); - responseMessage.setResponseMessage(e.getMessage()); - return responseMessage; - } - String eventType = eventBeanWrapper.getType(); - if (!LOCATION_EVENT_TYPE.equals(eventType)) { - String msg = "Dropping Android " + eventType + " Event.Only Location Event Type is supported."; - log.warn(msg); - Message responseMessage = new Message(); - responseMessage.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_BAD_REQUEST)); - responseMessage.setResponseMessage(msg); - return responseMessage; - } - Message message = new Message(); - Object[] metaData = {eventBeanWrapper.getDeviceIdentifier(), device.getEnrolmentInfo().getOwner(), - AndroidConstants.DEVICE_TYPE_ANDROID}; - String eventPayload = eventBeanWrapper.getPayload(); - JsonObject jsonObject = gson.fromJson(eventPayload, JsonObject.class); - Object[] payload = { - jsonObject.get(TIME_STAMP).getAsLong(), - jsonObject.get(LATITUDE).getAsDouble(), - jsonObject.get(LONGITUDE).getAsDouble(), - jsonObject.get(ALTITUDE).getAsDouble(), - jsonObject.get(SPEED).getAsFloat(), - jsonObject.get(BEARING).getAsFloat(), - jsonObject.get(DISTANCE).getAsDouble() - }; - try { - if (AndroidDeviceManagementDataHolder.getInstance().getEventsPublisherService().publishEvent( - EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload)) { - message.setResponseCode("Event is published successfully."); - return message; - } else { - log.warn("Error occurred while trying to publish the event. This could be due to unavailability " + - "of the publishing service. Please make sure that analytics server is running and accessible " + - "by this server"); - String errorMessage = "Error occurred due to " + - "unavailability of the publishing service."; - message.setResponseCode(String.valueOf(HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE)); - return message; - } - } catch (DataPublisherConfigurationException e) { - String msg = "Error occurred while getting the Data publisher Service instance."; - log.error(msg, e); - throw new UnexpectedServerErrorException(msg); - } - - } - - @Override - public List retrieveAlerts(String deviceId, - long from, - long to, - String type, - String ifModifiedSince) throws AndroidDeviceMgtPluginException { - if (from != 0l && to != 0l && deviceId != null) { - return retrieveAlertFromDate(deviceId, from, to); - } else if (deviceId != null && type != null) { - return retrieveAlertByType(deviceId, type); - } else if (deviceId != null) { - return retrieveAlert(deviceId); - } else { - String errorMessage = "Request must contain " + - "the device identifier. Optionally, both from and to value should be present to get " + - "alerts between times."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - } - - private List retrieveAlert(String deviceId) throws NotFoundException, UnexpectedServerErrorException { - if (log.isDebugEnabled()) { - log.debug("Retrieving events for given device Identifier."); - } - String query = "deviceIdentifier:" + deviceId; - List deviceStates; - try { - deviceStates = MobileDeviceManagementUtil.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); - if (deviceStates == null) { - String errorMessage = "No any alerts are " + - "published for Device: " + deviceId + "."; - throw new NotFoundException(errorMessage); - } else { - return deviceStates; - } - } catch (AnalyticsException e) { - String msg = "Error occurred while getting published events for specific device: " + deviceId + "."; - log.error(msg, e); - throw new UnexpectedServerErrorException(msg, e); - } - } - - private List retrieveAlertFromDate(String deviceId, long from, long to) throws NotFoundException, - UnexpectedServerErrorException { - String fromDate = String.valueOf(from); - String toDate = String.valueOf(to); - if (log.isDebugEnabled()) { - log.debug("Retrieving events for given device Identifier and time period."); - } - - String query = "deviceIdentifier:" + deviceId + " AND _timestamp: [" + fromDate + " TO " + toDate + "]"; - List deviceStates; - try { - deviceStates = MobileDeviceManagementUtil.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); - if (deviceStates == null) { - String errorMessage = "No any alerts are " + - "published on given date for given Device: " + deviceId + "."; - throw new NotFoundException(errorMessage); - - } else { - return deviceStates; - } - } catch (AnalyticsException e) { - String msg = "Error occurred while getting published events for specific " + - "Device: " + deviceId + " on given Date."; - log.error(msg, e); - throw new UnexpectedServerErrorException(msg, e); - } - } - - private List retrieveAlertByType(String deviceId, String type) - throws NotFoundException, UnexpectedServerErrorException { - if (log.isDebugEnabled()) { - log.debug("Retrieving events for given device identifier and type."); - } - String query = "deviceIdentifier:" + deviceId + " AND type:" + type; - List deviceStates; - try { - deviceStates = MobileDeviceManagementUtil.getAllEventsForDevice(EVENT_STREAM_DEFINITION, query); - if (deviceStates == null) { - String errorMessage = "No any alerts are " + - "published for given Device: '" + deviceId + "' and given specific Type."; - throw new NotFoundException(errorMessage); - - } else { - return deviceStates; - } - } catch (AnalyticsException e) { - String msg = "Error occurred while getting published events for specific " + - "Device: " + deviceId + "and given specific Type."; - log.error(msg, e); - throw new UnexpectedServerErrorException(msg, e); - } - } - - /** - * Extracts the device location - * - * @param deviceIdentifier - * @param properties - * @return returns null when location not found - */ - private DeviceLocation extractLocation(DeviceIdentifier deviceIdentifier, List properties) - throws DeviceManagementException { - - DeviceLocation location = null; - String latitude = "", longitude = "", altitude = "", speed = "", bearing = "", distance = ""; - - if (properties == null) return null; - - for (Device.Property property : properties) { - String propertyName = property.getName(); - if (propertyName == null) continue; - if (propertyName.equals("LATITUDE")) { - latitude = property.getValue(); - } - if (propertyName.equals("LONGITUDE")) { - longitude = property.getValue(); - } - if (propertyName.equals("ALTITUDE")) { - altitude = property.getValue(); - } - if (propertyName.equals("SPEED")) { - speed = property.getValue(); - } - if (propertyName.equals("BEARING")) { - bearing = property.getValue(); - } - if (propertyName.equals("DISTANCE")) { - distance = property.getValue(); - } - } - - if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude) && - StringUtils.isNotBlank(altitude) && StringUtils.isNotBlank(speed) && - StringUtils.isNotBlank(bearing) && StringUtils.isNotBlank(distance)) { - location = new DeviceLocation(); - location.setLatitude(Double.valueOf(latitude)); - location.setLongitude(Double.valueOf(longitude)); - location.setAltitude(Double.parseDouble(altitude)); - location.setSpeed(Float.parseFloat(speed)); - location.setBearing(Float.parseFloat(bearing)); - location.setDistance(Double.parseDouble(distance)); - location.setDeviceIdentifier(deviceIdentifier); - Device savedDevice = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .getDevice(deviceIdentifier, false); - location.setDeviceId(savedDevice.getId()); - } - return location; - } - - private static void validateApplicationUrl(String apkUrl) throws BadRequestException { - try { - URL url = new URL(apkUrl); - URLConnection conn = url.openConnection(); - if (((HttpURLConnection) conn).getResponseCode() != HttpURLConnection.HTTP_OK) { - String errorMessage = "URL is not pointed to a downloadable file."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - } catch (MalformedURLException e) { - String errorMessage = "Malformed application url."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } catch (IOException e) { - String errorMessage = "Invalid application url."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - } - - private static void validateApplicationType(String type) throws BadRequestException { - if (type != null) { - if (!"enterprise".equalsIgnoreCase(type) - && !"public".equalsIgnoreCase(type) - && !"webapp".equalsIgnoreCase(type)) { - String errorMessage = "Invalid application type."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - } else { - String errorMessage = "Application type is missing."; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - } - - private static void validateScheduleDate(String dateString) throws BadRequestException { - try { - if (dateString != null && !dateString.isEmpty()) { - SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - sdf.setLenient(false); - sdf.parse(dateString); - } - } catch (ParseException e) { - String errorMessage = "Issue in validating the schedule date"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/DeviceTypeCommonServiceImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/DeviceTypeCommonServiceImpl.java deleted file mode 100644 index cc0afcb0c..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/impl/DeviceTypeCommonServiceImpl.java +++ /dev/null @@ -1,231 +0,0 @@ -/* Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.impl; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.AppRegistrationCredentials; -import org.wso2.carbon.device.mgt.common.ApplicationRegistrationException; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; -import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException; -import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService; -import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; -import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; -import org.wso2.carbon.device.mgt.core.config.keymanager.KeyManagerConfigurations; -import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; -import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder; -import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; -import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class DeviceTypeCommonServiceImpl implements DeviceTypeCommonService { - - private static final Log log = LogFactory.getLog(DeviceTypeCommonServiceImpl.class); - - @Override - public Map getEnrollmentQRCode(String ownershipType) throws DeviceManagementException { - AndroidService androidService = AndroidDeviceManagementDataHolder.getInstance().getAndroidService(); - PlatformConfiguration platformConfiguration = androidService.getPlatformConfig(); - - Map qrEnrollmentPayload = new HashMap<>(); - Map defaultQREnrollmentPayload = new HashMap<>(); - - if (Arrays.stream(EnrolmentInfo.OwnerShip.values()) - .noneMatch(ownerShip -> ownerShip.toString().equalsIgnoreCase(ownershipType))) { - String msg = "Request to get QR enrollment code for invalid device ownership type " + ownershipType; - log.error(msg); - throw new BadRequestException(msg); - } - - String accessToken = getAccessTokenToEnroll(); - if (StringUtils.isBlank(accessToken)) { - String msg = "Couldn't get a access token for user " + PrivilegedCarbonContext.getThreadLocalCarbonContext() - .getUsername(); - log.error(msg); - throw new DeviceManagementException(msg); - } - - for (ConfigurationEntry configEntry : platformConfiguration.getConfiguration()) { - if (AndroidConstants.PlatformConfigs.DefaultConfigs.SERVER_IP.equals(configEntry.getName())) { - defaultQREnrollmentPayload - .put(AndroidConstants.PlatformConfigs.DefaultConfigs.SERVER_IP, configEntry.getValue()); - } - - if (EnrolmentInfo.OwnerShip.COSU.toString().equalsIgnoreCase(ownershipType) || EnrolmentInfo.OwnerShip.COPE - .toString().equalsIgnoreCase(ownershipType)) { - if (AndroidConstants.PlatformConfigs.KioskConfigs.ADMIN_COMPONENT_NAME.equals(configEntry.getName())) { - qrEnrollmentPayload.put(AndroidConstants.PlatformConfigs.KioskConfigs.ADMIN_COMPONENT_NAME, - configEntry.getValue()); - } else if (AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_SSID.equals(configEntry.getName())) { - qrEnrollmentPayload - .put(AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_SSID, configEntry.getValue()); - } else if (AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_PASSWORD.equals(configEntry.getName())) { - qrEnrollmentPayload - .put(AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_PASSWORD, configEntry.getValue()); - } else if (AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_SECURITY.equals(configEntry.getName())) { - qrEnrollmentPayload - .put(AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_SECURITY, configEntry.getValue()); - } else if (AndroidConstants.PlatformConfigs.KioskConfigs.CHECKSUM.equals(configEntry.getName())) { - qrEnrollmentPayload - .put(AndroidConstants.PlatformConfigs.KioskConfigs.CHECKSUM, configEntry.getValue()); - } else if (AndroidConstants.PlatformConfigs.KioskConfigs.DOWNLOAD_URL.equals(configEntry.getName())) { - qrEnrollmentPayload - .put(AndroidConstants.PlatformConfigs.KioskConfigs.DOWNLOAD_URL, configEntry.getValue()); - } else if (AndroidConstants.PlatformConfigs.KioskConfigs.SKIP_ENCRYPTION - .equals(configEntry.getName())) { - qrEnrollmentPayload - .put(AndroidConstants.PlatformConfigs.KioskConfigs.SKIP_ENCRYPTION, configEntry.getValue()); - } - } - - } - - defaultQREnrollmentPayload - .put(AndroidConstants.PlatformConfigs.DefaultConfigs.DEFAULT_OWNERSHIP, ownershipType.toUpperCase()); - defaultQREnrollmentPayload.put(AndroidConstants.PlatformConfigs.DefaultConfigs.ACCESS_TOKEN, accessToken); - qrEnrollmentPayload - .put(AndroidConstants.PlatformConfigs.KioskConfigs.ANDROID_EXTRA, defaultQREnrollmentPayload); - validateQREnrollmentPayload(qrEnrollmentPayload, ownershipType); - return qrEnrollmentPayload; - } - - /** - * To get Access token for device enroll scope. - * - * @return Access token - * @throws DeviceManagementException if error occurred when trying to get access token for device enroll scope. - */ - private String getAccessTokenToEnroll() throws DeviceManagementException { - DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance() - .getDeviceManagementConfig(); - KeyManagerConfigurations kmConfig = deviceManagementConfig.getKeyManagerConfigurations(); - try { - AppRegistrationCredentials credentials = DeviceManagerUtil.getApplicationRegistrationCredentials( - System.getProperty( - org.wso2.carbon.device.mgt.core.DeviceManagementConstants.ConfigurationManagement.IOT_GATEWAY_HOST), - System.getProperty( - org.wso2.carbon.device.mgt.core.DeviceManagementConstants.ConfigurationManagement.IOT_GATEWAY_HTTPS_PORT), - kmConfig.getAdminUsername(), kmConfig.getAdminPassword()); - - AccessTokenInfo accessTokenForAdmin = DeviceManagerUtil - .getAccessTokenForDeviceOwner("perm:device:enroll", credentials.getClient_id(), - credentials.getClient_secret(), - PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername()); - return accessTokenForAdmin.getAccessToken(); - } catch (ApplicationRegistrationException e) { - String msg = "Error occurred while registering Application to get access token to create enrollment QR code " - + "payload."; - log.error(msg); - throw new DeviceManagementException(msg, e); - } catch (JWTClientException e) { - String msg = "JWT Error occurred while registering Application to get access token to create enrollment " - + "QR code payload."; - log.error(msg, e); - throw new DeviceManagementException(msg, e); - } - } - - /** - * Validate the QR enrollment payload - * - * @param payload Configs use to generate Enrollment QR code - * @param ownershipType Device enrollment type - */ - private void validateQREnrollmentPayload(Map payload, - String ownershipType) { - boolean isInvalidConfig = false; - String invalidPlatformConfigs = ""; - - if (payload.get(AndroidConstants.PlatformConfigs.KioskConfigs.ANDROID_EXTRA) == null) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.KioskConfigs.ANDROID_EXTRA + ", "; - isInvalidConfig = true; - } else { - Map defaultPayload = (Map) payload - .get(AndroidConstants.PlatformConfigs.KioskConfigs.ANDROID_EXTRA); - if (StringUtils.isBlank( - (String) defaultPayload.get(AndroidConstants.PlatformConfigs.DefaultConfigs.DEFAULT_OWNERSHIP))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.DefaultConfigs.DEFAULT_OWNERSHIP + ", "; - isInvalidConfig = true; - } - if (StringUtils - .isBlank((String) defaultPayload.get(AndroidConstants.PlatformConfigs.DefaultConfigs.SERVER_IP))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.DefaultConfigs.SERVER_IP + ", "; - isInvalidConfig = true; - } - if (StringUtils.isBlank( - (String) defaultPayload.get(AndroidConstants.PlatformConfigs.DefaultConfigs.ACCESS_TOKEN))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.DefaultConfigs.ACCESS_TOKEN + ", "; - isInvalidConfig = true; - } - } - - if (EnrolmentInfo.OwnerShip.COSU.toString().equalsIgnoreCase(ownershipType) || EnrolmentInfo.OwnerShip.COPE - .toString().equalsIgnoreCase(ownershipType)) { - if (StringUtils.isBlank( - (String) payload.get(AndroidConstants.PlatformConfigs.KioskConfigs.ADMIN_COMPONENT_NAME))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.KioskConfigs.ADMIN_COMPONENT_NAME + ", "; - isInvalidConfig = true; - } - if (StringUtils.isBlank((String) payload.get(AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_SSID))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_SSID + ", "; - isInvalidConfig = true; - } - if (StringUtils - .isBlank((String) payload.get(AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_PASSWORD))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_PASSWORD + ", "; - isInvalidConfig = true; - } - if (StringUtils - .isBlank((String) payload.get(AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_SECURITY))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.KioskConfigs.WIFI_SECURITY + ", "; - isInvalidConfig = true; - } - if (StringUtils.isBlank((String) payload.get(AndroidConstants.PlatformConfigs.KioskConfigs.CHECKSUM))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.KioskConfigs.CHECKSUM + ", "; - isInvalidConfig = true; - } - if (StringUtils.isBlank((String) payload.get(AndroidConstants.PlatformConfigs.KioskConfigs.DOWNLOAD_URL))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.KioskConfigs.DOWNLOAD_URL + ", "; - isInvalidConfig = true; - } - if (StringUtils - .isBlank((String) payload.get(AndroidConstants.PlatformConfigs.KioskConfigs.SKIP_ENCRYPTION))) { - invalidPlatformConfigs += AndroidConstants.PlatformConfigs.KioskConfigs.SKIP_ENCRYPTION + ", "; - isInvalidConfig = true; - } - } - - if (isInvalidConfig) { - String msg = "Android Platform Configuration is not configured properly. Platform configs [ " - + invalidPlatformConfigs + " ]"; - log.error(msg); - throw new InvalidConfigurationException(msg); - } - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/internal/AndroidDeviceManagementDataHolder.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/internal/AndroidDeviceManagementDataHolder.java deleted file mode 100644 index a6f72d3a6..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/internal/AndroidDeviceManagementDataHolder.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.internal; - -import org.wso2.carbon.analytics.api.AnalyticsDataAPI; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; -import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; -import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService; -import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; -import org.wso2.carbon.policy.mgt.core.PolicyManagerService; -import org.wso2.carbon.registry.core.service.RegistryService; - -/** - * DataHolder class of Mobile plugins component. - */ -public class AndroidDeviceManagementDataHolder { - - private RegistryService registryService; - private AndroidGoogleEnterpriseService androidDeviceManagementService; - private DeviceManagementProviderService deviceManagementProviderService; - private ApplicationManagementProviderService applicationManagementProviderService; - private NotificationManagementService notificationManagementService; - private DeviceInformationManager deviceInformationManager; - private PolicyManagerService policyManagerService; - private AnalyticsDataAPI analyticsDataAPI; - private EventsPublisherService eventsPublisherService; - private AndroidService androidService; - - private DeviceTypeCommonService deviceTypeCommonService; - - private static AndroidDeviceManagementDataHolder thisInstance = new AndroidDeviceManagementDataHolder(); - - private AndroidDeviceManagementDataHolder() { - } - - public static AndroidDeviceManagementDataHolder getInstance() { - return thisInstance; - } - - public RegistryService getRegistryService() { - return registryService; - } - - public void setRegistryService(RegistryService registryService) { - this.registryService = registryService; - } - - public AndroidGoogleEnterpriseService getAndroidDeviceManagementService() { - return androidDeviceManagementService; - } - - public void setAndroidDeviceManagementService( - AndroidGoogleEnterpriseService androidDeviceManagementService) { - this.androidDeviceManagementService = androidDeviceManagementService; - } - - public AndroidService getAndroidService() { - return androidService; - } - - public void setAndroidService(AndroidService androidService) { - this.androidService = androidService; - } - - public DeviceTypeCommonService getDeviceTypeCommonService() { - return deviceTypeCommonService; - } - - public void setDeviceTypeCommonService(DeviceTypeCommonService deviceTypeCommonService) { - this.deviceTypeCommonService = deviceTypeCommonService; - } - - public DeviceManagementProviderService getDeviceManagementProviderService() { - return deviceManagementProviderService; - } - - public void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) { - this.deviceManagementProviderService = deviceManagementProviderService; - } - - public ApplicationManagementProviderService getApplicationManagementProviderService() { - return applicationManagementProviderService; - } - - public void setApplicationManagementProviderService(ApplicationManagementProviderService applicationManagementProviderService) { - this.applicationManagementProviderService = applicationManagementProviderService; - } - - public NotificationManagementService getNotificationManagementService() { - return notificationManagementService; - } - - public void setNotificationManagementService(NotificationManagementService notificationManagementService) { - this.notificationManagementService = notificationManagementService; - } - - public DeviceInformationManager getDeviceInformationManager() { - return deviceInformationManager; - } - - public void setDeviceInformationManager(DeviceInformationManager deviceInformationManager) { - this.deviceInformationManager = deviceInformationManager; - } - - public PolicyManagerService getPolicyManagerService() { - return policyManagerService; - } - - public void setPolicyManagerService(PolicyManagerService policyManagerService) { - this.policyManagerService = policyManagerService; - } - - public AnalyticsDataAPI getAnalyticsDataAPI() { - return analyticsDataAPI; - } - - public void setAnalyticsDataAPI(AnalyticsDataAPI analyticsDataAPI) { - this.analyticsDataAPI = analyticsDataAPI; - } - - public EventsPublisherService getEventsPublisherService() { - return eventsPublisherService; - } - - public void setEventsPublisherService(EventsPublisherService eventsPublisherService) { - this.eventsPublisherService = eventsPublisherService; - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/internal/AndroidPluginServiceComponent.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/internal/AndroidPluginServiceComponent.java deleted file mode 100644 index 7835c12ae..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/internal/AndroidPluginServiceComponent.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleContext; -import org.osgi.service.component.ComponentContext; -import org.wso2.carbon.analytics.api.AnalyticsDataAPI; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; -import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; -import org.wso2.carbon.device.mgt.common.spi.DeviceTypeCommonService; -import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidGoogleEnterpriseService; -import org.wso2.carbon.device.mgt.mobile.android.common.spi.AndroidService; -import org.wso2.carbon.device.mgt.mobile.android.core.MobileDeviceConfigFactory; -import org.wso2.carbon.device.mgt.mobile.android.core.dao.AbstractMobileDeviceManagementDAOFactory; -import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidGoogleEnterpriseServiceImpl; -import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl; -import org.wso2.carbon.device.mgt.mobile.android.core.impl.DeviceTypeCommonServiceImpl; -import org.wso2.carbon.ndatasource.core.DataSourceService; -import org.wso2.carbon.policy.mgt.core.PolicyManagerService; -import org.wso2.carbon.registry.core.service.RegistryService; - -/** - * @scr.component name="org.wso2.carbon.device.mgt.mobile.android" immediate="true" - * @scr.reference name="org.wso2.carbon.device.manager" - * interface="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDeviceManagementService" - * unbind="unsetDeviceManagementService" - * @scr.reference name="org.wso2.carbon.devicemgt.policy.manager" - * interface="org.wso2.carbon.policy.mgt.core.PolicyManagerService" - * cardinality="1..1" - * policy="dynamic" - * bind="setPolicyManagerService" - * unbind="unsetPolicyManagerService" - * @scr.reference name="analytics.api.component" - * interface="org.wso2.carbon.analytics.api.AnalyticsDataAPI" - * cardinality="1..1" - * policy="dynamic" - * bind="setAnalyticsDataAPI" - * unbind="unsetAnalyticsDataAPI" - * @scr.reference name="org.wso2.carbon.device.mgt.analytics.data.publisher.internal.DataPublisherServiceComponent" - * interface="org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService" - * cardinality="1..1" - * policy="dynamic" - * bind="setEventsPublisherService" - * unbind="unsetEventsPublisherService" - * @scr.reference name="org.wso2.carbon.ndatasource" - * interface="org.wso2.carbon.ndatasource.core.DataSourceService" - * cardinality="1..1" - * policy="dynamic" - * bind="setDataSourceService" - * unbind="unsetDataSourceService" - * @scr.reference name="registry.service" - * interface="org.wso2.carbon.registry.core.service.RegistryService" - * cardinality="0..1" - * policy="dynamic" - * bind="setRegistryService" - * unbind="unsetRegistryService" - */ - -@SuppressWarnings("unused") -public class AndroidPluginServiceComponent { - - private static final Log log = LogFactory.getLog(AndroidPluginServiceComponent.class); - - protected void activate(ComponentContext componentContext) { - - if (log.isDebugEnabled()) { - log.debug("Activating Android Mobile Device Management Service Component"); - } - try { - BundleContext bundleContext = componentContext.getBundleContext(); - - MobileDeviceConfigFactory.init(); - AbstractMobileDeviceManagementDAOFactory.init("android", MobileDeviceConfigFactory - .getDataSourceConfigurations().getDataSourceConfiguration()); - - AndroidService androidService = new AndroidServiceImpl(); - AndroidDeviceManagementDataHolder.getInstance().setAndroidService(androidService); - bundleContext.registerService(AndroidService.class, androidService, null); - - DeviceTypeCommonService deviceTypeCommonService = new DeviceTypeCommonServiceImpl(); - AndroidDeviceManagementDataHolder.getInstance().setDeviceTypeCommonService(deviceTypeCommonService); - bundleContext.registerService(DeviceTypeCommonService.class, deviceTypeCommonService, null); - - AndroidGoogleEnterpriseService androidPluginService = new AndroidGoogleEnterpriseServiceImpl(); - AndroidDeviceManagementDataHolder.getInstance().setAndroidDeviceManagementService(androidPluginService); - bundleContext.registerService(AndroidGoogleEnterpriseService.class, androidPluginService, null); - if (log.isDebugEnabled()) { - log.debug("Android Mobile Device Management Service Component has been successfully activated"); - } - } catch (Throwable e) { - log.error("Error occurred while activating Android Mobile Device Management Service Component", e); - } - } - - protected void deactivate(ComponentContext componentContext) { - if (log.isDebugEnabled()) { - log.debug("De-activating Android Mobile Device Management Service Component"); - } - try { - if (log.isDebugEnabled()) { - log.debug( - "Android Mobile Device Management Service Component has been successfully de-activated"); - } - } catch (Throwable e) { - log.error("Error occurred while de-activating Android Mobile Device Management bundle", e); - } - } - - protected void setDeviceManagementService(DeviceManagementProviderService deviceManagerService) { - if (log.isDebugEnabled()) { - log.debug("Setting Device Management Service"); - } - AndroidDeviceManagementDataHolder.getInstance().setDeviceManagementProviderService(deviceManagerService); - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - - ApplicationManagementProviderService applicationManagementProviderService = - (ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null); - AndroidDeviceManagementDataHolder.getInstance() - .setApplicationManagementProviderService(applicationManagementProviderService); - - NotificationManagementService notificationManagementService = - (NotificationManagementService) ctx.getOSGiService(NotificationManagementService.class, null); - AndroidDeviceManagementDataHolder.getInstance() - .setNotificationManagementService(notificationManagementService); - - DeviceInformationManager deviceInformationManager = - (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); - AndroidDeviceManagementDataHolder.getInstance().setDeviceInformationManager(deviceInformationManager); - } - - protected void unsetDeviceManagementService(DeviceManagementProviderService deviceManagementService) { - if (log.isDebugEnabled()) { - log.debug("Removing Device Management Service"); - } - AndroidDeviceManagementDataHolder.getInstance().setDeviceManagementProviderService(null); - AndroidDeviceManagementDataHolder.getInstance().setApplicationManagementProviderService(null); - AndroidDeviceManagementDataHolder.getInstance().setNotificationManagementService(null); - AndroidDeviceManagementDataHolder.getInstance().setDeviceInformationManager(null); - } - - protected void setPolicyManagerService(PolicyManagerService policyManagerService) { - AndroidDeviceManagementDataHolder.getInstance().setPolicyManagerService(policyManagerService); - } - - protected void unsetPolicyManagerService(PolicyManagerService policyManagerService) { - AndroidDeviceManagementDataHolder.getInstance().setPolicyManagerService(null); - } - - protected void setAnalyticsDataAPI(AnalyticsDataAPI analyticsDataAPI) { - AndroidDeviceManagementDataHolder.getInstance().setAnalyticsDataAPI(analyticsDataAPI); - } - - protected void unsetAnalyticsDataAPI(AnalyticsDataAPI analyticsDataAPI) { - AndroidDeviceManagementDataHolder.getInstance().setAnalyticsDataAPI(null); - } - - protected void setEventsPublisherService(EventsPublisherService eventsPublisherService) { - AndroidDeviceManagementDataHolder.getInstance().setEventsPublisherService(eventsPublisherService); - } - - protected void unsetEventsPublisherService(EventsPublisherService eventsPublisherService) { - AndroidDeviceManagementDataHolder.getInstance().setEventsPublisherService(null); - } - - protected void setDataSourceService(DataSourceService dataSourceService) { - /* This is to avoid mobile device management component getting initialized before the underlying datasources - are registered */ - if (log.isDebugEnabled()) { - log.debug("Data source service set to android mobile service component"); - } - } - - protected void unsetDataSourceService(DataSourceService dataSourceService) { - //do nothing - } - - protected void setRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("RegistryService acquired"); - } - AndroidDeviceManagementDataHolder.getInstance().setRegistryService(registryService); - } - - protected void unsetRegistryService(RegistryService registryService) { - AndroidDeviceManagementDataHolder.getInstance().setRegistryService(null); - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/util/MobileDeviceManagementUtil.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/util/MobileDeviceManagementUtil.java deleted file mode 100644 index a559c11f5..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/util/MobileDeviceManagementUtil.java +++ /dev/null @@ -1,689 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.util; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.json.JSONArray; -import org.json.JSONObject; -import org.w3c.dom.Document; -import org.wso2.carbon.analytics.api.AnalyticsDataAPI; -import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil; -import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse; -import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry; -import org.wso2.carbon.analytics.datasource.commons.Record; -import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; -import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; -import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; -import org.wso2.carbon.context.CarbonContext; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.EnrolmentInfo; -import org.wso2.carbon.device.mgt.common.app.mgt.Application; -import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo; -import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.common.policy.mgt.ProfileFeature; -import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; -import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; -import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; -import org.wso2.carbon.device.mgt.core.operation.mgt.util.OperationIdComparator; -import org.wso2.carbon.device.mgt.core.search.mgt.impl.Utils; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.DeviceState; -import org.wso2.carbon.device.mgt.mobile.android.common.config.datasource.AndroidDBConfigurations; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.BadRequestException; -import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder; -import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; -import org.wso2.carbon.policy.mgt.common.PolicyManagementException; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.utils.CarbonUtils; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * Provides utility methods required by the mobile device management bundle. - */ -public class MobileDeviceManagementUtil { - - private static final Log log = LogFactory.getLog(MobileDeviceManagementUtil.class); - - public static Activity getOperationResponse(List deviceIDs, Operation operation) - throws AndroidDeviceMgtPluginException, OperationManagementException, InvalidDeviceException { - if (deviceIDs == null || deviceIDs.isEmpty()) { - String errorMessage = "Device identifier list is empty"; - log.error(errorMessage); - throw new BadRequestException(errorMessage); - } - DeviceIdentifier deviceIdentifier; - List deviceIdentifiers = new ArrayList<>(); - for (String deviceId : deviceIDs) { - deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(deviceId); - deviceIdentifier.setType(AndroidConstants.DEVICE_TYPE_ANDROID); - deviceIdentifiers.add(deviceIdentifier); - } - return AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService().addOperation( - DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, deviceIdentifiers); - } - - public static boolean isValidDeviceIdentifier(Device device) { - return !(device == null || device.getDeviceIdentifier() == null || - device.getDeviceIdentifier().isEmpty() || - device.getEnrolmentInfo() == null || - EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())); - } - - public static List getPendingOperations - (Device device, DeviceIdentifier deviceIdentifier) throws OperationManagementException { - List operations = AndroidDeviceManagementDataHolder.getInstance() - .getDeviceManagementProviderService().getPendingOperations(device); - if (operations != null) { - List pendingOperations = new ArrayList<>(operations); - if (!pendingOperations.isEmpty() && deviceIdentifier != null) { - handleAppManagerPayloadForOldAgent(deviceIdentifier, pendingOperations); - operations = pendingOperations; - } - } - return operations; - } - - public static void updateOperation(Device device, Operation operation) - throws OperationManagementException, PolicyComplianceException, - org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException { - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(device.getDeviceIdentifier()); - deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - - if (!Operation.Status.ERROR.equals(operation.getStatus()) && - AndroidConstants.OperationCodes.MONITOR.equals(operation.getCode())) { - if (log.isDebugEnabled()) { - log.debug("Received compliance status from MONITOR operation ID: " + operation.getId()); - } - AndroidDeviceManagementDataHolder.getInstance().getPolicyManagerService() - .checkPolicyCompliance(deviceIdentifier, getComplianceFeatures(operation.getPayLoad())); - } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. - OperationCodes.APPLICATION_LIST.equals(operation.getCode())) { - if (log.isDebugEnabled()) { - log.debug("Received applications list from device '" + device.getDeviceIdentifier() + "'"); - } - updateApplicationList(operation, device); - - } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. - OperationCodes.DEVICE_INFO.equals(operation.getCode())) { - - try { - if (log.isDebugEnabled()) { - log.debug("Operation response: " + operation.getOperationResponse()); - } - Device deviceInfoBean = new Gson().fromJson(operation.getOperationResponse(), Device.class); - org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo = convertDeviceToInfo(deviceInfoBean); - updateDeviceInfo(device, deviceInfo); - } catch (DeviceDetailsMgtException e) { - throw new OperationManagementException("Error occurred while updating the device information.", e); - } - - } else if (!Operation.Status.ERROR.equals(operation.getStatus()) && - AndroidConstants.OperationCodes.DEVICE_LOCATION.equals(operation.getCode())) { - try { - DeviceLocation location = new Gson().fromJson(operation.getOperationResponse(), DeviceLocation.class); - // reason for checking "location.getLatitude() != null" because when device fails to provide - // device location and send status instead, above Gson converter create new location object - // with null attributes - if (location != null && location.getLatitude() != null) { - location.setDeviceIdentifier(deviceIdentifier); - updateDeviceLocation(device, location); - } - } catch (DeviceDetailsMgtException e) { - throw new OperationManagementException("Error occurred while updating the device location.", e); - } - } else if (AndroidConstants.OperationCodes.INSTALL_APPLICATION.equals(operation.getCode()) - || AndroidConstants.OperationCodes.UNINSTALL_APPLICATION.equals(operation.getCode())) { - try { - updateAppSubStatus(deviceIdentifier, operation.getId(), operation.getStatus().toString()); - } catch (org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException e) { - String msg = "Error occurred while updating the app subscription for device."; - log.error(msg); - throw new OperationManagementException(msg, e); - } catch (DeviceManagementException e) { - String msg = "Error occurred while getting device data for device identifier."; - log.error(msg); - throw new OperationManagementException(msg, e); - } - } - AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .updateOperation(device, operation); - // This has to be bellow other if blocks, since updateOperation would fail if we execute against a disenrolled - // device. - if (!Operation.Status.ERROR.equals(operation.getStatus()) && AndroidConstants. - OperationCodes.WIPE_DATA.equals(operation.getCode())) { - if (log.isDebugEnabled()) { - log.debug("Received wipe data from device '" + device.getDeviceIdentifier() + "'"); - } - try { - AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .disenrollDevice(deviceIdentifier); - } catch (DeviceManagementException e) { - throw new OperationManagementException("Error occurred while unenrolling the device.", e); - } - - } - } - - /** - * App Installation and App Un-installation payloads are modified as per old app manager payloads to - * support old android agent versions. Old android agent versions are detected on the unavailability of - * AGENT_VERSION value. - * - * @param deviceIdentifier of the Device - * @param operations list of pending operations - * @throws OperationManagementException when there is an error in retreiveing device information - */ - private static void handleAppManagerPayloadForOldAgent( - DeviceIdentifier deviceIdentifier, List operations) throws OperationManagementException { - List appManagerOperations = new ArrayList<>(); - Iterator operationIterator = operations.iterator(); - while (operationIterator.hasNext()) { - Operation op = operationIterator.next(); - if (AndroidConstants.ApplicationInstall.INSTALL_APPLICATION.equals(op.getCode()) - || AndroidConstants.ApplicationInstall.UNINSTALL_APPLICATION.equals(op.getCode())) { - DeviceInfo deviceInfo; - try { - deviceInfo = AndroidDeviceManagementDataHolder.getInstance().getDeviceInformationManager() - .getDeviceInfo(deviceIdentifier); - } catch (DeviceDetailsMgtException e) { - String msg = "Error occurred while retrieving device info from DeviceInformationManagerService " - + "of device " + deviceIdentifier; - log.error(msg); - throw new OperationManagementException(msg, e); - } - if (deviceInfo != null - && deviceInfo.getDeviceDetailsMap() != null - && !deviceInfo.getDeviceDetailsMap().isEmpty() - && StringUtils.isBlank(deviceInfo.getDeviceDetailsMap().get( - AndroidConstants.ApplicationProperties.AGENT_VERSION))) { - JSONObject appPayload = new JSONObject(op.getPayLoad().toString()); - String appType = appPayload.getString(AndroidConstants.ApplicationProperties.TYPE); - if (AndroidConstants.ApplicationProperties.ENTERPRISE.equals(appType)) { - appPayload.put(AndroidConstants.ApplicationProperties.PACKAGE_NAME, - appPayload.getString(AndroidConstants.ApplicationProperties.APP_IDENTIFIER)); - op.setPayLoad(appPayload.toString()); - appManagerOperations.add(op); - operationIterator.remove(); - } else if (AndroidConstants.ApplicationProperties.WEB_CLIP.equals(appType)) { - appPayload.put(AndroidConstants.ApplicationProperties.TYPE, - AndroidConstants.ApplicationProperties.WEBAPP); - op.setPayLoad(appPayload.toString()); - appManagerOperations.add(op); - operationIterator.remove(); - } - } - } - } - if (!appManagerOperations.isEmpty()) { - operations.addAll(appManagerOperations); - operations.sort(new OperationIdComparator()); - } - } - - private static void updateApplicationList(Operation operation, Device device) - throws org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException { - // Parsing json string to get applications list. - if (operation.getOperationResponse() != null) { - if (operation.getOperationResponse().equals("SAME_APPLICATION_LIST")) { - return; - } - JsonElement jsonElement = new JsonParser().parse(operation.getOperationResponse()); - JsonArray jsonArray = jsonElement.getAsJsonArray(); - Application app; - List applications = new ArrayList<>(jsonArray.size()); - for (JsonElement element : jsonArray) { - app = new Application(); - app.setName(element.getAsJsonObject(). - get(AndroidConstants.ApplicationProperties.NAME).getAsString()); - app.setApplicationIdentifier(element.getAsJsonObject(). - get(AndroidConstants.ApplicationProperties.IDENTIFIER).getAsString()); - app.setPlatform(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS) != null) { - app.setMemoryUsage(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.USS).getAsInt()); - } - if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION) != null) { - app.setVersion(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.VERSION).getAsString()); - } - if (element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE) != null) { - app.setActive(element.getAsJsonObject().get(AndroidConstants.ApplicationProperties.IS_ACTIVE).getAsBoolean()); - } - applications.add(app); - } - AndroidDeviceManagementDataHolder.getInstance().getApplicationManagementProviderService() - .updateApplicationListInstalledInDevice(device, applications); - } else { - if (log.isDebugEnabled()) { - log.debug("Operation Response is null."); - } - } - } - - private static void updateDeviceLocation(Device device, DeviceLocation deviceLocation) - throws DeviceDetailsMgtException { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - DeviceInformationManager informationManager = - (DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null); - - informationManager.addDeviceLocation(device, deviceLocation); - } - - private static void updateAppSubStatus(DeviceIdentifier deviceIdentifier, int operationId, String status) - throws org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException, - DeviceManagementException { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - ApplicationManager applicationManager = - (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null); - Device device = AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .getDevice(deviceIdentifier); - applicationManager.updateSubsStatus(device.getId(), operationId, status); - } - - private static void updateDeviceInfo(Device device, DeviceInfo deviceInfo) - throws DeviceDetailsMgtException { - DeviceInformationManager informationManager = AndroidDeviceManagementDataHolder.getInstance() - .getDeviceInformationManager(); - informationManager.addDeviceInfo(device, deviceInfo); - } - - private static org.wso2.carbon.device.mgt.common.device.details.DeviceInfo convertDeviceToInfo(Device device) { - - org.wso2.carbon.device.mgt.common.device.details.DeviceInfo deviceInfo = - new org.wso2.carbon.device.mgt.common.device.details.DeviceInfo(); - if (deviceInfo.getDeviceDetailsMap() == null) { - deviceInfo.setDeviceDetailsMap(new HashMap<>()); - } - List props = device.getProperties(); - - for (Device.Property prop : props) { - if (Utils.getDeviceDetailsColumnNames().containsValue(prop.getName())) { - extractDefinedProperties(deviceInfo, prop); - } else { - extractMapProperties(deviceInfo, prop); - } - } - return deviceInfo; - } - - private static void extractMapProperties(DeviceInfo deviceInfo, Device.Property prop) { - if (prop.getName().equalsIgnoreCase("CPU_INFO")) { - deviceInfo.getDeviceDetailsMap().put("cpuUser", getProperty(prop.getValue(), "User")); - deviceInfo.getDeviceDetailsMap().put("cpuSystem", getProperty(prop.getValue(), "System")); - deviceInfo.getDeviceDetailsMap().put("IOW", getProperty(prop.getValue(), "IOW")); - deviceInfo.getDeviceDetailsMap().put("IRQ", getProperty(prop.getValue(), "IRQ")); - } else if (prop.getName().equalsIgnoreCase("RAM_INFO")) { - if (!getProperty(prop.getValue(), "TOTAL_MEMORY").isEmpty()) { - deviceInfo.setTotalRAMMemory(Double.parseDouble(getProperty(prop.getValue(), "TOTAL_MEMORY"))); - } else { - deviceInfo.setTotalRAMMemory(-1D); - } - if (!getProperty(prop.getValue(), "AVAILABLE_MEMORY").isEmpty()) { - deviceInfo.setAvailableRAMMemory(Double.parseDouble( - getProperty(prop.getValue(), "AVAILABLE_MEMORY"))); - } else { - deviceInfo.setAvailableRAMMemory(-1D); - } - deviceInfo.getDeviceDetailsMap().put("ramThreshold", getProperty(prop.getValue(), "THRESHOLD")); - deviceInfo.getDeviceDetailsMap().put("ramLowMemory", getProperty(prop.getValue(), "LOW_MEMORY")); - } else if (prop.getName().equalsIgnoreCase("BATTERY_INFO")) { - deviceInfo.setPluggedIn(Boolean.parseBoolean(getProperty(prop.getValue(), "PLUGGED"))); - - deviceInfo.getDeviceDetailsMap().put("batteryLevel", getProperty(prop.getValue(), "BATTERY_LEVEL")); - deviceInfo.getDeviceDetailsMap().put("batteryScale", getProperty(prop.getValue(), "SCALE")); - deviceInfo.getDeviceDetailsMap().put("batteryVoltage", - getProperty(prop.getValue(), "BATTERY_VOLTAGE")); - deviceInfo.getDeviceDetailsMap().put("batteryTemperature", - getProperty(prop.getValue(), "TEMPERATURE")); - deviceInfo.getDeviceDetailsMap().put("batteryCurrentTemperature", - getProperty(prop.getValue(), "CURRENT_AVERAGE")); - deviceInfo.getDeviceDetailsMap().put("batteryTechnology", - getProperty(prop.getValue(), "TECHNOLOGY")); - deviceInfo.getDeviceDetailsMap().put("batteryHealth", getProperty(prop.getValue(), "HEALTH")); - deviceInfo.getDeviceDetailsMap().put("batteryStatus", getProperty(prop.getValue(), "STATUS")); - } else if (prop.getName().equalsIgnoreCase("NETWORK_INFO")) { - deviceInfo.setSsid(getProperty(prop.getValue(), "WIFI_SSID")); - deviceInfo.setConnectionType(getProperty(prop.getValue(), "CONNECTION_TYPE")); - - deviceInfo.getDeviceDetailsMap().put("mobileSignalStrength", - getProperty(prop.getValue(), "MOBILE_SIGNAL_STRENGTH")); - deviceInfo.getDeviceDetailsMap().put("wifiSignalStrength", - getProperty(prop.getValue(), "WIFI_SIGNAL_STRENGTH")); - } else if (prop.getName().equalsIgnoreCase("DEVICE_INFO")) { - if (!getProperty(prop.getValue(), "BATTERY_LEVEL").isEmpty()) { - deviceInfo.setBatteryLevel(Double.parseDouble( - getProperty(prop.getValue(), "BATTERY_LEVEL"))); - } else { - deviceInfo.setBatteryLevel(-1D); - } - if (!getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY").isEmpty()) { - deviceInfo.setInternalTotalMemory(Double.parseDouble( - getProperty(prop.getValue(), "INTERNAL_TOTAL_MEMORY"))); - } else { - deviceInfo.setInternalTotalMemory(-1D); - } - if (!getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY").isEmpty()) { - deviceInfo.setInternalAvailableMemory(Double.parseDouble( - getProperty(prop.getValue(), "INTERNAL_AVAILABLE_MEMORY"))); - } else { - deviceInfo.setInternalAvailableMemory(-1D); - } - if (!getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY").isEmpty()) { - deviceInfo.setExternalTotalMemory(Double.parseDouble( - getProperty(prop.getValue(), "EXTERNAL_TOTAL_MEMORY"))); - } else { - deviceInfo.setExternalTotalMemory(-1D); - } - if (!getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY").isEmpty()) { - deviceInfo.setExternalAvailableMemory(Double.parseDouble( - getProperty(prop.getValue(), "EXTERNAL_AVAILABLE_MEMORY"))); - } else { - deviceInfo.setExternalAvailableMemory(-1D); - } - - deviceInfo.getDeviceDetailsMap().put("encryptionEnabled", - getProperty(prop.getValue(), "ENCRYPTION_ENABLED")); - deviceInfo.getDeviceDetailsMap().put("passcodeEnabled", - getProperty(prop.getValue(), "PASSCODE_ENABLED")); - deviceInfo.getDeviceDetailsMap().put("operator", - getProperty(prop.getValue(), "OPERATOR")); - deviceInfo.getDeviceDetailsMap().put("PhoneNumber", - getProperty(prop.getValue(), "PHONE_NUMBER")); - } else if (prop.getName().equalsIgnoreCase("IMEI")) { - deviceInfo.getDeviceDetailsMap().put("IMEI", prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("IMSI")) { - deviceInfo.getDeviceDetailsMap().put("IMSI", prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("MAC")) { - deviceInfo.getDeviceDetailsMap().put("mac", prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("SERIAL")) { - deviceInfo.getDeviceDetailsMap().put("serial", prop.getValue()); - } else { - deviceInfo.getDeviceDetailsMap().put(prop.getName(), prop.getValue()); - } - } - - private static void extractDefinedProperties(DeviceInfo deviceInfo, Device.Property prop) { - if (prop.getName().equalsIgnoreCase("DEVICE_MODEL")) { - deviceInfo.setDeviceModel(prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("VENDOR")) { - deviceInfo.setVendor(prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("OS_VERSION")) { - deviceInfo.setOsVersion(prop.getValue()); - } else if (prop.getName().equalsIgnoreCase("OS_BUILD_DATE")) { - deviceInfo.setOsBuildDate(prop.getValue()); - } - } - - private static String getProperty(String properties, String needed) { - // This is not a key value pair. value is the immediate element to its filed name. - // Ex: - // [{"name":"ENCRYPTION_ENABLED","value":"false"},{"name":"PASSCODE_ENABLED","value":"true"}, - // {"name":"BATTERY_LEVEL","value":"100"},{"name":"INTERNAL_TOTAL_MEMORY","value":"0.76"}] - JsonElement jsonElement = new JsonParser().parse(properties); - JsonArray jsonArray = jsonElement.getAsJsonArray(); - for (JsonElement element : jsonArray) { - if (element.isJsonObject()) { - JsonObject jsonObject = element.getAsJsonObject(); - if (jsonObject.has("name") - && jsonObject.get("name").getAsString().equalsIgnoreCase(needed)) { - if (jsonObject.has("value") && jsonObject.get("value") != JsonNull.INSTANCE) { - return jsonObject.get("value").getAsString().replace("%", ""); - } else { - return ""; - } - } - } - } - return ""; - } - - public static String getAuthenticatedUser() { - PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - String username = threadLocalCarbonContext.getUsername(); - String tenantDomain = threadLocalCarbonContext.getTenantDomain(); - if (username != null && username.endsWith(tenantDomain)) { - return username.substring(0, username.lastIndexOf("@")); - } - return username; - } - - public static void installEnrollmentApplications(ProfileFeature feature, DeviceIdentifier deviceIdentifier) - throws PolicyManagementException { - String uuid = ""; - try { - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - ApiApplicationKey apiApplicationKey = OAuthUtils.getClientCredentials(tenantDomain); - String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm() - .getRealmConfiguration().getAdminUserName() + AndroidConstants.ApplicationInstall.AT + tenantDomain; - AccessTokenInfo tokenInfo = OAuthUtils.getOAuthCredentials(apiApplicationKey, username); - String requestUrl = AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_PROTOCOL + - System.getProperty(AndroidConstants.ApplicationInstall.IOT_CORE_HOST) + - AndroidConstants.ApplicationInstall.COLON + - System.getProperty(AndroidConstants.ApplicationInstall.IOT_CORE_PORT) + - AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_URL; - JsonElement appListElement = new JsonParser().parse(feature.getContent().toString()).getAsJsonObject() - .get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_CODE); - - JSONObject deviceObject = new JSONObject(); - deviceObject.put("id", deviceIdentifier.getId()); - deviceObject.put("type", deviceIdentifier.getType()); - JSONArray payload = new JSONArray(); - payload.put(deviceObject); - StringEntity requestEntity = new StringEntity(payload.toString(), ContentType.APPLICATION_JSON); - JsonArray appListArray = appListElement.getAsJsonArray(); - for (JsonElement appElement : appListArray) { - JsonElement googlePolicyPayload = appElement.getAsJsonObject(). - get(AndroidConstants.ApplicationInstall.GOOGLE_POLICY_PAYLOAD); - - if (googlePolicyPayload == null || googlePolicyPayload.toString().equals("\"\"")) { - uuid = appElement.getAsJsonObject(). - get(AndroidConstants.ApplicationInstall.ENROLLMENT_APP_INSTALL_UUID).getAsString(); - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpPost postRequest = new HttpPost(requestUrl.replace("{uuid}", uuid)); - postRequest.setHeader(AndroidConstants.ApplicationInstall.AUTHORIZATION, - AndroidConstants.ApplicationInstall.AUTHORIZATION_HEADER_VALUE + tokenInfo - .getAccessToken()); - postRequest.setEntity(requestEntity); - httpClient.execute(postRequest); - } - } - } - } catch (UserStoreException e) { - String msg = "Error while accessing user store for user with Android device id: " + - deviceIdentifier.getId(); - log.error(msg, e); - throw new PolicyManagementException(msg, e); - } catch (APIManagerException e) { - String msg = "Error while retrieving access token for Android device id: " + deviceIdentifier.getId(); - log.error(msg, e); - throw new PolicyManagementException(msg, e); - } catch (HttpException e) { - String msg = "Error while calling the app store to install enrollment app with uuid: " + uuid + - " on device with id: " + deviceIdentifier.getId(); - log.error(msg, e); - throw new PolicyManagementException(msg, e); - } catch (IOException e) { - String msg = "Error while installing the enrollment with uuid: " + uuid + " on device with id: " + - deviceIdentifier.getId(); - log.error(msg, e); - throw new PolicyManagementException(msg, e); - } - } - - /** - * Update status of pending operations to error when a dis-enroll operation is triggered. - * - * @param device the device - * @throws DeviceManagementException - */ - public static void updateDisEnrollOperationStatus(Device device) - throws DeviceManagementException { - try { - List pendingOperations = getPendingOperations(device, null); - if (pendingOperations != null && !pendingOperations.isEmpty()) { - for (Operation operation : pendingOperations) { - operation.setStatus(Operation.Status.ERROR); - AndroidDeviceManagementDataHolder.getInstance().getDeviceManagementProviderService() - .updateOperation(device, operation); - } - } - } catch (OperationManagementException e) { - String msg = "Error occurred while retrieving pending operations to update operation statuses of " + - "device to be dis-enrolled"; - log.error(msg); - throw new DeviceManagementException(msg, e); - } - } - - public static List getAllEventsForDevice(String tableName, String query) throws AnalyticsException { - int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); - AnalyticsDataAPI analyticsDataAPI = AndroidDeviceManagementDataHolder.getInstance().getAnalyticsDataAPI(); - int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); - if (eventCount == 0) { - return null; - } - List resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount); - List recordIds = getRecordIds(resultEntries); - AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); - Map deviceStateses = createDeviceStatusData(AnalyticsDataAPIUtil.listRecords( - analyticsDataAPI, response)); - return getSortedDeviceStateData(deviceStateses, resultEntries); - } - - private static List getRecordIds(List searchResults) { - List ids = new ArrayList<>(); - for (SearchResultEntry searchResult : searchResults) { - ids.add(searchResult.getId()); - } - return ids; - } - - public static Map createDeviceStatusData(List records) { - Map deviceStatuses = new HashMap<>(); - for (Record record : records) { - DeviceState deviceState = createDeviceStatusData(record); - deviceStatuses.put(deviceState.getId(), deviceState); - } - return deviceStatuses; - } - - private static DeviceState createDeviceStatusData(Record record) { - DeviceState deviceState = new DeviceState(); - deviceState.setId(record.getId()); - deviceState.setValues(record.getValues()); - return deviceState; - } - - public static List getSortedDeviceStateData(Map sensorDatas, - List searchResults) { - List sortedRecords = new ArrayList<>(); - for (SearchResultEntry searchResultEntry : searchResults) { - sortedRecords.add(sensorDatas.get(searchResultEntry.getId())); - } - return sortedRecords; - } - - public static DeviceIdentifier convertToDeviceIdentifierObject(String deviceId) { - DeviceIdentifier identifier = new DeviceIdentifier(); - identifier.setId(deviceId); - identifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - return identifier; - } - - private static List getComplianceFeatures(Object compliancePayload) - throws PolicyComplianceException { - String compliancePayloadString = new Gson().toJson(compliancePayload); - if (compliancePayload == null) { - return null; - } - // Parsing json string to get compliance features. - JsonElement jsonElement; - if (compliancePayloadString instanceof String) { - jsonElement = new JsonParser().parse(compliancePayloadString); - } else { - throw new PolicyComplianceException("Invalid policy compliance payload"); - } - - JsonArray jsonArray = jsonElement.getAsJsonArray(); - Gson gson = new Gson(); - ComplianceFeature complianceFeature; - List complianceFeatures = new ArrayList(jsonArray.size()); - - for (JsonElement element : jsonArray) { - complianceFeature = gson.fromJson(element, ComplianceFeature.class); - complianceFeatures.add(complianceFeature); - } - return complianceFeatures; - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/util/OAuthUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/util/OAuthUtils.java deleted file mode 100644 index d4a6064aa..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/util/OAuthUtils.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2018, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; -import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; -import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.mobile.android.common.AndroidConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.ApiRegistrationProfile; -import org.wso2.carbon.identity.jwt.client.extension.JWTClient; -import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; -import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; -import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.utils.multitenancy.MultitenantConstants; - -public class OAuthUtils { - - private static final Log log = LogFactory.getLog(OAuthUtils.class); - - public static ApiApplicationKey getClientCredentials(String tenantDomain) - throws UserStoreException, APIManagerException { - ApiRegistrationProfile registrationProfile = new ApiRegistrationProfile(); - registrationProfile.setApplicationName(AndroidConstants.ApplicationInstall.APPLICATION_NAME); - registrationProfile.setTags(new String[]{AndroidConstants.DEVICE_TYPE_ANDROID}); - registrationProfile.setAllowedToAllDomains(false); - registrationProfile.setMappingAnExistingOAuthApp(false); - return getCredentials(registrationProfile, tenantDomain); - } - - public static ApiApplicationKey getCredentials(ApiRegistrationProfile registrationProfile, String tenantDomain) - throws UserStoreException, APIManagerException { - ApiApplicationKey apiApplicationKeyInfo; - if (tenantDomain == null || tenantDomain.isEmpty()) { - tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; - } - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(PrivilegedCarbonContext. - getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName()); - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - APIManagementProviderService apiManagementProviderService = (APIManagementProviderService) ctx. - getOSGiService(APIManagementProviderService.class, null); - apiApplicationKeyInfo = apiManagementProviderService. - generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), - registrationProfile.getTags(), AndroidConstants.ApplicationInstall.DEFAULT_TOKEN_TYPE, - registrationProfile.getApplicationName(), registrationProfile.isAllowedToAllDomains(), - AndroidConstants.ApplicationInstall.DEFAULT_VALIDITY_PERIOD); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - } - return apiApplicationKeyInfo; - } - - public static AccessTokenInfo getOAuthCredentials(ApiApplicationKey apiApplicationKey, String username) - throws APIManagerException { - try { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - JWTClientManagerService jwtClientManagerService = (JWTClientManagerService) ctx. - getOSGiService(JWTClientManagerService.class, null); - JWTClient jwtClient = jwtClientManagerService.getJWTClient(); - return jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), - username, AndroidConstants.ApplicationInstall.SUBSCRIPTION_SCOPE); - } catch (JWTClientException e) { - String errorMsg = "Error while generating an OAuth token for user " + username; - log.error(errorMsg, e); - throw new APIManagerException(errorMsg, e); - } - } - -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/DeviceManagementAdminServiceTests.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/DeviceManagementAdminServiceTests.java deleted file mode 100644 index aba3da397..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/DeviceManagementAdminServiceTests.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core; - -import org.junit.Assert; -import org.junit.Test; -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockObjectFactory; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl; -import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceManagementProviderServiceMock; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.utils.TestUtils; - -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) -@PrepareForTest(AndroidDeviceManagementDataHolder.class) -public class DeviceManagementAdminServiceTests { - - private AndroidServiceImpl androidService; - - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new PowerMockObjectFactory(); - } - - @BeforeClass - public void init() { - MockitoAnnotations.initMocks(this); - androidService = new AndroidServiceImpl(); - } - - private void mockDeviceManagementService() { - PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceManagementProviderService")) - .toReturn(new DeviceManagementProviderServiceMock()); - } - - @Test - public void testConfigureDeviceLock() throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.configureDeviceLock(TestUtils.getDeviceLockBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testConfigureDeviceUnlock() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.configureDeviceUnlock(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testGetDeviceLocation() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.getDeviceLocation(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testRemovePassword() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.removePassword(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testConfigureCamera() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.configureCamera(TestUtils.getCamerabeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testGetDeviceInformation() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.getDeviceInformation(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testGetDeviceLogcat() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.getDeviceLogcat(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testWipeDevice() throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.wipeDevice(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testWipeData() throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.wipeData(TestUtils.getWipeDataBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testGetApplications() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.getApplications(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testRingDevice() throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.ringDevice(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testRebootDevice() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.rebootDevice(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testChangeLockTask() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.changeLockTask(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testMuteDevice() throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.muteDevice(TestUtils.getDeviceIds()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testInstallApplication() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService - .installApplication(TestUtils.getApplicationInstallationBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testUpdateApplication() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.updateApplication(TestUtils.getApplicationUpdateBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testUninstallApplicationPublic() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService - .uninstallApplication(TestUtils.getApplicationUninstallationBeanWrapperPublic()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testUninstallApplicationWebApp() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService - .uninstallApplication(TestUtils.getApplicationUninstallationBeanWrapperWebApp()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testBlacklistApplications() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService - .blacklistApplications(TestUtils.getBlacklistApplicationsBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testUpgradeFirmware() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.upgradeFirmware(TestUtils.getUpgradeFirmwareBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testConfigureVPN() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.configureVPN(TestUtils.getVpnBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testSendNotification() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.sendNotification(TestUtils.getNotificationBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testConfigureWifi() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.configureWifi(TestUtils.getWifiBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testEncryptStorage() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.encryptStorage(TestUtils.getEncryptionBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testChangeLockCode() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.changeLockCode(TestUtils.getLockCodeBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testSetPasswordPolicy() - throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.setPasswordPolicy(TestUtils.getPasswordPolicyBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } - - @Test - public void testSetWebClip() throws OperationManagementException, AndroidDeviceMgtPluginException { - mockDeviceManagementService(); - Activity activity = androidService.setWebClip(TestUtils.getWebClipBeanWrapper()); - Assert.assertNotNull(activity); - Assert.assertNotNull(activity.getActivityId()); - } -} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/DeviceManagementServiceTests.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/DeviceManagementServiceTests.java deleted file mode 100644 index 2a37841d9..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/test/java/org/wso2/carbon/device/mgt/mobile/android/core/DeviceManagementServiceTests.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.core; - -import org.mockito.MockitoAnnotations; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockObjectFactory; -import org.testng.Assert; -import org.testng.IObjectFactory; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.ObjectFactory; -import org.testng.annotations.Test; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -import org.wso2.carbon.device.mgt.mobile.android.common.Message; -import org.wso2.carbon.device.mgt.mobile.android.common.bean.wrapper.AndroidDevice; -import org.wso2.carbon.device.mgt.mobile.android.core.impl.AndroidServiceImpl; -import org.wso2.carbon.device.mgt.mobile.android.core.internal.AndroidDeviceManagementDataHolder; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.ApplicationManagementProviderServiceMock; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceInformationManagerServiceMock; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.DeviceManagementProviderServiceMock; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.NotificationManagementServiceMock; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.PolicyManagerServiceMock; -import org.wso2.carbon.device.mgt.mobile.android.core.mokcs.utils.TestUtils; -import org.wso2.carbon.device.mgt.mobile.android.core.util.MobileDeviceManagementUtil; - -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.List; - -@PowerMockIgnore({"javax.ws.rs.*", "org.apache.log4j.*"}) -@PrepareForTest({AndroidDeviceManagementDataHolder.class, MobileDeviceManagementUtil.class}) -public class DeviceManagementServiceTests { - - private AndroidServiceImpl androidService; - - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new PowerMockObjectFactory(); - } - - @BeforeClass - public void init() { - MockitoAnnotations.initMocks(this); - androidService = new AndroidServiceImpl(); - } - - private void mockDeviceManagementService() { - PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceManagementProviderService")) - .toReturn(new DeviceManagementProviderServiceMock()); - } - - private void mockApplicationManagerService() { - PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getApplicationManagementProviderService")) - .toReturn(new ApplicationManagementProviderServiceMock()); - } - - private void mockPolicyManagerService() { - PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getPolicyManagerService")) - .toReturn(new PolicyManagerServiceMock()); - } - - private void mockDeviceInformationManagerService() { - PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getDeviceInformationManager")) - .toReturn(new DeviceInformationManagerServiceMock()); - } - - private void mockNotificationManagementService() { - PowerMockito.stub(PowerMockito.method(AndroidDeviceManagementDataHolder.class, "getNotificationManagementService")) - .toReturn(new NotificationManagementServiceMock()); - } - - private void mockUser() { - PowerMockito.stub(PowerMockito.method(MobileDeviceManagementUtil.class, "getAuthenticatedUser")) - .toReturn("admin"); - } - - @Test - public void testUpdateApplicationList() - throws ApplicationManagementException { - mockApplicationManagerService(); - Message message = androidService - .updateApplicationList(TestUtils.getDeviceId(), TestUtils.getAndroidApplications()); - Assert.assertNotNull(message); - Assert.assertEquals(message.getResponseCode(), Response.Status.ACCEPTED.toString()); - } - - @Test (expectedExceptions = {InvalidDeviceException.class}) - public void testGetPendingOperationsForNullDevice() - throws DeviceManagementException, InvalidDeviceException { - List resultOperations = new ArrayList<>(); - androidService.getPendingOperations(null, resultOperations); - } - - @Test (expectedExceptions = {InvalidDeviceException.class}) - public void testGetPendingOperationsForInvalidDevice() - throws DeviceManagementException, InvalidDeviceException { - mockDeviceManagementService(); - List resultOperations = new ArrayList<>(); - DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject("1234"); - androidService.getPendingOperations(deviceIdentifier, resultOperations); - } - - @Test - public void testGetPendingOperationsNullResponse() - throws DeviceManagementException, InvalidDeviceException { - mockDeviceManagementService(); - DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); - List pendingOperations = androidService - .getPendingOperations(deviceIdentifier, null); - Assert.assertNotNull(pendingOperations); - Assert.assertFalse((pendingOperations.isEmpty())); - } - - @Test - public void testGetPendingOperationsWithMonitorResponse() - throws DeviceManagementException, InvalidDeviceException { - mockDeviceManagementService(); - mockPolicyManagerService(); - DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); - List pendingOperations = androidService - .getPendingOperations(deviceIdentifier, TestUtils.getSuccessMonitorOperationResponse()); - Assert.assertNotNull(pendingOperations); - Assert.assertFalse((pendingOperations.isEmpty())); - } - - @Test - public void testGetPendingOperationsWithApplicationResponse() - throws DeviceManagementException, InvalidDeviceException { - mockDeviceManagementService(); - mockApplicationManagerService(); - DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); - List pendingOperations = androidService - .getPendingOperations(deviceIdentifier, TestUtils.getSuccessApplicationOperationResponse()); - Assert.assertNotNull(pendingOperations); - Assert.assertFalse((pendingOperations.isEmpty())); - } - - @Test - public void testGetPendingOperationsWithDeviceInfoResponse() - throws DeviceManagementException, InvalidDeviceException { - mockDeviceManagementService(); - mockDeviceInformationManagerService(); - DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); - List pendingOperations = androidService - .getPendingOperations(deviceIdentifier, TestUtils.getSuccessInfoOperationResponse()); - Assert.assertNotNull(pendingOperations); - Assert.assertFalse((pendingOperations.isEmpty())); - } - - @Test - public void testGetPendingOperationsWithInProgressResponse() - throws DeviceManagementException, InvalidDeviceException { - mockDeviceManagementService(); - DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); - List pendingOperations = androidService - .getPendingOperations(deviceIdentifier, TestUtils.getInProgressOperationResponse()); - Assert.assertNotNull(pendingOperations); - Assert.assertFalse((pendingOperations.isEmpty())); - } - - @Test - public void testGetPendingOperationsWithErrorResponse() - throws DeviceManagementException, InvalidDeviceException { - mockDeviceManagementService(); - mockNotificationManagementService(); - DeviceIdentifier deviceIdentifier = MobileDeviceManagementUtil.convertToDeviceIdentifierObject(TestUtils.getDeviceId()); - List pendingOperations = androidService - .getPendingOperations(deviceIdentifier, TestUtils.getErrorOperationResponse()); - Assert.assertNotNull(pendingOperations); - Assert.assertFalse((pendingOperations.isEmpty())); - } - - @Test - public void testEnrollDeviceWithoutLocationSuccess() - throws DeviceManagementException { - mockDeviceManagementService(); - mockPolicyManagerService(); - mockUser(); - Message message = androidService.enrollDevice(TestUtils.getBasicAndroidDevice()); - Assert.assertNotNull(message); - Assert.assertEquals(message.getResponseCode(), Response.Status.OK.getStatusCode()); - } - - @Test - public void testEnrollDeviceWithLocationSuccess() throws DeviceManagementException { - mockDeviceManagementService(); - mockDeviceInformationManagerService(); - mockPolicyManagerService(); - mockUser(); - AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice(); - - List properties = new ArrayList<>(); - Device.Property property = new Device.Property(); - property.setName("LATITUDE"); - property.setValue("79.5"); - properties.add(property); - property = new Device.Property(); - property.setName("LONGITUDE"); - property.setValue("6.9"); - properties.add(property); - property = new Device.Property(); - property.setName("ALTITUDE"); - property.setValue("-59.8373726"); - properties.add(property); - property = new Device.Property(); - property.setName("SPEED"); - property.setValue("0.5123423333"); - properties.add(property); - property = new Device.Property(); - property.setName("BEARING"); - property.setValue("44.0"); - properties.add(property); - property = new Device.Property(); - property.setName("DISTANCE"); - property.setValue("44.0"); - properties.add(property); - androidDevice.setProperties(properties); - - Message message = androidService.enrollDevice(androidDevice); - Assert.assertNotNull(message); - Assert.assertEquals(message.getResponseCode(), Response.Status.OK.getStatusCode()); - } - - @Test - public void testEnrollDeviceUnSuccess() throws DeviceManagementException { - mockDeviceManagementService(); - mockUser(); - AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice(); - androidDevice.setDeviceIdentifier("1234"); - Message message = androidService.enrollDevice(androidDevice); - Assert.assertNotNull(message); - Assert.assertEquals(message.getResponseCode(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); - } - - @Test - public void testIsEnrolledExists() throws DeviceManagementException { - mockDeviceManagementService(); - Message message = androidService.isEnrolled(TestUtils.getDeviceId(), null); - Assert.assertNotNull(message); - Assert.assertEquals(message.getResponseCode(), Response.Status.OK.toString()); - } - - @Test - public void testIsEnrolledNonExist() throws DeviceManagementException { - mockDeviceManagementService(); - Message message = androidService.isEnrolled("1234", null); - Assert.assertNotNull(message); - Assert.assertEquals(message.getResponseCode(), Response.Status.NOT_FOUND.toString()); - } - - @Test - public void testIsEnrolledNull() throws DeviceManagementException { - mockDeviceManagementService(); - Message response = androidService.isEnrolled(null, null); - Assert.assertNotNull(response); - Assert.assertEquals(response.getResponseCode(), Response.Status.NOT_FOUND.toString()); - } - - @Test - public void testModifyEnrollmentSuccess() throws DeviceManagementException { - mockDeviceManagementService(); - mockUser(); - boolean status = androidService.modifyEnrollment(TestUtils.getDeviceId(), TestUtils.getBasicAndroidDevice()); - Assert.assertTrue(status); - } - - @Test - public void testModifyEnrollmentUnSuccess() throws DeviceManagementException { - mockDeviceManagementService(); - mockUser(); - AndroidDevice androidDevice = TestUtils.getBasicAndroidDevice(); - androidDevice.setDeviceIdentifier("1234"); - boolean status = androidService.modifyEnrollment(TestUtils.getDeviceId(), androidDevice); - Assert.assertFalse(status); - } - - @Test - public void testDisEnrollDeviceSuccess() throws DeviceManagementException { - mockDeviceManagementService(); - boolean status = androidService.disEnrollDevice(TestUtils.getDeviceId()); - Assert.assertTrue(status); - } - - @Test - public void testDisEnrollUnSuccess() throws DeviceManagementException { - mockDeviceManagementService(); - boolean status = androidService.disEnrollDevice("1234"); - Assert.assertFalse(status); - } -} - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml index 6db3752a1..ed8ce3c6b 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml @@ -29,7 +29,6 @@ 4.0.0 org.wso2.carbon.device.mgt.mobile.android.ui - 5.0.7-SNAPSHOT WSO2 Carbon - Mobile Android UI pom diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.hbs index f360de27b..a70e51f93 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.hbs @@ -20,12 +20,12 @@ data-deviceinfoservice="{{device.deviceInfoServiceAPI}}" data-devicelocationservice="{{device.deviceLocationServiceAPI}}"> {{device.owner}}'s {{device.name}} - - - + + {{#if device.model}}

{{device.vendor}} {{device.model}}

{{/if}} @@ -97,8 +97,6 @@
  • Applications
  • Policy Compliance
  • -
  • Extensive Device Information
  • -
  • Remote Session
  • {{/zone}} {{#zone "device-view-tab-injected-conents"}} @@ -116,7 +114,7 @@ The device location information is not available right now! Please refresh the page in a few minutes. The location details will not be available if the device’s “Location Services setting” is disabled - or if Entgra IoT Server has not received the device’s location information from the device. + or if WSO2 IoT Server has not received the device’s location information from the device.

    @@ -144,105 +142,6 @@
    -
    -
    - {{#if device.deviceInfoAvailable}} - - {{#each device.extensiveDeviceInfo}} - - - - - {{/each}} -
    - {{@key}} - - {{this}} -
    - {{else}}

    Extensive information is not available yet.

    - {{/if}} -
    -
    - -
    -
    - - -
    -
    {{/zone}} @@ -274,7 +173,6 @@ type="text/x-handlebars-template"> {{js "js/device-detail.js"}} - {{js "js/remote-session.js"}} {{js "js/jquery.touchSwipe.min.js"}} {{/if}} {{/zone}} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.js index c786448f9..da2574458 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/device-view.js @@ -76,33 +76,10 @@ function onRequest(context) { viewModel["ownership"] = filteredDeviceData["enrolmentInfo"]["ownership"]; } } - var extensiveDeviceInfo = {}; if (filteredDeviceData["initialDeviceInfo"]) { viewModel["deviceInfoAvailable"] = true; if (filteredDeviceData["initialDeviceInfo"]["IMEI"]) { viewModel["imei"] = filteredDeviceData["initialDeviceInfo"]["IMEI"]; - extensiveDeviceInfo["IMEI"] = filteredDeviceData["initialDeviceInfo"]["IMEI"]; - } - if (filteredDeviceData["initialDeviceInfo"]["IMSI"]) { - extensiveDeviceInfo["IMSI"] = filteredDeviceData["initialDeviceInfo"]["IMSI"]; - } - if (filteredDeviceData["initialDeviceInfo"]["OS_VERSION"]) { - extensiveDeviceInfo["OS Version"] = filteredDeviceData["initialDeviceInfo"]["OS_VERSION"]; - } - if (filteredDeviceData["initialDeviceInfo"]["DEVICE_MODEL"]) { - extensiveDeviceInfo["Model"] = filteredDeviceData["initialDeviceInfo"]["DEVICE_MODEL"]; - } - if (filteredDeviceData["initialDeviceInfo"]["VENDOR"]) { - extensiveDeviceInfo["Vendor"] = filteredDeviceData["initialDeviceInfo"]["VENDOR"]; - } - if (filteredDeviceData["initialDeviceInfo"]["SERIAL"]) { - extensiveDeviceInfo["Serial Number"] = filteredDeviceData["initialDeviceInfo"]["SERIAL"]; - } - if (filteredDeviceData["initialDeviceInfo"]["MAC_ADDRESS"]) { - extensiveDeviceInfo["MAC Address"] = filteredDeviceData["initialDeviceInfo"]["MAC_ADDRESS"]; - } - if (filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"]) { - extensiveDeviceInfo["OS Build Date"] = filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"]; } if (!filteredDeviceData["latestDeviceInfo"]) { if (filteredDeviceData["initialDeviceInfo"]["OS_BUILD_DATE"]) { @@ -132,12 +109,6 @@ function onRequest(context) { } else { viewModel["internalMemory"]["usage"] = 0; } - if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["OPERATOR"]) { - extensiveDeviceInfo["Operator"] = filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["OPERATOR"]; - } - if (filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["PHONE_NUMBER"]) { - extensiveDeviceInfo["Phone Number"] = filteredDeviceData["initialDeviceInfo"]["DEVICE_INFO"]["PHONE_NUMBER"]; - } viewModel["externalMemory"] = {}; viewModel["externalMemory"]["total"] = replaceNaNVal(Math. @@ -171,15 +142,6 @@ function onRequest(context) { viewModel["vendor"] = filteredDeviceData["latestDeviceInfo"]["vendor"]; viewModel["model"] = filteredDeviceData["latestDeviceInfo"]["deviceModel"]; } - if (filteredDeviceData["latestDeviceInfo"]["osVersion"]) { - extensiveDeviceInfo["OS Version"] = filteredDeviceData["latestDeviceInfo"]["osVersion"]; - } - if (filteredDeviceData["latestDeviceInfo"]["connectionType"]) { - extensiveDeviceInfo["Connection Type"] = filteredDeviceData["latestDeviceInfo"]["connectionType"]; - } - if (filteredDeviceData["latestDeviceInfo"]["ssid"]) { - extensiveDeviceInfo["SSID"] = filteredDeviceData["latestDeviceInfo"]["ssid"]; - } if (filteredDeviceData["latestDeviceInfo"]["updatedTime"]) { viewModel["lastUpdatedTime"] = filteredDeviceData["latestDeviceInfo"]["updatedTime"]. substr(0, filteredDeviceData["latestDeviceInfo"]["updatedTime"].indexOf("+")); @@ -189,7 +151,6 @@ function onRequest(context) { viewModel["cpuUsage"] = {}; viewModel["cpuUsage"]["value"] = filteredDeviceData["latestDeviceInfo"]["cpuUsage"]; - extensiveDeviceInfo["CPU Usage"] = filteredDeviceData["latestDeviceInfo"]["cpuUsage"]; viewModel["ramUsage"] = {}; if (filteredDeviceData["latestDeviceInfo"]["totalRAMMemory"] != 0) { @@ -222,7 +183,6 @@ function onRequest(context) { viewModel["externalMemory"]["usage"] = 0; } } - viewModel["extensiveDeviceInfo"] = extensiveDeviceInfo; if (!filteredDeviceData["initialDeviceInfo"] && !filteredDeviceData["latestDeviceInfo"]) { viewModel["deviceInfoAvailable"] = false; } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/device-detail.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/device-detail.js index 8739addd1..cf3b3665c 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/device-detail.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/device-detail.js @@ -211,7 +211,7 @@ var InitiateViewOption = null; order: [], ajax: { url: "/devicemgt/api/operation/paginate", - data: {deviceId: deviceIdentifier, deviceType: deviceType, owner: owner, ownership: ownership}, + data: {deviceId: deviceIdentifier, deviceType: deviceType, owner: owner}, dataSrc: function (json) { $("#operations-spinner").addClass("hidden"); $("#operations-log-container").empty(); diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/remote-session.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/remote-session.js deleted file mode 100644 index 8fd1718d3..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/remote-session.js +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -var rs_websocket; -var rs_WebSocketURL; -var shellMessageField = document.getElementById('shell-command'); -var shellResponseField = document.getElementById('shell-response'); -var canRemotelyControl = true; -WebSocket.prototype.set_opened = function() { - this._opened = true; -}; - -WebSocket.prototype.set_closed = function() { - this._opened = false; -}; -WebSocket.prototype.get_opened = function() { - return this._opened || false; -}; - -var remoteSessionWebSocketOnOpen = function() { - rs_websocket.set_opened(); -}; - -var remoteSessionWebSocketOnMessage = function(message) { - - $('#lbl-remote-session-status').text('Server Connected...'); - $('#remote-session-operations').removeClass('hidden'); - $('#loading-remote-session').addClass('hidden'); - $('#btn-close-remote-session').removeClass('hidden'); - $('#shell-terminal').removeClass('hidden'); - if (typeof message.data !== 'string') { - $('#loading-screen').addClass('hidden'); - var url = URL.createObjectURL(event.data); - var img = new Image; - - img.onload = function() { - var ctx = document.getElementById("canvas").getContext('2d'); - ctx.canvas.height = this.height; - ctx.canvas.width = this.width; - ctx.drawImage(this, 0, 0); - URL.revokeObjectURL(url); - } - img.src = url; - } else { - - var json = $.parseJSON(message.data); - if (json.code == "REMOTE_SHELL") { - if (json.status != "NEW") { - $('#loading-terminal').addClass('hidden'); - } - if (json.operationResponse != null) { - var shellResponse = $("#shell-response"); - shellResponse.val(shellResponse.val() + json.operationResponse); - } - - } else if (json.code == "REMOTE_LOGCAT") { - - if (json.status != "NEW") { - $('#btn-refresh-logCat').removeClass('hidden'); - $('#loading-logcat').addClass('hidden'); - } - if (json.operationResponse != null) { - var logcatResponse = $("#logcat-response"); - - logcatResponse.val(logcatResponse.val() + json.operationResponse); - } - } else if (json.code == "REMOTE_CONNECT") { - $('#loading-terminal').addClass('hidden'); - if (json.operationResponse != null) { - var shellResponse = $("#shell-response"); - shellResponse.val(json.operationResponse); - } - } else if (json.code == "REMOTE_INPUT") { - canRemotelyControl = false; - } else { - console.log("Message type not supported." + JSON.stringify(json)); - } - } -}; - -var remoteSessionWebSocketOnClose = function(e) { - location.reload(); -}; - -var remoteSessionWebSocketOnError = function(err) { - location.reload(); -}; - -$("#btn-connect-device").click(function() { - - $('#loading-remote-session').removeClass('hidden'); - $('#btn-connect-device').addClass('hidden'); - $('#lbl-remote-session-status').text('Connecting to Server...'); - initializeRemoteSession(); -}); - - -$("#btn-close-remote-session").click(function() { - // Close the WebSocket. - rs_websocket.close(); - rs_websocket.set_closed(); - var canvas = document.getElementById("canvas"); - var ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, canvas.width, canvas.height); - $('#btn-connect-device').removeClass('hidden'); - $('#remote-session-operations').addClass('hidden'); - $('#btn-close-remote-session').addClass('hidden'); - $('#loading-screen').addClass('hidden'); - $('#btn-stop-screen').addClass('hidden'); - $('#btn-start-screen').removeClass('hidden'); - //location.reload(); -}); - -$("#btn-refresh-logCat").click(function() { - - $('#loading-logcat').removeClass('hidden'); - $('#btn-refresh-logCat').addClass('hidden'); - var message = new Object(); - message.code = "REMOTE_LOGCAT"; - - // Send the message through the WebSocket. - rs_websocket.send(JSON.stringify(message)); - - // Clear out the message field. - $("#logcat-response").val(""); - -}); - - -function initializeRemoteSessionWebSocket() { - - rs_websocket = new WebSocket(rs_WebSocketURL); - rs_websocket.onopen = remoteSessionWebSocketOnOpen; - rs_websocket.onmessage = remoteSessionWebSocketOnMessage; - rs_websocket.onclose = remoteSessionWebSocketOnClose; - rs_websocket.onerror = remoteSessionWebSocketOnError; - -} - -function initializeRemoteSession() { - - rs_WebSocketURL = $("#remote-session").data("remote-session-uri"); - if (rs_WebSocketURL != null) { - initializeRemoteSessionWebSocket(); - window.onbeforeunload = function() { - rs_websocket.close(); - } - $('#lbl-remote-session-status').text('Waiting on device to connect...'); - - } else { - noty({ - text: 'Remote Session endpoint connection Failed!', - type: 'error' - }); - $('#btn-connect-device').removeClass('hidden'); - $('#loading-remote-session').addClass('hidden'); - } -} - - -$("#shell-command").keyup(function(event) { - if (event.keyCode == 13) { - var message = new Object(); - message.code = "REMOTE_SHELL"; - message.payload = $("#shell-command").val(); - - - // Send the message through the WebSocket. - rs_websocket.send(JSON.stringify(message)); - - // Clear out the message field. - $("#shell-command").val(""); - $("#shell-response").val(""); - $('#loading-terminal').removeClass('hidden'); - } -}); - - -$("#btn-start-screen").click(function() { - - canRemotelyControl = true; - $('#loading-screen').removeClass('hidden'); - $('#btn-start-screen').addClass('hidden'); - $('#remote-control-pannel').removeClass('hidden'); - $('#btn-stop-screen').removeClass('hidden'); - var message = new Object(); - var input = new Object(); - input.action = "start"; - input.height = 768; - input.width = 1024; - message.code = "REMOTE_SCREEN"; - message.payload = JSON.stringify(input); - // Send the message through the WebSocket. - rs_websocket.send(JSON.stringify(message)); -}); - - -$("#btn-stop-screen").click(function() { - - canRemotelyControl = false; - var canvas = document.getElementById("canvas"); - var ctx = canvas.getContext('2d'); - ctx.clearRect(0, 0, canvas.width, canvas.height); - $('#loading-screen').addClass('hidden'); - $('#remote-control-pannel').addClass('hidden'); - $('#btn-stop-screen').addClass('hidden'); - $('#btn-start-screen').removeClass('hidden'); - var message = new Object(); - var input = new Object(); - input.action = "stop"; - message.code = "REMOTE_SCREEN"; - message.payload = JSON.stringify(input); - // Send the message through the WebSocket. - rs_websocket.send(JSON.stringify(message)); -}); - - -$(function() { - var lastDuration = 0; - var minDuration = 50; - var durationDiff = 0; - var status = "ready"; - var bounds, x, y; - //Enable swiping... - $("#canvas").swipe({ - swipeStatus: function(event, phase, direction, distance, duration, fingers, fingerData, currentDirection) { - - if (canRemotelyControl) { - bounds = event.target.getBoundingClientRect(); - x = event.clientX - bounds.left; - y = event.clientY - bounds.top; - durationDiff = duration - lastDuration; - if (x < 0 || y < 0 || status == "blocked") { - return; - } - var inputMessage = new Object(); - var input = new Object(); - input.x = x / bounds.width; - input.y = y / bounds.height; - input.duration = durationDiff; - inputMessage.code = "REMOTE_INPUT"; - - if (status == "ready" && phase == "start") { - input.action = "down"; - inputMessage.payload = JSON.stringify(input); - rs_websocket.send(JSON.stringify(inputMessage)); - status = "unblocked"; - } else if (status == "unblocked") { - if (phase == "move") { - if (durationDiff < minDuration) { - return; - } else { - input.action = "move"; - inputMessage.payload = JSON.stringify(input); - rs_websocket.send(JSON.stringify(inputMessage)); - lastDuration = duration; - } - } else { - input.action = "up"; - lastDuration = 0; - status = "blocked"; - if (durationDiff < minDuration) { - setTimeout(function() { - inputMessage.payload = JSON.stringify(input); - rs_websocket.send(JSON.stringify(inputMessage)); - status = "ready"; - }, minDuration); - } else { - inputMessage.payload = JSON.stringify(input); - rs_websocket.send(JSON.stringify(inputMessage)); - status = "ready"; - } - } - - } - - } - - }, - threshold: 200, - maxTimeThreshold: 5000, - fingers: 'all' - }); -});; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/public/js/operation-bar.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/public/js/operation-bar.js index f25c05693..89f8e7f7a 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/public/js/operation-bar.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/public/js/operation-bar.js @@ -363,7 +363,6 @@ var generatePayload = function (operationCode, operationData, deviceList) { "DISALLOW_AUTOFILL": operationData["disallowAutoFill"], "DISALLOW_BLUETOOTH": operationData["disallowBluetooth"], "DISALLOW_BLUETOOTH_SHARING": operationData["disallowBluetoothSharing"], - "DISALLOW_REMOVE_USER": operationData["disallowRemoveUser"], "DISALLOW_DATA_ROAMING": operationData["disallowDataRoaming"] } }; @@ -601,6 +600,5 @@ var androidOperationConstants = { "DISALLOW_AUTOFILL": "DISALLOW_AUTOFILL", "DISALLOW_BLUETOOTH": "DISALLOW_BLUETOOTH", "DISALLOW_BLUETOOTH_SHARING": "DISALLOW_BLUETOOTH_SHARING", - "DISALLOW_REMOVE_USER": "DISALLOW_REMOVE_USER", "DISALLOW_DATA_ROAMING": "DISALLOW_DATA_ROAMING" }; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/public/templates/operation-bar.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/public/templates/operation-bar.hbs deleted file mode 100644 index c76e48859..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/public/templates/operation-bar.hbs +++ /dev/null @@ -1,186 +0,0 @@ -{{! - Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - - Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - Version 2.0 (the "License"); you may not use this file except - in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -}} -{{#if controlOperations}} -
    - - {{#each controlOperations}} - - {{#if iconFont}} - - {{else}} - {{#if icon}} - - {{else}} - - {{/if}} - {{/if}} - {{name}} - - -
    -
    - -
    -
    -

    - - - - - {{name}} -
    -

    -

    - {{description}} -
    -

    - - - - - -
    -
    - {{#each params.0.pathParams}} - -
    - {{/each}} - {{#each params.0.formParams}} - -
    - {{/each}} - {{#each params.0.queryParams}} - -
    - {{/each}} - {{#each uiParams}} - {{#equal this.type "select"}} -
    - -
    - {{/equal}} - {{#equal this.type "radio"}} - - {{this.value}} - {{/equal}} - {{#equal this.type "checkbox"}} - - {{this.label}} -
    - {{/equal}} - {{#equal this.type "password"}} - -
    - {{/equal}} - {{#equal this.type "text"}} - -
    - {{/equal}} - {{#equal this.type "info"}} -
    - - {{this.value}} - -
    - {{/equal}} - {{/each}} - - - - -
    -
    -
    -
    -
    -
    - {{/each}} -
    -{{/if}} - - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/configuration.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/configuration.hbs index e278056b9..f264830e8 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/configuration.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/configuration.hbs @@ -17,11 +17,6 @@ }}
    -
    {{#zone "bottomJs"}} {{js "js/platform-configuration.js"}} -{{/zone}} \ No newline at end of file +{{/zone}} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/public/js/platform-configuration.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/public/js/platform-configuration.js index b14da8670..5d75b35d9 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/public/js/platform-configuration.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.platform.configuration/public/js/platform-configuration.js @@ -80,32 +80,10 @@ var configParams = { "IOS_CONFIG_APNS_MODE": "iOSConfigAPNSMode" }; -var kioskConfigs = { - "adminComponentName" : "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME", - "wifiSSID" : "android.app.extra.PROVISIONING_WIFI_SSID", - "wifiPassword" : "android.app.extra.PROVISIONING_WIFI_PASSWORD", - "wifiSecurity" : "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE", - "skipEncryption" : "android.app.extra.PROVISIONING_SKIP_ENCRYPTION", - "checksum" : "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM", - "downloadURL" : "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION", - "defaultOwnership" : "android.app.extra.defaultOwner", - "serverIP" : "android.app.extra.serverIp" -}; - -function getParameterByName(name, url) { - if (!url) url = window.location.href; - name = name.replace(/[\[\]]/g, '\\$&'); - var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), - results = regex.exec(url); - if (!results) return null; - if (!results[2]) return ''; - return decodeURIComponent(results[2].replace(/\+/g, ' ')); -} - $(document).ready(function () { $("#fcm-inputs").hide(); tinymce.init({ - selector: "#android-eula", + selector: "textarea", height:500, theme: "modern", plugins: [ @@ -119,12 +97,6 @@ $(document).ready(function () { var androidConfigAPI = "/api/device-mgt/android/v1.0/configuration"; - var enterpriseSuccess = getParameterByName('enterprise-success'); - if (enterpriseSuccess) { - $("#config-save-form").addClass("hidden"); - $("#record-created-msg").removeClass("hidden"); - } - /** * Following requests would execute * on page load event of platform configuration page in WSO2 EMM Console. @@ -139,45 +111,22 @@ $(document).ready(function () { if (data != null && data.configuration != null) { for (var i = 0; i < data.configuration.length; i++) { var config = data.configuration[i]; - if (config.name === configParams["NOTIFIER_TYPE"]) { + if (config.name == configParams["NOTIFIER_TYPE"]) { $("#android-config-notifier").val(config.value); - if (config.value !== notifierTypeConstants["FCM"]) { + if (config.value != notifierTypeConstants["FCM"]) { $("#fcm-inputs").hide(); $("#local-inputs").show(); } else { $("#fcm-inputs").show(); $("#local-inputs").hide(); } - } else if (config.name === configParams["NOTIFIER_FREQUENCY"]) { + } else if (config.name == configParams["NOTIFIER_FREQUENCY"]) { $("input#android-config-notifier-frequency").val(config.value / 1000); - } else if (config.name === configParams["FCM_API_KEY"]) { + } else if (config.name == configParams["FCM_API_KEY"]) { $("input#android-config-fcm-api-key").val(config.value); - } else if (config.name === configParams["ANDROID_EULA"]) { + } else if (config.name == configParams["ANDROID_EULA"]) { $("#android-eula").val(config.value); - } else if (config.name === kioskConfigs["adminComponentName"]) { - $("input#android-kiosk-config-admin-component").val(config.value); - } else if (config.name === kioskConfigs["wifiSSID"]) { - $("input#android-kiosk-config-wifi-ssid").val(config.value); - } else if (config.name === kioskConfigs["wifiSecurity"]) { - $("#android-kiosk-config-wifi-sec").val(config.value); - } else if (config.name === kioskConfigs["wifiPassword"]) { - $("input#android-kiosk-config-wifi-password").val(config.value); - } else if (config.name === kioskConfigs["checksum"]) { - $("input#android-kiosk-config-checksum").val(config.value); - } else if (config.name === kioskConfigs["downloadURL"]) { - $("input#android-kiosk-config-download-url").val(config.value); - } else if (config.name === kioskConfigs["skipEncryption"]) { - $("#android-kiosk-config-encryption").val(config.value); - } else if (config.name === "esa") { - $("#afw-esa").val(config.value); - } else if (config.name === "enterpriseId") { - $("#afw-enterprise-id").val(config.value); - } else if (config.name === kioskConfigs["defaultOwnership"]) { - $("#android-kiosk-config-defaultOwner").val(config.value); - } else if (config.name === kioskConfigs["serverIP"]) { - $("#android-kiosk-config-server-ip").val(config.value); } - } } }, function (data) { @@ -212,27 +161,13 @@ $(document).ready(function () { var androidLicense = tinyMCE.activeEditor.getContent(); var errorMsgWrapper = "#android-config-error-msg"; var errorMsg = "#android-config-error-msg span"; - var esa = $("input#afw-esa").val(); - var enterpriseId = $("input#afw-enterprise-id").val(); - - // KIOSK configs - var adminComponentName = $("input#android-kiosk-config-admin-component").val(); - var checksum = $("input#android-kiosk-config-checksum").val(); - var downloadUrl = $("input#android-kiosk-config-download-url").val(); - var wifiSSID = $("input#android-kiosk-config-wifi-ssid").val(); - var wifiPassword = $("input#android-kiosk-config-wifi-password").val(); - var encryption = $("#android-kiosk-config-encryption").find("option:selected").attr("value"); - var wifiSecurity = $("#android-kiosk-config-wifi-sec").find("option:selected").attr("value"); - var defaultOwner = $("#android-kiosk-config-defaultOwner").find("option:selected").attr("value"); - var serverIp = $("#android-kiosk-config-server-ip").val(); - - if (notifierType === notifierTypeConstants["LOCAL"] && !notifierFrequency) { + if (notifierType == notifierTypeConstants["LOCAL"] && !notifierFrequency) { $(errorMsg).text("Notifier frequency is a required field. It cannot be empty."); $(errorMsgWrapper).removeClass("hidden"); - } else if (notifierType === notifierTypeConstants["LOCAL"] && !isPositiveInteger(notifierFrequency)) { + } else if (notifierType == notifierTypeConstants["LOCAL"] && !isPositiveInteger(notifierFrequency)) { $(errorMsg).text("Provided notifier frequency is invalid. "); $(errorMsgWrapper).removeClass("hidden"); - } else if (notifierType === notifierTypeConstants["FCM"] && !fcmAPIKey) { + } else if (notifierType == notifierTypeConstants["FCM"] && !fcmAPIKey) { $(errorMsg).text("FCM API Key is a required field. It cannot be empty."); $(errorMsgWrapper).removeClass("hidden"); } else { @@ -270,89 +205,10 @@ $(document).ready(function () { "contentType": "text" }; - var kioskAdminComponent = { - "name": kioskConfigs["adminComponentName"], - "value": adminComponentName, - "contentType": "text" - }; - - var kioskChecksum = { - "name": kioskConfigs["checksum"], - "value": checksum, - "contentType": "text" - }; - - var kioskDownloadURL = { - "name": kioskConfigs["downloadURL"], - "value": downloadUrl, - "contentType": "text" - }; - - var kioskWifiSSID = { - "name": kioskConfigs["wifiSSID"], - "value": wifiSSID, - "contentType": "text" - }; - - var kioskWifiSecurity = { - "name": kioskConfigs["wifiSecurity"], - "value": wifiSecurity, - "contentType": "text" - }; - - var kioskWifiPassword = { - "name": kioskConfigs["wifiPassword"], - "value": wifiPassword, - "contentType": "text" - }; - - var kioskEncryption = { - "name": kioskConfigs["skipEncryption"], - "value": encryption, - "contentType": "text" - }; - - var esa = { - "name": "esa", - "value": esa, - "contentType": "text" - }; - - var enterpriseId = { - "name": "enterpriseId", - "value": enterpriseId, - "contentType": "text" - }; - - var kioskDefaultOwner = { - "name": kioskConfigs["defaultOwnership"], - "value": defaultOwner, - "contentType": "text" - }; - - var kioskServerIp = { - "name": kioskConfigs["serverIP"], - "value": serverIp, - "contentType": "text" - }; - configList.push(type); configList.push(frequency); configList.push(androidEula); - - configList.push(kioskAdminComponent); - configList.push(kioskChecksum); - configList.push(kioskDownloadURL); - configList.push(kioskEncryption); - configList.push(kioskWifiSSID); - configList.push(kioskWifiPassword); - configList.push(kioskWifiSecurity); - configList.push(esa); - configList.push(enterpriseId); - configList.push(kioskDefaultOwner); - configList.push(kioskServerIp); - - if (notifierType === notifierTypeConstants["FCM"]) { + if (notifierType == notifierTypeConstants["FCM"]) { configList.push(fcmKey); configList.push(fcmId); } @@ -378,137 +234,8 @@ $(document).ready(function () { $(errorMsg).text("An unexpected error occurred."); } $(errorMsgWrapper).removeClass("hidden"); - $(window).scrollTop(0); } ); } }); - - function getSignupUrl(serverUrl, emmToken) { - - var appContext = window.location.href;// mgt:9443 call to jaggery API - var tokenURL = appContext.replace("platform-configuration", "api/enterprise/token"); - var callbackURL = appContext.replace("platform-configuration", "api/enterprise/enroll-complete"); - - var requestData = {}; - requestData.externalToken = emmToken; - requestData.endpoint = serverUrl + "/api/android-for-work/v1.0/google/enterprise/signup-url"; - requestData.callbackURL = callbackURL; - - $.ajax({ - type: "POST", - url: tokenURL, - data: JSON.stringify(requestData), - contentType: "application/json", - success: function(response) { - window.location.replace(response.signupURL); - }, - error: function(data) { - var errorMsgWrapper = "#android-config-error-msg"; - var errorMsg = "#android-config-error-msg span"; - if (data.status == 500) { - $(errorMsg).text("Exception occurred at backend."); - } else if (data.status == 403) { - $(errorMsg).text("Action was not permitted."); - } else { - $(errorMsg).text("An unexpected error occurred."); - } - $(errorMsgWrapper).removeClass("hidden"); - $(window).scrollTop(0); - }, - dataType: 'json' - }); - } - - $("button#afw-configure").click(function() { - var serverDetails = $("input#afw-server-details").val(); - var emmToken = $("input#afw-backend-token").val(); - getSignupUrl(serverDetails, emmToken) - }); - - - var modalPopup = ".modal"; - var modalPopupContainer = modalPopup + " .modal-content"; - var modalPopupContent = modalPopup + " .modal-content"; - var body = "body"; - - function unenroll(serverUrl, emmToken) { - - var appContext = window.location.href; - var unenrollURL = appContext.replace("platform-configuration", "api/enterprise/unenroll"); - - var requestData = {}; - requestData.externalToken = emmToken; - requestData.endpoint = serverUrl; - - $.ajax({ - type: "PUT", - url: unenrollURL, - data: JSON.stringify(requestData), - contentType: "application/json", - success: function(response) { - $("input#afw-server-details").val("") ; - $("input#afw-backend-token").val(""); - $("input#afw-esa").val(""); - $("input#afw-enterprise-id").val(""); - }, - error: function(data) { - var errorMsgWrapper = "#android-config-error-msg"; - var errorMsg = "#android-config-error-msg span"; - if (data.status == 200) { - $(errorMsg).text("hari."); - } - else if (data.status == 500) { - $(errorMsg).text("Exception occurred at backend."); - } else if (data.status == 403) { - $(errorMsg).text("Action was not permitted."); - } else { - $(errorMsg).text("An unexpected error occurred."); - } - $(errorMsgWrapper).removeClass("hidden"); - $(window).scrollTop(0); - }, - dataType: 'text' - }); - } - - - $("button#afw-unenroll").click(function() { - - $(modalPopupContent).html($('#remove-unenroll-modal-content').html()); - showPopup(); - - $("a#remove-unenroll-yes-link").click(function () { - var serverDetails = $("input#afw-server-details").val() - + "/api/android-for-work/v1.0/google/enterprise/unenroll/" + $("input#afw-enterprise-id").val(); - var emmToken = $("input#afw-backend-token").val(); - unenroll(serverDetails, emmToken); - hidePopup(); - }); - - $("a#remove-unenroll-cancel-link").click(function () { - hidePopup(); - }); - - }); - - /* - * show popup function. - */ - function showPopup() { - $(modalPopup).modal('show'); - } - - /* - * hide popup function. - */ - function hidePopup() { - $(modalPopupContent).html(""); - $(modalPopupContent).removeClass("operation-data"); - $(modalPopup).modal('hide'); - $('body').removeClass('modal-open').css('padding-right', '0px'); - $('.modal-backdrop').remove(); - } - - -}); +}); \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-edit/public/templates/android-policy-edit.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-edit/public/templates/android-policy-edit.hbs index 838369bb9..58f1b9fcb 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-edit/public/templates/android-policy-edit.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-edit/public/templates/android-policy-edit.hbs @@ -56,17 +56,6 @@ - - - - - Global Proxy Settings - - - - @@ -75,24 +64,6 @@ - - - - - - Access Point Name - - - - - - - - - Certificates Install - - - {{#unless iscloud}} @@ -161,39 +132,6 @@ class="fw fw-error"> {{/unless}} - - - - - Enrollment Application Install - - - - - - - - - - Display Message Configuration - - - - - - - - - - App Usage Time Configuration - - - - -
    @@ -325,192 +263,27 @@
    - - -
    - -
    -
    - -
    - - -
    - - -

    Passcode policy for work profile

    -
    - -
    - @@ -562,7 +335,6 @@ work-profile owner or device owner. -
    -
    - -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    +
      @@ -802,7 +481,6 @@ device owner.
    -
    -
    -
    -
    -
    - -
    -
    -
    - -
    -
    +
    {{/unless}} @@ -1282,149 +934,12 @@ -
    - -
    - -
    -
    - -
    -
    - -
    - -
    - Please note that * sign represents required fields of data. -
    -
    - - -
    - - -
    -
    -
    - - -
    -
    - - - -
    -
    - - -
    -
    - -
    -
    -
    - -
    - Configure the OpenVPN settings on Android devices. - In order to enable this, device needs to have "OpenVPN for Android" application installed. + This configurations can be used to configure VPN settings on an Android device. + Once this configuration profile is installed on a device, corresponding users will not be able + to modify these settings on their devices.

    + Please note that * sign represents required fields of data. +

    -
    -
    -
    - - - - - -
    -
    - - -
    -
    -
    +
    + +
    - - - - - - - - - - - - -
    - -
    - -
    -
    - -
    -
    - Please note that * sign represents required fields of data. -
    -
    - -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - -
    - -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - -
    - -
    - - -
    -
    -
    -
    - - - -
    -
    - -
    -
    - - -
    - -
    - - - - - - - Add Certificate - -
    - - - - - - - - - - - - - - -
    No:Certificate NameCertificate File
    - No entries added yet . -
    - - - - - - - - - - -
    -
    -
    -
    -
    - -
    -

    -
    - -
    -
    - -
    -
    - - - - -
    - - - - - - - - - - - - {{#each storeapps}} - - - - - - - - {{else}} - - - - - - - - {{/each}} - -
    Application NameTypeVersionAuto InstallWork Profile Availability
    - {{this.appName}} - - - {{this.type}} - - - {{this.version}} - - - - - - - - - - - -
    No android apps available in the store.
    - - -
    - -
    -

    -

    Work profile global user configurations

    -
    - - -
    - -
    - - -
    -
    -
    -
    -
    - - - -
    -
    - -
    -
    -
    - -
    - -
    - Below lock screen message is valid only when the Agent is the - device owner. -
    - -

    - - -

    - - -
    -
    -
    -
    - - - -
    -
    - -
    -
    -
    -
    -
      - - This policy works only for Android 5.1 (Lolipop) or later versions. -
    -

    -
    - -{{!--
    --}} -{{!--
    --}} -{{!--
    --}} -{{!-- --}} -{{!-- --}} -{{!--
    --}} -{{!--
    --}} -{{!--
    --}} -
    - -
    - - - - - - Add Application - -
    - - - - - - - - - - - - - - - - - -
    No:Package NameAllowed Time TypeAllowed TimePeriod Time TypePeriod Time
    - No entries added yet . -
    - - - - - - - - - - - - - -
    -
    -
    -
    -
    -
    -
    - - -
    - - \ No newline at end of file + diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-view/public/templates/android-policy-view.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-view/public/templates/android-policy-view.hbs index ae3bfc105..91fffa49d 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-view/public/templates/android-policy-view.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-view/public/templates/android-policy-view.hbs @@ -39,17 +39,6 @@ - - - - - Global Proxy Settings - - - - @@ -59,27 +48,6 @@ - - - - - - Access Point Name - - - - - - - - - - Certificate Install - - - - - {{#unless iscloud}} @@ -89,16 +57,6 @@ - - - - - COSU Profile Configurations - - - - @@ -110,41 +68,6 @@ - - - - - - Runtime Permission Policy (COSU) - - - - - - - - - System Update Policy (COSU) - - - - - - - - - Whitelist Apps (COSU) - - - - - {{/unless}} @@ -155,29 +78,6 @@ - - - - - - Display Message Configuration - - - - - - - - - - App Usage Time Configuration - - - - -
    @@ -309,193 +209,27 @@
    - - -
    - -
    -
    - -
    - - -
    - - -

    Passcode policy for work profile

    -
    - -
    - @@ -541,7 +275,6 @@ - {{#unless iscloud}}
    Bellow restrictions will be applied on devices with Android version 5.0 Lollipop onwards only @@ -938,147 +671,7 @@ -
    -
    - - Bellow restrictions will be applied on devices with Android version 6.0 Marshmallow onwards - only. - -

    -
    - -
    - -
    -
    - -
    -
    - -
    - -
    -
    - -
    - -
    -
    - -
    - -
    -
    - -
    - -
    -
    - -
    - -
    -
    - -
    - -
    -
    - -
    - -
    - -
    - -
    -
    - {{/unless}} @@ -1291,465 +884,12 @@ -
    - -
    - -
    -
    - -
    -
    - -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - -
    - -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - -
    - -
    - - -
    -
    -
    -
    - - - -
    -
    - -
    -
    - -
    - -
    - Please note that * sign represents required fields of data. -
    -
    - - -
    - - -
    -
    -
    - - -
    -
    - - - -
    -
    - - -
    -
    -
    -
    - - -
    -
    -
    -
    -
    - -

    -
    - -
    -
    - -
    -
    - - -
    - -
    - -
    - - - - - - - - - - - - - - -
    No:Certificate NameCertificate File
    - No entries added yet . -
    - - - - - - - - - - -
    -
    -
    -
    -
    - - @@ -3580,278 +1854,5 @@
    - -
    -
    - -
    -
    - - - - -
    - - - - - - - - - - - - -
    Application NameTypeVersionAuto InstallWork Profile Availability
    -
    -
    -
    -
    - - - -
    -
    - -
    -
    -
    - -
    - Below lock screen message is valid only when the Agent is the - device owner. -
    - -

    - - -

    - - -
    -
    -
    -
    - - - -
    -
    - -
    -
    -
    -
    -
      - - This policy works only for Android 5.1 (Lolipop) or later versions. -
    -

    -
    - -{{!--
    --}} -{{!--
    --}} -{{!--
    --}} -{{!-- --}} -{{!-- --}} -{{!--
    --}} -{{!--
    --}} -{{!--
    --}} -
    - -
    - -
    - - - - - - - - - - - - - - - - - -
    No:Package NameAllowed Time TypeAllowed TimePeriod Time TypePeriod Time
    - No entries added yet . -
    - - - - - - - - - - - - - -
    -
    -
    -
    -
    - - - - + \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-wizard/public/templates/android-policy-operations.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-wizard/public/templates/android-policy-operations.hbs index 67eb789a9..2eaa2cafb 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-wizard/public/templates/android-policy-operations.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.policy-wizard/public/templates/android-policy-operations.hbs @@ -56,17 +56,6 @@ - - - - - Global Proxy Settings - - - - @@ -76,25 +65,6 @@ - - - - - Access Point Name - - - - - - - - - Certificate Install - - - - - {{#unless iscloud}} @@ -105,18 +75,6 @@ - - - - - COSU Profile Configurations - - - - @@ -129,80 +87,18 @@ class="fw fw-success"> - - - - - - Runtime Permission Policy - - - - - - System Update Policy (COSU) - - - - - - - - - Whitelist Apps (COSU) - - - - - {{/unless}} - - - - - Enrollment Application Install - - - - - - - - - Display Message Configuration - - - - - - - - - - App Usage Time Configuration - - - - - - +
    @@ -236,7 +132,7 @@
    -
    maximumNumberOfFailedAttemptsBeforeDeviceLock - - -
    -
    -
    - -
    - - -
    - - -

    Passcode policy for work profile

    -
    - -
    - -
    @@ -560,12 +291,11 @@
    - {{#unless iscloud}}
    @@ -711,384 +441,6 @@
    -
    - -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    - -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    - -
    -
    - -
    -
    -
    - -
    -
    -
    - -
    -
    - {{/unless}} @@ -1141,324 +493,6 @@ - - -
    -
    - -
    -
    - Please note that * sign represents required fields of data. -
    -
    - -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - - -
    -
    - - -
    - -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - -
    - -
    - - -
    -
    -
    -
    - -
    @@ -1619,149 +653,12 @@
    -
    - -
    - -
    -
    - -
    -
    - -
    - -
    - Please note that * sign represents required fields of data. -
    -
    - - -
    - - -
    -
    -
    - - -
    -
    - - - -
    -
    - - -
    -
    - -
    -
    -
    - -
    - -
    -
    - -
    -
    - -
    -
    -
    -

    - Restrict Device Operation Time - -

    -
    -
    -
    - - -
    -
    - - -
    - -
    -
    -
    -
    -
    -
    -

    - Device Global Configuration - -

    -
    -
    - -
    - - -
    -
    - - -
    -
    - - -
    - -
    -
    - Is single application mode - - -
    - -
    - -
    -
    - Is idle media enabled - - -
    - -
    - -
    -
    - Keep display awake - - -
    -
    - -
    -
    - Is multi-user device - - -
    - -
    - -
    - - -
    -
    -
    - Enable Browser Properties - - -
    -
    -
    - - -
    -
    - -
    -
    - -
    -
    - -
    -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    - -
    -
    - - -
    - -
    - - -
    - -
    - -
    -
    - -
    -
    - -
    -
    - -
    -
    - -
    -
    - - -
    - -
    - - -
    -
    - - -
    - -
    - -
    -
    - -
    -
    - -
    -
    - -
    -
    - -
    -
    - -
    -
    - -
    - -
    - - -
    - -
    - - -
    -
    -
    - - -
    - -
    -
    -
    -
    - -

    @@ -2871,19 +854,6 @@
    - - - - - - - - - - - - -
    @@ -2891,108 +861,6 @@
    - -
    -
    - -
    -
    - - -
    - -
    - - - - - - - Add Certificate - -
    - - - - - - - - - - - - - - -
    No:Certificate NameCertificate File
    - No entries added yet . -
    - - - - - - - - - - -
    -
    -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    - - - -
    - -
    - - - - - - Add Application - -
    - - - - - - - - - - - - - - - - -
    No:ApplicationPackage NamePermission NamePermission Type
    - No entries added yet . -
    - - - - - - - - - - - - -
    -
    -
    -
    -
    -
      - - Already granted or denied permissions are not affected by this policy. -
      - - Permissions can be granted or revoked only for applications built with a Target SDK Version - of Android Marshmallow or later. -
    -
    -
    -
    -
    - - -
    -
    - -
    -
    - -
    - -

    - - - -
    -
    - -
    - - -
    -
    - - -
    -
    -
    -
    -
    - -
    -
    - -
    -
    - - -
    - -
    - - - - - - - - - - - - - - -
    No:Application Name / DescriptionPackage Name
    - No entries added yet. -
    - - - - - - - - - - -
    -
    -
    -
    -
    - -
    - -
    -
    - -
    -
    -
    - -
    - -
    - Below lock screen message is valid only when the Agent is the - device owner. -
    - -

    - - -

    - - -
    -
    -
    -
    - - - -
    -
    - -
    -
    -
    -
    -
      - - This policy works only for Android 5.1 (Lolipop) or later versions. -
    -

    -
    - -{{!--
    --}} -{{!--
    --}} -{{!--
    --}} -{{!-- --}} -{{!-- --}} -{{!--
    --}} -{{!--
    --}} -{{!--
    --}} -
    - -
    - - - - - - Add Application - -
    - - - - - - - - - - - - - - - - - -
    No:Package NameAllowed Time TypeAllowed TimePeriod Time TypePeriod Time
    - No entries added yet . -
    - - - - - - - - - - - - - -
    -
    -
    -
    -
    -
    -
    - -
    -
    +
    \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/private/config.json b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/private/config.json index 17511f509..e6ab55c5d 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/private/config.json +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/private/config.json @@ -13,7 +13,6 @@ "perm:android:lock-devices", "perm:android:configure-vpn", "perm:android:configure-wifi", - "perm:android:configure-global-proxy", "perm:android:enroll", "perm:android:uninstall-application", "perm:android:manage-configuration", @@ -36,9 +35,7 @@ "perm:android:unlock-devices", "perm:android:control-camera", "perm:android:reboot", - "perm:android:change-LockTask", - "perm:android:logcat", - "perm:android:send-app-restrictions" + "perm:android:logcat" ], "features": { "DEVICE_RING": { @@ -75,11 +72,6 @@ "filter" : {"property" : "ownership", "value" : "COPE", "text": "This feature is only available in COPE/COSU"}, "permission": "/device-mgt/devices/owning-device/operations/android/reboot" }, - "CHANGE_LOCK_TASK_MODE": { - "icon": "fw-mobile", - "filter" : {"property" : "ownership", "value" : "COPE", "text": "This feature is only available in COSU(KIOSK)"}, - "permission": "/device-mgt/devices/owning-device/operations/android/change-LockTask" - }, "UPGRADE_FIRMWARE": { "icon": "fw-hardware", "filter" : {"property" : "ownership", "value" : "COPE", "text": "This feature is only available in COPE/COSU"}, @@ -221,24 +213,6 @@ } ], "permission": "/device-mgt/devices/owning-device/operations/android/wipe" - }, - "REMOTE_APP_CONFIG": { - "icon": "fw-lock", - "formParams": [ - { - "type": "text", - "id": "app-id", - "optional": false, - "label": "Application identifier" - }, - { - "type": "text", - "id": "payload", - "optional": false, - "label": "Application restriction payload" - } - ], - "permission": "/device-mgt/devices/owning-device/operations/android/send-app-conf" } } } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/assets/.gitignore b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/assets/.gitignore deleted file mode 100644 index e69de29bb..000000000 diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/css/styles.css b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/css/styles.css index 811c4137d..a23eed95a 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/css/styles.css +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/css/styles.css @@ -59,7 +59,7 @@ hr { color: #006eff; } .enrollment-qr-container canvas { - width: 15%; + width: 14%; } @media (min-width:992px){ diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/images/application.svg b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/images/application.svg deleted file mode 100644 index fbef3182c..000000000 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/images/application.svg +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/js/type-view.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/js/type-view.js index 89c474f58..6375247c8 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/js/type-view.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/js/type-view.js @@ -31,20 +31,6 @@ var backendEndBasePath = "/api/device-mgt/v1.0"; // }); //} -var kioskConfigs = { - "adminComponentName": "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME", - "wifiSSID": "android.app.extra.PROVISIONING_WIFI_SSID", - "wifiPassword": "android.app.extra.PROVISIONING_WIFI_PASSWORD", - "wifiSecurity": "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE", - "skipEncryption": "android.app.extra.PROVISIONING_SKIP_ENCRYPTION", - "checksum": "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM", - "downloadURL": "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION", - "androidExtra": "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE", - "accessToken": "android.app.extra.token", - "defaultOwnership": "android.app.extra.defaultOwner", - "serverIp": "android.app.extra.serverIp" -}; - /* * set popup maximum height function. */ @@ -70,143 +56,29 @@ function hidePopup() { $(modalPopupContent).html(""); $(modalPopupContent).removeClass("operation-data"); $(modalPopup).modal('hide'); - $('body').removeClass('modal-open').css('padding-right', '0px'); + $('body').removeClass('modal-open').css('padding-right','0px'); $('.modal-backdrop').remove(); } /* * QR-code generation function. */ -function generateQRCode() { +function generateQRCode(qrCodeClass) { var enrollmentURL = $("#qr-code-modal").data("enrollment-url"); $(qrCodeClass).qrcode({ text: enrollmentURL, - width: 150, - height: 150 + width: 200, + height: 200 }); } -/* - * QR-code generation function for KIOSK. - */ -function generateKIOSKQRCode(qrCodeClass) { - - var payload = {}; - var androidConfigAPI = "/api/device-mgt/android/v1.0/configuration"; - - var isKioskConfigured = false; - var defaultOwnerVal = {}; - var serverIp = {}; - $("#android-qr-code").show(); - $("#enrollment_qr_content").show(); - $("#qr-code-img").hide(); - $("#enroll-qr-heading").show(); - var ownership_type = $("#android-device-ownership").find("option:selected").attr("value"); - - invokerUtil.get( - androidConfigAPI, - function(data) { - data = JSON.parse(data); - if (data != null && data.configuration != null) { - if (ownership_type == "COSU" || ownership_type == "COPE") { - for (var i = 0; i < data.configuration.length; i++) { - var config = data.configuration[i]; - if (config.name === kioskConfigs["adminComponentName"]) { - isKioskConfigured = true; - payload[config.name] = config.value; - } else if (config.name === kioskConfigs["wifiSSID"]) { - payload[config.name] = config.value; - } else if (config.name === kioskConfigs["wifiPassword"]) { - payload[config.name] = config.value; - } else if (config.name === kioskConfigs["wifiSecurity"]) { - payload[config.name] = config.value; - } else if (config.name === kioskConfigs["checksum"]) { - payload[config.name] = config.value; - } else if (config.name === kioskConfigs["downloadURL"]) { - payload[config.name] = config.value; - } else if (config.name === kioskConfigs["skipEncryption"]) { - payload[config.name] = Boolean(config.value); - } else if (config.name === kioskConfigs["defaultOwnership"]) { - defaultOwnerVal[config.name] = ownership_type; - } else if (config.name === kioskConfigs["serverIp"]) { - serverIp[config.name] = config.value; - } - } - } else { - for (var i = 0; i < data.configuration.length; i++) { - var config = data.configuration[i]; - if (config.name === kioskConfigs["adminComponentName"]) { - isKioskConfigured = true; - payload[config.name] = config.value; - } else if (config.name === kioskConfigs["defaultOwnership"]) { - defaultOwnerVal[config.name] = ownership_type; - } else if (config.name === kioskConfigs["serverIp"]) { - serverIp[config.name] = config.value; - } - } - } - } - }, - function(data) { - console.log(data); - }); - - var aToken = $(".a-token"); - var tokenPair = aToken.data("atoken"); - - var accessToken = {}; - accessToken[kioskConfigs["accessToken"]] = tokenPair["accessToken"]; - var sumExtra = $.extend(accessToken, defaultOwnerVal, serverIp); - payload[kioskConfigs["androidExtra"]] = sumExtra; - $(".kiosk-enrollment-qr-container").empty(); - if (isKioskConfigured) { - $(qrCodeClass).qrcode({ - text: JSON.stringify(payload), - width: 350, - height: 350 - }); - } else { - $("#android-configurations-alert").fadeToggle(500); - $("#kiosk_content").hide(); - } -} - -function displayAgentDownloadQR() { - $(".enrollment-qr-container").empty(); - generateQRCode(".enrollment-qr-container"); - $("#download-agent-qr").fadeToggle(1000); - $("#enroll-agent-qr").fadeOut(1000); - $("#android-enroll-manually-instructions").fadeOut(1000); - $('html,body').animate({ - scrollTop: $('#download-agent-qr').position().top - }, 800); -} - -function displayEnrollmentQR() { - $("#download-agent-qr").fadeOut(1000); - $("#enroll-agent-qr").fadeToggle(1000); - $("#android-enroll-manually-instructions").fadeOut(1000); - $('html,body').animate({ - scrollTop: $('#enroll-agent-qr').position().top - }, 800); -} - -function manualEnrollmentGuide() { - $("#enroll-agent-qr").fadeOut(1000); - $("#download-agent-qr").fadeOut(1000); - $("#android-enroll-manually-instructions").fadeToggle(1000); - $('html,body').animate({ - scrollTop: $('#android-enroll-manually-instructions').position().top - }, 800); -} - function toggleEnrollment() { $(".modal-content").html($("#qr-code-modal").html()); generateQRCode(".modal-content .qr-code"); modalDialog.show(); } -var updateNotificationCountOnSuccess = function(data, textStatus, jqXHR) { +var updateNotificationCountOnSuccess = function (data, textStatus, jqXHR) { var notificationBubble = "#notification-bubble"; if (jqXHR.status == 200 && data) { var responsePayload = JSON.parse(data); @@ -244,12 +116,12 @@ function loadNewNotifications() { var notifications = $("#notifications"); var currentUser = notifications.data("currentUser"); - $.template("notification-listing", notifications.attr("src"), function(template) { + $.template("notification-listing", notifications.attr("src"), function (template) { var serviceURL = backendEndBasePath + "/notifications?offset=0&limit=5&status=NEW"; invokerUtil.get( serviceURL, // on success - function(data, textStatus, jqXHR) { + function (data, textStatus, jqXHR) { if (jqXHR.status == 200 && data) { var viewModel = {}; var responsePayload = JSON.parse(data); @@ -271,7 +143,7 @@ function loadNewNotifications() { } }, // on error - function(jqXHR) { + function (jqXHR) { if (jqXHR.status = 500) { $(messageSideBar).html("

    Unexpected error occurred while trying " + "to retrieve any new notifications.

    "); @@ -287,7 +159,7 @@ function loadNewNotifications() { * notification listing sidebar. * @return {Null} */ -$.sidebar_toggle = function(action, target, container) { +$.sidebar_toggle = function (action, target, container) { var elem = '[data-toggle=sidebar]', button, containerOffsetLeft, @@ -301,7 +173,7 @@ $.sidebar_toggle = function(action, target, container) { buttonParent; var sidebar_window = { - update: function(target, container, button) { + update: function (target, container, button) { containerOffsetLeft = $(container).data('offset-left') ? $(container).data('offset-left') : 0; containerOffsetRight = $(container).data('offset-right') ? $(container).data('offset-right') : 0; targetOffsetLeft = $(target).data('offset-left') ? $(target).data('offset-left') : 0; @@ -316,7 +188,7 @@ $.sidebar_toggle = function(action, target, container) { } }, - show: function() { + show: function () { if ($(target).data('sidebar-fixed') == true) { $(target).height($(window).height() - $(target).data('fixed-offset')); } @@ -360,7 +232,7 @@ $.sidebar_toggle = function(action, target, container) { $(target).trigger('shown.sidebar'); }, - hide: function() { + hide: function () { $(target).trigger('hide.sidebar'); $(target).removeClass('toggled'); if (button !== undefined) { @@ -407,7 +279,7 @@ $.sidebar_toggle = function(action, target, container) { // binding click function var body = 'body'; $(body).off('click', elem); - $(body).on('click', elem, function(e) { + $(body).on('click', elem, function (e) { e.preventDefault(); button = $(this); container = button.data('container'); @@ -425,41 +297,41 @@ $.sidebar_toggle = function(action, target, container) { }); }; -$.fn.collapse_nav_sub = function() { +$.fn.collapse_nav_sub = function () { var navSelector = 'ul.nav'; if (!$(navSelector).hasClass('collapse-nav-sub')) { - $(navSelector + ' > li', this).each(function() { + $(navSelector + ' > li', this).each(function () { var position = $(this).offset().left - $(this).parent().scrollLeft(); $(this).attr('data-absolute-position', (position + 5)); }); - $(navSelector + ' li', this).each(function() { + $(navSelector + ' li', this).each(function () { if ($('ul', this).length !== 0) { $(this).addClass('has-sub'); } }); - $(navSelector + ' > li', this).each(function() { + $(navSelector + ' > li', this).each(function () { $(this).css({ 'left': $(this).data('absolute-position'), 'position': 'absolute' }); }); - $(navSelector + ' li.has-sub', this).on('click', function() { + $(navSelector + ' li.has-sub', this).on('click', function () { var elem = $(this); if (elem.attr('aria-expanded') !== 'true') { - elem.siblings().fadeOut(100, function() { - elem.animate({ 'left': '15' }, 200, function() { + elem.siblings().fadeOut(100, function () { + elem.animate({'left': '15'}, 200, function () { $(elem).first().children('ul').fadeIn(200); }); }); elem.siblings().attr('aria-expanded', 'false'); elem.attr('aria-expanded', 'true'); } else { - $(elem).first().children('ul').fadeOut(100, function() { - elem.animate({ 'left': $(elem).data('absolute-position') }, 200, function() { + $(elem).first().children('ul').fadeOut(100, function () { + elem.animate({'left': $(elem).data('absolute-position')}, 200, function () { elem.siblings().fadeIn(100); }); }); @@ -468,24 +340,26 @@ $.fn.collapse_nav_sub = function() { } }); - $(navSelector + ' > li.has-sub ul', this).on('click', function(e) { + $(navSelector + ' > li.has-sub ul', this).on('click', function (e) { e.stopPropagation(); }); $(navSelector).addClass('collapse-nav-sub'); } }; -$(document).ready(function() { +$(document).ready(function () { $.sidebar_toggle(); + generateQRCode(".enrollment-qr-container"); + if (typeof $.fn.collapse == 'function') { - $('.navbar-collapse.tiles').on('shown.bs.collapse', function() { + $('.navbar-collapse.tiles').on('shown.bs.collapse', function () { $(this).collapse_nav_sub(); }); } loadNewNotificationsOnSideViewPanel(); - $("#right-sidebar").on("click", ".new-notification", function() { + $("#right-sidebar").on("click", ".new-notification", function () { var notificationId = $(this).data("id"); var redirectUrl = $(this).data("url"); var markAsReadNotificationsEpr = backendEndBasePath + "/notifications/" + notificationId + "/mark-checked"; @@ -495,14 +369,14 @@ $(document).ready(function() { markAsReadNotificationsEpr, null, // on success - function(data) { + function (data) { data = JSON.parse(data); if (data.statusCode == responseCodes["ACCEPTED"]) { location.href = redirectUrl; } }, // on error - function() { + function () { var content = "
  • Warning

    " + "

    Unexpected error occurred while loading notification. Please refresh the pa{{#if isCloud}}ge and" + " try again

  • "; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/type-view.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/type-view.hbs index 8f72feb66..01af00766 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/type-view.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/type-view.hbs @@ -1,152 +1,56 @@ - +{{unit "cdmf.unit.lib.qrcode"}} {{unit "cdmf.unit.device.type.qr-modal" enrollmentURL=enrollmentURL deviceTypeName="Android"}} +{{unit "cdmf.unit.device.type.email.invite-modal" deviceTypeView="android"}}
    {{#if isVirtual}}

    DOWNLOAD THE VIRTUAL ANDROID DEVICE

    {{else}} -

    ENROLL THE ANDROID AGENT

    +

    DOWNLOAD THE ANDROID AGENT

    {{/if}}
    -

    Step 01 - Get your Android Agent.

    -

    -

    The Android agent can be downloaded by 2 methods. - Either the generated QR code can be scanned, and the agent APK downloaded from the link, - or the agent APK can be manually downloaded via the "Download APK" button, transferred to - the device and then installed.

    -
    - -
    - - {{!-- Agent download qr class --}} - - -{{!-- Warning message --}} - - - +
    Step 2

    Tap Skip to proceed with the default enrollment process.

    - +
    Step 3

    Enter the server address based on your environment, in the text box provided.

    - +
    Step 4
    @@ -274,7 +181,7 @@
  • Password: Your password.
  • - +
    {{/if}} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/type-view.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/type-view.js index 8c872ae1a..8d0ff38b3 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/type-view.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/type-view.js @@ -23,7 +23,6 @@ function onRequest(context) { viewModel["isVirtual"] = request.getParameter("type") == 'virtual'; viewModel["isCloud"] = isCloud; viewModel["hostName"] = devicemgtProps["httpsURL"]; - viewModel["accessToken"] = session.get("tokenPair"); if (isCloud) { viewModel["enrollmentURL"] = "https://play.google.com/store/apps/details?id=org.wso2.iot.agent"; } else { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/pom.xml b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/pom.xml new file mode 100644 index 000000000..26415ebbb --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/pom.xml @@ -0,0 +1,184 @@ + + + + + + + android-plugin + org.wso2.carbon.devicemgt-plugins + 5.0.7-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.mobile.android + bundle + WSO2 Carbon - Mobile Device Management Android Impl + WSO2 Carbon - Mobile Device Management Android Implementation + http://wso2.org + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.devicemgt.plugins.version} + Device Management Mobile Android Impl Bundle + org.wso2.carbon.device.mgt.mobile.android.internal + + org.osgi.framework, + org.osgi.service.component, + org.apache.commons.logging, + javax.xml, + javax.xml.stream, + javax.xml.bind.*, + javax.sql, + javax.xml.parsers; version=0.0.0, + org.w3c.dom, + javax.naming, + org.wso2.carbon.context, + org.wso2.carbon.utils.*, + org.wso2.carbon.device.mgt.common.*, + org.wso2.carbon.ndatasource.core, + org.wso2.carbon.policy.mgt.common.*, + org.wso2.carbon.registry.core, + org.wso2.carbon.registry.core.session, + org.wso2.carbon.registry.core.service, + org.wso2.carbon.registry.api, + org.wso2.carbon.device.mgt.extensions.license.mgt.registry, + com.google.gson.* + + + !org.wso2.carbon.device.mgt.mobile.android.internal, + org.wso2.carbon.device.mgt.mobile.android.* + + + + + + org.jacoco + jacoco-maven-plugin + + ${basedir}/target/coverage-reports/jacoco-unit.exec + + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + ${basedir}/target/coverage-reports/jacoco-unit.exec + ${basedir}/target/coverage-reports/site + + + + + + + + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.carbon + org.wso2.carbon.core + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon + org.wso2.carbon.utils + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.extensions + + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + + + org.wso2.carbon.devicemgt + org.wso2.carbon.policy.mgt.common + + + org.wso2.carbon.devicemgt + org.wso2.carbon.policy.mgt.core + + + org.wso2.carbon + org.wso2.carbon.registry.api + + + org.wso2.carbon + org.wso2.carbon.registry.core + + + org.testng + testng + + + org.apache.tomcat.wso2 + jdbc-pool + + + com.h2database.wso2 + h2-database-engine + test + + + com.google.code.gson + gson + + + diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidDeviceManagementService.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidDeviceManagementService.java new file mode 100644 index 000000000..d2568978d --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidDeviceManagementService.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManager; +import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig; +import org.wso2.carbon.device.mgt.common.ProvisioningConfig; +import org.wso2.carbon.device.mgt.common.InitialOperationConfig; +import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig; +import org.wso2.carbon.device.mgt.common.StartupOperationConfig; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.general.GeneralConfig; +import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; +import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber; +import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypePlatformDetails; +import org.wso2.carbon.device.mgt.mobile.android.impl.util.AndroidPluginConstants; +import org.wso2.carbon.device.mgt.mobile.android.internal.AndroidDeviceManagementDataHolder; + +import java.util.HashMap; +import java.util.List; + +/** + * This represents the Android implementation of DeviceManagerService. + */ +public class AndroidDeviceManagementService implements DeviceManagementService { + + private static final Log log = LogFactory.getLog(AndroidDeviceManagementService.class); + private DeviceManager deviceManager; + public static final String DEVICE_TYPE_ANDROID = "android"; + private static final String SUPER_TENANT_DOMAIN = "carbon.super"; + private static final String NOTIFIER_PROPERTY = "notifierType"; + private static final String FCM_API_KEY = "fcmAPIKey"; + private static final String FCM_SENDER_ID = "fcmSenderId"; + private PolicyMonitoringManager policyMonitoringManager; + + @Override + public String getType() { + return AndroidDeviceManagementService.DEVICE_TYPE_ANDROID; + } + + @Override + public OperationMonitoringTaskConfig getOperationMonitoringConfig() { + return null; + } + + @Override + public void init() throws DeviceManagementException { + this.deviceManager = new AndroidDeviceManager(); + this.policyMonitoringManager = new AndroidPolicyMonitoringManager(); + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public ProvisioningConfig getProvisioningConfig() { + return new ProvisioningConfig(SUPER_TENANT_DOMAIN, true); + } + + @Override + public PushNotificationConfig getPushNotificationConfig() { + try { + DeviceManagementService deviceManagementService = AndroidDeviceManagementDataHolder.getInstance(). + getAndroidDeviceManagementService(); + if (deviceManagementService != null && deviceManagementService.getDeviceManager() != null) { + PlatformConfiguration androidConfig = deviceManagementService.getDeviceManager().getConfiguration(); + if (androidConfig != null) { + List configuration = androidConfig.getConfiguration(); + String notifierValue = this.getConfigProperty(configuration, NOTIFIER_PROPERTY); + if (notifierValue != null && !notifierValue.isEmpty()) { + int notifierType = Integer.parseInt(notifierValue); + if (notifierType == 2) { + HashMap config = new HashMap<>(); + config.put(FCM_API_KEY, this.getConfigProperty(configuration, FCM_API_KEY)); + config.put(FCM_SENDER_ID, this.getConfigProperty(configuration, FCM_SENDER_ID)); + return new PushNotificationConfig(AndroidPluginConstants.NotifierType.FCM, false, + config); + } + } + } + } + } catch (DeviceManagementException e) { + log.error("Unable to get the Android platform configuration from registry."); + } + return null; + } + + @Override + public PolicyMonitoringManager getPolicyMonitoringManager() { + return policyMonitoringManager; + } + + @Override + public InitialOperationConfig getInitialOperationConfig() { + return null; + } + + @Override + public StartupOperationConfig getStartupOperationConfig() { + return null; + } + + @Override + public PullNotificationSubscriber getPullNotificationSubscriber() { + return null; + } + + @Override + public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig() { + return null; + } + + @Override + public GeneralConfig getGeneralConfig() { + return null; + } + + @Override + public DeviceTypePlatformDetails getDeviceTypePlatformDetails() { + return null; + } + + private String getConfigProperty(List configs, String propertyName) { + for (ConfigurationEntry entry : configs) { + if (propertyName.equals(entry.getName())) { + return entry.getValue().toString(); + } + } + return null; + } +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidDeviceManager.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidDeviceManager.java new file mode 100644 index 000000000..c9f859d0c --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidDeviceManager.java @@ -0,0 +1,382 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.mobile.android.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.common.DeviceManager; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.license.mgt.License; +import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; +import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager; +import org.wso2.carbon.device.mgt.common.ui.policy.mgt.PolicyConfigurationManager; +import org.wso2.carbon.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.AbstractMobileDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.AndroidDAOFactory; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl.AndroidDeviceMgtPluginException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileDevice; +import org.wso2.carbon.device.mgt.mobile.android.impl.util.AndroidPluginConstants; +import org.wso2.carbon.device.mgt.mobile.android.impl.util.AndroidPluginUtils; +import org.wso2.carbon.device.mgt.mobile.android.impl.util.MobileDeviceManagementUtil; +import org.wso2.carbon.registry.api.RegistryException; +import org.wso2.carbon.registry.api.Resource; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import java.io.StringReader; +import java.io.StringWriter; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; + +public class AndroidDeviceManager implements DeviceManager { + + private AbstractMobileDeviceManagementDAOFactory daoFactory; + private static final Log log = LogFactory.getLog(AndroidDeviceManagementService.class); + private FeatureManager featureManager = new AndroidFeatureManager(); + private LicenseManager licenseManager; + + public AndroidDeviceManager() { + this.daoFactory = new AndroidDAOFactory(); + this.licenseManager = new RegistryBasedLicenseManager(); + License defaultLicense; + + try { + if (licenseManager.getLicense(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID, + AndroidPluginConstants.MobilePluginConstants.LANGUAGE_CODE_ENGLISH_US) == + null) { + defaultLicense = AndroidPluginUtils.getDefaultLicense(); + licenseManager.addLicense(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID, defaultLicense); + } + featureManager.addSupportedFeaturesToDB(); + } catch (LicenseManagementException e) { + log.error("Error occurred while adding default license for Android devices", e); + } catch (DeviceManagementException e) { + log.error("Error occurred while adding supported device features for Android platform", e); + } + } + + @Override + public FeatureManager getFeatureManager() { + return featureManager; + } + + @Override + public PolicyConfigurationManager getPolicyUIConfigurationManager() { + return null; + } + + @Override + public boolean saveConfiguration(PlatformConfiguration tenantConfiguration) + throws DeviceManagementException { + boolean status; + try { + if (log.isDebugEnabled()) { + log.debug("Persisting android configurations in Registry"); + } + String resourcePath = MobileDeviceManagementUtil.getPlatformConfigPath( + DeviceManagementConstants. + MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + StringWriter writer = new StringWriter(); + JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class); + Marshaller marshaller = context.createMarshaller(); + marshaller.marshal(tenantConfiguration, writer); + + Resource resource = MobileDeviceManagementUtil.getConfigurationRegistry().newResource(); + resource.setContent(writer.toString()); + resource.setMediaType(AndroidPluginConstants.MobilePluginConstants.MEDIA_TYPE_XML); + MobileDeviceManagementUtil.putRegistryResource(resourcePath, resource); + status = true; + } catch (AndroidDeviceMgtPluginException e) { + throw new DeviceManagementException( + "Error occurred while retrieving the Registry instance : " + e.getMessage(), e); + } catch (RegistryException e) { + throw new DeviceManagementException( + "Error occurred while persisting the Registry resource of Android Configuration : " + e.getMessage(), e); + } catch (JAXBException e) { + throw new DeviceManagementException( + "Error occurred while parsing the Android configuration : " + e.getMessage(), e); + } + return status; + } + + @Override + public PlatformConfiguration getConfiguration() throws DeviceManagementException { + Resource resource; + try { + String androidRegPath = + MobileDeviceManagementUtil.getPlatformConfigPath(DeviceManagementConstants. + MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + resource = MobileDeviceManagementUtil.getRegistryResource(androidRegPath); + if (resource != null) { + XMLInputFactory factory = XMLInputFactory.newInstance(); + factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); + factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); + XMLStreamReader reader = factory.createXMLStreamReader( + new StringReader(new String((byte[]) resource.getContent(), Charset. + forName(AndroidPluginConstants.MobilePluginConstants.CHARSET_UTF8)))); + JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class); + Unmarshaller unmarshaller = context.createUnmarshaller(); + return (PlatformConfiguration) unmarshaller.unmarshal(reader); + } + return null; + } catch (AndroidDeviceMgtPluginException e) { + throw new DeviceManagementException( + "Error occurred while retrieving the Registry instance : " + e.getMessage(), e); + } catch (JAXBException | XMLStreamException e) { + throw new DeviceManagementException( + "Error occurred while parsing the Android configuration : " + e.getMessage(), e); + } catch (RegistryException e) { + throw new DeviceManagementException( + "Error occurred while retrieving the Registry resource of Android Configuration : " + e.getMessage(), e); + } + } + + @Override + public boolean enrollDevice(Device device) throws DeviceManagementException { + boolean status = false; + boolean isEnrolled = this.isEnrolled( + new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); + + try { + if (log.isDebugEnabled()) { + log.debug("Enrolling a new Android device : " + device.getDeviceIdentifier()); + } + + if (isEnrolled) { + this.modifyEnrollment(device); + } else { + MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device); + AndroidDAOFactory.beginTransaction(); + status = daoFactory.getMobileDeviceDAO().addMobileDevice(mobileDevice); + AndroidDAOFactory.commitTransaction(); + } + } catch (MobileDeviceManagementDAOException e) { + try { + AndroidDAOFactory.rollbackTransaction(); + } catch (MobileDeviceManagementDAOException mobileDAOEx) { + String msg = "Error occurred while roll back the device enrol transaction :" + + device.toString(); + log.warn(msg, mobileDAOEx); + } + String msg = + "Error while enrolling the Android device : " + device.getDeviceIdentifier(); + throw new DeviceManagementException(msg, e); + } + return status; + } + + @Override + public boolean modifyEnrollment(Device device) throws DeviceManagementException { + boolean status; + MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device); + try { + if (log.isDebugEnabled()) { + log.debug("Modifying the Android device enrollment data"); + } + AndroidDAOFactory.beginTransaction(); + status = daoFactory.getMobileDeviceDAO().updateMobileDevice(mobileDevice); + AndroidDAOFactory.commitTransaction(); + } catch (MobileDeviceManagementDAOException e) { + try { + AndroidDAOFactory.rollbackTransaction(); + } catch (MobileDeviceManagementDAOException mobileDAOEx) { + String msg = "Error occurred while roll back the update device transaction :" + + device.toString(); + log.warn(msg, mobileDAOEx); + } + String msg = "Error while updating the enrollment of the Android device : " + + device.getDeviceIdentifier(); + throw new DeviceManagementException(msg, e); + } + return status; + } + + @Override + public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException { + //Here we don't have anything specific to do. Hence returning. + return true; + } + + @Override + public void deleteDevices(List list) throws DeviceManagementException { + + } + + @Override + public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { + boolean isEnrolled = false; + try { + if (log.isDebugEnabled()) { + log.debug("Checking the enrollment of Android device : " + deviceId.getId()); + } + MobileDevice mobileDevice = + daoFactory.getMobileDeviceDAO().getMobileDevice(deviceId.getId()); + if (mobileDevice != null) { + isEnrolled = true; + } + } catch (MobileDeviceManagementDAOException e) { + String msg = "Error while checking the enrollment status of Android device : " + + deviceId.getId(); + throw new DeviceManagementException(msg, e); + } + return isEnrolled; + } + + @Override + public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException { + return true; + } + + @Override + public boolean setActive(DeviceIdentifier deviceId, boolean status) + throws DeviceManagementException { + return true; + } + + @Override + public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { + Device device; + try { + if (log.isDebugEnabled()) { + log.debug("Getting the details of Android device : '" + deviceId.getId() + "'"); + } + MobileDevice mobileDevice = daoFactory.getMobileDeviceDAO(). + getMobileDevice(deviceId.getId()); + device = MobileDeviceManagementUtil.convertToDevice(mobileDevice); + } catch (MobileDeviceManagementDAOException e) { + throw new DeviceManagementException( + "Error occurred while fetching the Android device: '" + + deviceId.getId() + "'", e); + } + return device; + } + + @Override + public boolean updateDeviceProperties(DeviceIdentifier deviceIdentifier, List list) throws DeviceManagementException { + return false; + } + + @Override + public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) + throws DeviceManagementException { + return true; + } + + @Override + public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException { + return false; + } + + @Override + public boolean setStatus(DeviceIdentifier deviceIdentifier, String currentUser, + EnrolmentInfo.Status status) throws DeviceManagementException { + return false; + } + + @Override + public License getLicense(String languageCode) throws LicenseManagementException { + return licenseManager. + getLicense(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID, languageCode); + } + + @Override + public void addLicense(License license) throws LicenseManagementException { + licenseManager.addLicense(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID, license); + } + + @Override + public boolean requireDeviceAuthorization() { + return true; + } + + @Override + public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) + throws DeviceManagementException { + boolean status; + Device existingDevice = this.getDevice(deviceIdentifier); + // This object holds the current persisted device object + MobileDevice existingMobileDevice = + MobileDeviceManagementUtil.convertToMobileDevice(existingDevice); + + // This object holds the newly received device object from response + MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device); + + // Updating current object features using newer ones + existingMobileDevice.setLatitude(mobileDevice.getLatitude()); + existingMobileDevice.setLongitude(mobileDevice.getLongitude()); + existingMobileDevice.setDeviceProperties(mobileDevice.getDeviceProperties()); + + try { + if (log.isDebugEnabled()) { + log.debug( + "updating the details of Android device : " + device.getDeviceIdentifier()); + } + AndroidDAOFactory.beginTransaction(); + status = daoFactory.getMobileDeviceDAO().updateMobileDevice(existingMobileDevice); + AndroidDAOFactory.commitTransaction(); + } catch (MobileDeviceManagementDAOException e) { + try { + AndroidDAOFactory.rollbackTransaction(); + } catch (MobileDeviceManagementDAOException e1) { + log.warn("Error occurred while roll back the update device info transaction : '" + + device.toString() + "'", e1); + } + throw new DeviceManagementException( + "Error occurred while updating the Android device: '" + + device.getDeviceIdentifier() + "'", e); + } + return status; + } + + @Override + public List getAllDevices() throws DeviceManagementException { + List devices = null; + try { + if (log.isDebugEnabled()) { + log.debug("Fetching the details of all Android devices"); + } + List mobileDevices = + daoFactory.getMobileDeviceDAO().getAllMobileDevices(); + if (mobileDevices != null) { + devices = new ArrayList<>(mobileDevices.size()); + for (MobileDevice mobileDevice : mobileDevices) { + devices.add(MobileDeviceManagementUtil.convertToDevice(mobileDevice)); + } + } + } catch (MobileDeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while fetching all Android devices", + e); + } + return devices; + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidFeatureManager.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidFeatureManager.java new file mode 100644 index 000000000..1c9f3538d --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidFeatureManager.java @@ -0,0 +1,484 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.mobile.android.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.common.FeatureManager; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.AndroidDAOFactory; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileFeatureDAO; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileFeature; +import org.wso2.carbon.device.mgt.mobile.android.impl.util.MobileDeviceManagementUtil; + +import java.util.ArrayList; +import java.util.List; + +public class AndroidFeatureManager implements FeatureManager { + + private MobileFeatureDAO featureDAO; + private static final Log log = LogFactory.getLog(AndroidFeatureManager.class); + + public AndroidFeatureManager() { + MobileDeviceManagementDAOFactory daoFactory = new AndroidDAOFactory(); + this.featureDAO = daoFactory.getMobileFeatureDAO(); + } + + @Override + public boolean addFeature(Feature feature) throws DeviceManagementException { + try { + AndroidDAOFactory.beginTransaction(); + MobileFeature mobileFeature = MobileDeviceManagementUtil.convertToMobileFeature(feature); + featureDAO.addFeature(mobileFeature); + AndroidDAOFactory.commitTransaction(); + return true; + } catch (MobileDeviceManagementDAOException e) { + try { + AndroidDAOFactory.rollbackTransaction(); + } catch (MobileDeviceManagementDAOException e1) { + log.warn("Error occurred while roll-backing the transaction", e); + } + throw new DeviceManagementException("Error occurred while adding the feature", e); + } + } + + @Override + public boolean addFeatures(List features) throws DeviceManagementException { + List mobileFeatures = new ArrayList(features.size()); + for (Feature feature : features) { + mobileFeatures.add(MobileDeviceManagementUtil.convertToMobileFeature(feature)); + } + try { + AndroidDAOFactory.beginTransaction(); + featureDAO.addFeatures(mobileFeatures); + AndroidDAOFactory.commitTransaction(); + return true; + } catch (MobileDeviceManagementDAOException e) { + try { + AndroidDAOFactory.rollbackTransaction(); + } catch (MobileDeviceManagementDAOException e1) { + log.warn("Error occurred while roll-backing the transaction", e); + } + throw new DeviceManagementException("Error occurred while adding the features", e); + } + } + + @Override + public Feature getFeature(String name) throws DeviceManagementException { + try { + MobileFeature mobileFeature = featureDAO.getFeatureByCode(name); + Feature feature = MobileDeviceManagementUtil.convertToFeature(mobileFeature); + return feature; + } catch (MobileDeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while retrieving the feature", e); + } + } + + @Override + public List getFeatures() throws DeviceManagementException { + try { + List mobileFeatures = featureDAO.getAllFeatures(); + List featureList = new ArrayList(mobileFeatures.size()); + for (MobileFeature mobileFeature : mobileFeatures) { + featureList.add(MobileDeviceManagementUtil.convertToFeature(mobileFeature)); + } + return featureList; + } catch (MobileDeviceManagementDAOException e) { + throw new DeviceManagementException("Error occurred while retrieving the list of features registered for " + + "Android platform", e); + } + } + + @Override + public List getFeatures(String s) throws DeviceManagementException { + return null; + } + + @Override + public List getFeatures(String s, boolean b) throws DeviceManagementException { + return null; + } + + @Override + public boolean removeFeature(String code) throws DeviceManagementException { + boolean status; + try { + AndroidDAOFactory.beginTransaction(); + featureDAO.deleteFeatureByCode(code); + AndroidDAOFactory.commitTransaction(); + status = true; + } catch (MobileDeviceManagementDAOException e) { + try { + AndroidDAOFactory.rollbackTransaction(); + } catch (MobileDeviceManagementDAOException e1) { + log.warn("Error occurred while roll-backing the transaction", e); + } + throw new DeviceManagementException("Error occurred while removing the feature", e); + } + return status; + } + + @Override + public boolean addSupportedFeaturesToDB() throws DeviceManagementException { + synchronized (this) { + List supportedFeatures = getSupportedFeatures(); + List existingFeatures = this.getFeatures(); + List missingFeatures = MobileDeviceManagementUtil. + getMissingFeatures(supportedFeatures, existingFeatures); + if (missingFeatures.size() > 0) { + return this.addFeatures(missingFeatures); + } + return true; + } + } + + //Get the supported feature list. + private static List getSupportedFeatures() { + List supportedFeatures = new ArrayList(); + Feature feature = new Feature(); + feature.setCode("DEVICE_LOCK"); + feature.setName("Device Lock"); + feature.setDescription("Lock the device"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("DEVICE_LOCATION"); + feature.setName("Location"); + feature.setDescription("Request coordinates of device location"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("WIFI"); + feature.setName("wifi"); + feature.setDescription("Setting up wifi configuration"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("CAMERA"); + feature.setName("camera"); + feature.setDescription("Enable or disable camera"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("EMAIL"); + feature.setName("Email"); + feature.setDescription("Configure email settings"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("DEVICE_MUTE"); + feature.setName("mute"); + feature.setDescription("Enable mute in the device"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("DEVICE_INFO"); + feature.setName("Device info"); + feature.setDescription("Request device information"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("ENTERPRISE_WIPE"); + feature.setName("Enterprise Wipe"); + feature.setDescription("Remove enterprise applications"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("CLEAR_PASSWORD"); + feature.setName("Clear Password"); + feature.setDescription("Clear current password"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("WIPE_DATA"); + feature.setName("Wipe Data"); + feature.setDescription("Factory reset the device"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("APPLICATION_LIST"); + feature.setName("Application List"); + feature.setDescription("Request list of current installed applications"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("CHANGE_LOCK_CODE"); + feature.setName("Change Lock-code"); + feature.setDescription("Change current lock code"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("INSTALL_APPLICATION"); + feature.setName("Install App"); + feature.setDescription("Install Enterprise or Market application"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("UNINSTALL_APPLICATION"); + feature.setName("Uninstall App"); + feature.setDescription("Uninstall application"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("BLACKLIST_APPLICATIONS"); + feature.setName("Blacklist app"); + feature.setDescription("Blacklist applications"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("ENCRYPT_STORAGE"); + feature.setName("Encrypt storage"); + feature.setDescription("Encrypt storage"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("DEVICE_RING"); + feature.setName("Ring"); + feature.setDescription("Ring the device"); + supportedFeatures.add(feature); + feature = new Feature(); + feature.setCode("PASSCODE_POLICY"); + feature.setName("Password Policy"); + feature.setDescription("Set passcode policy"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("NOTIFICATION"); + feature.setName("Message"); + feature.setDescription("Send message"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DEVICE_REBOOT"); + feature.setName("Reboot"); + feature.setDescription("Reboot the device"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("UPGRADE_FIRMWARE"); + feature.setName("Upgrade Firmware"); + feature.setDescription("Upgrade Firmware"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("VPN"); + feature.setName("Configure VPN"); + feature.setDescription("Configure VPN settings"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_ADJUST_VOLUME"); + feature.setName("Adjust Volume"); + feature.setDescription("allow or disallow user to change volume"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CONFIG_BLUETOOTH"); + feature.setName("Disallow bluetooth configuration"); + feature.setDescription("allow or disallow user to change bluetooth configurations"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CONFIG_CELL_BROADCASTS"); + feature.setName("Disallow cell broadcast configuration"); + feature.setDescription("allow or disallow user to change cell broadcast configurations"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CONFIG_CREDENTIALS"); + feature.setName("Disallow credential configuration"); + feature.setDescription("allow or disallow user to change user credentials"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CONFIG_MOBILE_NETWORKS"); + feature.setName("Disallow mobile network configure"); + feature.setDescription("allow or disallow user to change mobile networks configurations"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CONFIG_TETHERING"); + feature.setName("Disallow tethering configuration"); + feature.setDescription("allow or disallow user to change tethering configurations"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CONFIG_VPN"); + feature.setName("Disallow VPN configuration"); + feature.setDescription("allow or disallow user to change VPN configurations"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CONFIG_WIFI"); + feature.setName("Disallow WIFI configuration"); + feature.setDescription("allow or disallow user to change WIFI configurations"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_APPS_CONTROL"); + feature.setName("Disallow APP control configuration"); + feature.setDescription("allow or disallow user to change app control"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CREATE_WINDOWS"); + feature.setName("Disallow window creation"); + feature.setDescription("allow or disallow window creation"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_APPS_CONTROL"); + feature.setName("Disallow APP control configuration"); + feature.setDescription("allow or disallow user to change app control configurations"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_CROSS_PROFILE_COPY_PASTE"); + feature.setName("Disallow cross profile copy paste"); + feature.setDescription("allow or disallow cross profile copy paste"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_DEBUGGING_FEATURES"); + feature.setName("Disallow debugging features"); + feature.setDescription("allow or disallow debugging features"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_FACTORY_RESET"); + feature.setName("Disallow factory reset"); + feature.setDescription("allow or disallow factory reset"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_ADD_USER"); + feature.setName("Disallow add user"); + feature.setDescription("allow or disallow add user"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_INSTALL_APPS"); + feature.setName("Disallow install apps"); + feature.setDescription("allow or disallow install apps"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_INSTALL_UNKNOWN_SOURCES"); + feature.setName("Disallow install unknown sources"); + feature.setDescription("allow or disallow install unknown sources"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_MODIFY_ACCOUNTS"); + feature.setName("Disallow modify account"); + feature.setDescription("allow or disallow modify account"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_MOUNT_PHYSICAL_MEDIA"); + feature.setName("Disallow mount physical media"); + feature.setDescription("allow or disallow mount physical media."); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_NETWORK_RESET"); + feature.setName("Disallow network reset"); + feature.setDescription("allow or disallow network reset"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_OUTGOING_BEAM"); + feature.setName("Disallow outgoing beam"); + feature.setDescription("allow or disallow outgoing beam."); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_OUTGOING_CALLS"); + feature.setName("Disallow outgoing calls"); + feature.setDescription("allow or disallow outgoing calls"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_REMOVE_USER"); + feature.setName("Disallow remove users"); + feature.setDescription("allow or disallow remove users"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_SAFE_BOOT"); + feature.setName("Disallow safe boot"); + feature.setDescription("allow or disallow safe boot"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_SHARE_LOCATION"); + feature.setName("Disallow share location"); + feature.setDescription("allow or disallow share location."); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_SMS"); + feature.setName("Disallow sms"); + feature.setDescription("allow or disallow sms"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_UNINSTALL_APPS"); + feature.setName("Disallow uninstall app"); + feature.setDescription("allow or disallow uninstall app"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_UNMUTE_MICROPHONE"); + feature.setName("Disallow unmute mic"); + feature.setDescription("allow or disallow unmute mic"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DISALLOW_USB_FILE_TRANSFER"); + feature.setName("Disallow usb file transfer"); + feature.setDescription("allow or disallow usb file transfer"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("ALLOW_PARENT_PROFILE_APP_LINKING"); + feature.setName("Disallow parent profile app linking"); + feature.setDescription("allow or disallow parent profile app linking"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("ENSURE_VERIFY_APPS"); + feature.setName("Disallow ensure verify apps"); + feature.setDescription("allow or disallow ensure verify apps"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("AUTO_TIME"); + feature.setName("Allow auto timing"); + feature.setDescription("allow or disallow auto timing"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("REMOVE_DEVICE_OWNER"); + feature.setName("Remove device owner"); + feature.setDescription("remove device owner"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("LOGCAT"); + feature.setName("Fetch Logcat"); + feature.setDescription("Fetch device logcat"); + supportedFeatures.add(feature); + + feature = new Feature(); + feature.setCode("DEVICE_UNLOCK"); + feature.setName("Device Unlock"); + feature.setDescription("Unlock the device"); + supportedFeatures.add(feature); + + return supportedFeatures; + } +} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidPolicyMonitoringManager.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidPolicyMonitoringManager.java new file mode 100644 index 000000000..11d2f5332 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/AndroidPolicyMonitoringManager.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.wso2.carbon.device.mgt.mobile.android.impl; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager; +import org.wso2.carbon.device.mgt.common.policy.mgt.Policy; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; +import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; + +import java.util.ArrayList; +import java.util.List; + +public class AndroidPolicyMonitoringManager implements PolicyMonitoringManager { + + private static Log log = LogFactory.getLog(AndroidPolicyMonitoringManager.class); + + @Override + public NonComplianceData checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, + Object compliancePayload) throws PolicyComplianceException { + if (log.isDebugEnabled()) { + log.debug("Checking policy compliance status of device '" + deviceIdentifier.getId() + "'"); + } + NonComplianceData complianceData = new NonComplianceData(); + if (compliancePayload == null || policy == null) { + return complianceData; + } + String compliancePayloadString = new Gson().toJson(compliancePayload); + // Parsing json string to get compliance features. + JsonElement jsonElement; + if (compliancePayloadString instanceof String) { + jsonElement = new JsonParser().parse(compliancePayloadString); + } else { + throw new PolicyComplianceException("Invalid policy compliance payload"); + } + + JsonArray jsonArray = jsonElement.getAsJsonArray(); + Gson gson = new Gson(); + ComplianceFeature complianceFeature; + List complianceFeatures = new ArrayList(jsonArray.size()); + List nonComplianceFeatures = new ArrayList<>(); + + for (JsonElement element : jsonArray) { + complianceFeature = gson.fromJson(element, ComplianceFeature.class); + complianceFeatures.add(complianceFeature); + } + + for (ComplianceFeature cf : complianceFeatures) { + if (!cf.isCompliant()) { + complianceData.setStatus(false); + nonComplianceFeatures.add(cf); + break; + } + } + + complianceData.setComplianceFeatures(nonComplianceFeatures); + return complianceData; + } + +} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceConfigurationManager.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceConfigurationManager.java new file mode 100644 index 000000000..ded87ad71 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceConfigurationManager.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.config; + +import org.w3c.dom.Document; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.mobile.android.impl.util.MobileDeviceManagementUtil; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import java.io.File; + +/** + * Class responsible for the mobile device manager configuration initialization. + */ +public class MobileDeviceConfigurationManager { + + private static final String MOBILE_DEVICE_CONFIG_XML_NAME = "mobile-config.xml"; + private static final String MOBILE_DEVICE_PLUGIN_DIRECTORY = "mobile"; + private static final String DEVICE_MGT_PLUGIN_CONFIGS_DIRECTORY = "device-mgt-plugin-configs"; + private MobileDeviceManagementConfig currentMobileDeviceConfig; + private static MobileDeviceConfigurationManager mobileDeviceConfigManager; + + private final String mobileDeviceMgtConfigXMLPath = + CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + + DEVICE_MGT_PLUGIN_CONFIGS_DIRECTORY + + File.separator + + MOBILE_DEVICE_PLUGIN_DIRECTORY + File.separator + MOBILE_DEVICE_CONFIG_XML_NAME; + + public static MobileDeviceConfigurationManager getInstance() { + if (mobileDeviceConfigManager == null) { + synchronized (MobileDeviceConfigurationManager.class) { + if (mobileDeviceConfigManager == null) { + mobileDeviceConfigManager = new MobileDeviceConfigurationManager(); + } + } + } + return mobileDeviceConfigManager; + } + + public synchronized void initConfig() throws DeviceManagementException { + try { + File mobileDeviceMgtConfig = new File(mobileDeviceMgtConfigXMLPath); + Document doc = MobileDeviceManagementUtil.convertToDocument(mobileDeviceMgtConfig); + JAXBContext mobileDeviceMgmtContext = + JAXBContext.newInstance(MobileDeviceManagementConfig.class); + Unmarshaller unmarshaller = mobileDeviceMgmtContext.createUnmarshaller(); + this.currentMobileDeviceConfig = + (MobileDeviceManagementConfig) unmarshaller.unmarshal(doc); + } catch (Exception e) { + throw new DeviceManagementException( + "Error occurred while initializing Mobile Device Management config", e); + } + } + + public MobileDeviceManagementConfig getMobileDeviceManagementConfig() { + return currentMobileDeviceConfig; + } + + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceManagementConfig.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceManagementConfig.java new file mode 100644 index 000000000..2c65375c7 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceManagementConfig.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Represents Mobile Device Mgt configuration. + */ +@XmlRootElement(name = "MobileDeviceMgtConfiguration") +public final class MobileDeviceManagementConfig { + + private MobileDeviceManagementRepository mobileDeviceMgtRepository; + + @XmlElement(name = "ManagementRepository", nillable = false) + public MobileDeviceManagementRepository getMobileDeviceMgtRepository() { + return mobileDeviceMgtRepository; + } + + public void setMobileDeviceMgtRepository( + MobileDeviceManagementRepository mobileDeviceMgtRepository) { + this.mobileDeviceMgtRepository = mobileDeviceMgtRepository; + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceManagementRepository.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceManagementRepository.java new file mode 100644 index 000000000..e40202acf --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/MobileDeviceManagementRepository.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.config; + +import org.wso2.carbon.device.mgt.mobile.android.impl.config.datasource.DataSourceConfigAdapter; +import org.wso2.carbon.device.mgt.mobile.android.impl.config.datasource.MobileDataSourceConfig; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import java.util.List; +import java.util.Map; + +/** + * Class for holding management repository data. + */ +@XmlRootElement(name = "ManagementRepository") +public class MobileDeviceManagementRepository { + + private Map mobileDataSourceConfigMap; + private List mobileDataSourceConfigs; + + public MobileDataSourceConfig getMobileDataSourceConfig(String provider) { + return mobileDataSourceConfigMap.get(provider); + } + + @XmlElement(name = "DataSourceConfigurations") + @XmlJavaTypeAdapter(DataSourceConfigAdapter.class) + public Map getMobileDataSourceConfigMap() { + return mobileDataSourceConfigMap; + } + + public void setMobileDataSourceConfigMap(Map mobileDataSourceConfigMap) { + this.mobileDataSourceConfigMap = mobileDataSourceConfigMap; + } + + public List getMobileDataSourceConfigs() { + return (List) mobileDataSourceConfigMap.values(); + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/DataSourceConfigAdapter.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/DataSourceConfigAdapter.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/DataSourceConfigAdapter.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/DataSourceConfigAdapter.java index 5b0aa5713..75a95c7c7 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/DataSourceConfigAdapter.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/DataSourceConfigAdapter.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.config.datasource; +package org.wso2.carbon.device.mgt.mobile.android.impl.config.datasource; import javax.xml.bind.annotation.adapters.XmlAdapter; import java.util.HashMap; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/JNDILookupDefinition.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/JNDILookupDefinition.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/JNDILookupDefinition.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/JNDILookupDefinition.java index 770963989..d98022058 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/JNDILookupDefinition.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/JNDILookupDefinition.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.config.datasource; +package org.wso2.carbon.device.mgt.mobile.android.impl.config.datasource; import javax.xml.bind.annotation.*; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/MobileDataSourceConfig.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/MobileDataSourceConfig.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/MobileDataSourceConfig.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/MobileDataSourceConfig.java index 09bb84de4..cb0e78fb2 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/MobileDataSourceConfig.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/MobileDataSourceConfig.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.config.datasource; +package org.wso2.carbon.device.mgt.mobile.android.impl.config.datasource; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/MobileDataSourceConfigurations.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/MobileDataSourceConfigurations.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/MobileDataSourceConfigurations.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/MobileDataSourceConfigurations.java index b4613bd99..c698e7800 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/datasource/MobileDataSourceConfigurations.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/datasource/MobileDataSourceConfigurations.java @@ -15,7 +15,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.config.datasource; +package org.wso2.carbon.device.mgt.mobile.android.impl.config.datasource; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/task/TaskConfiguration.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/task/TaskConfiguration.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/task/TaskConfiguration.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/task/TaskConfiguration.java index 56b873c34..9c98306fb 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/config/task/TaskConfiguration.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/config/task/TaskConfiguration.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.config.task; +package org.wso2.carbon.device.mgt.mobile.android.impl.config.task; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/AbstractMobileDeviceManagementDAOFactory.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AbstractMobileDeviceManagementDAOFactory.java similarity index 85% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/AbstractMobileDeviceManagementDAOFactory.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AbstractMobileDeviceManagementDAOFactory.java index 043dadaf8..c96b603a8 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/AbstractMobileDeviceManagementDAOFactory.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AbstractMobileDeviceManagementDAOFactory.java @@ -16,14 +16,14 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.core.dao; +package org.wso2.carbon.device.mgt.mobile.android.impl.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.device.mgt.mobile.android.common.config.datasource.JNDILookupDefinition; -import org.wso2.carbon.device.mgt.mobile.android.common.config.datasource.MobileDataSourceConfig; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.AndroidDeviceMgtPluginException; -import org.wso2.carbon.device.mgt.mobile.android.core.dao.util.MobileDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.mobile.android.impl.config.datasource.JNDILookupDefinition; +import org.wso2.carbon.device.mgt.mobile.android.impl.config.datasource.MobileDataSourceConfig; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl.AndroidDeviceMgtPluginException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.util.MobileDeviceManagementDAOUtil; import javax.sql.DataSource; import java.util.HashMap; @@ -34,7 +34,7 @@ import java.util.Map; /** * Factory class used to create MobileDeviceManagement related DAO objects. */ -public abstract class AbstractMobileDeviceManagementDAOFactory { +public abstract class AbstractMobileDeviceManagementDAOFactory implements MobileDeviceManagementDAOFactory { private static final Log log = LogFactory.getLog(AbstractMobileDeviceManagementDAOFactory.class); private static Map dataSourceMap = new HashMap<>(); @@ -80,11 +80,12 @@ public abstract class AbstractMobileDeviceManagementDAOFactory { List jndiPropertyList = jndiConfig.getJndiProperties(); if (jndiPropertyList != null) { - Hashtable jndiProperties = new Hashtable<>(); + Hashtable jndiProperties = new Hashtable(); for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { jndiProperties.put(prop.getName(), prop.getValue()); } - dataSource = MobileDeviceManagementDAOUtil + dataSource = + MobileDeviceManagementDAOUtil .lookupDataSource(jndiConfig.getJndiName(), jndiProperties); } else { dataSource = MobileDeviceManagementDAOUtil diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/AndroidDAOFactory.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AndroidDAOFactory.java similarity index 61% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/AndroidDAOFactory.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AndroidDAOFactory.java index d18cc0f8a..e3949b16a 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/AndroidDAOFactory.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AndroidDAOFactory.java @@ -16,13 +16,13 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.core.dao; +package org.wso2.carbon.device.mgt.mobile.android.impl.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.mobile.android.common.exception.EnterpriseManagementDAOException; -import org.wso2.carbon.device.mgt.mobile.android.core.dao.impl.EnterpriseDAOImpl; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl.AndroidDeviceDAOImpl; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl.AndroidFeatureDAOImpl; import javax.sql.DataSource; import java.sql.Connection; @@ -38,52 +38,38 @@ public class AndroidDAOFactory extends AbstractMobileDeviceManagementDAOFactory this.dataSource = getDataSourceMap().get(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); } - public static EnterpriseDAO getEnterpriseDAO() { - if (dataSource == null) { - dataSource = getDataSourceMap().get(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); - } - - return new EnterpriseDAOImpl(); + @Override + public MobileDeviceDAO getMobileDeviceDAO() { + return new AndroidDeviceDAOImpl(); } - public static void beginTransaction() throws EnterpriseManagementDAOException { + public MobileFeatureDAO getMobileFeatureDAO() { + return new AndroidFeatureDAOImpl(); + } + + public static void beginTransaction() throws MobileDeviceManagementDAOException { try { Connection conn = dataSource.getConnection(); conn.setAutoCommit(false); currentConnection.set(conn); } catch (SQLException e) { - throw new EnterpriseManagementDAOException("Error occurred while retrieving datasource connection", e); + throw new MobileDeviceManagementDAOException("Error occurred while retrieving datasource connection", e); } } - public static void openConnection() throws EnterpriseManagementDAOException { - Connection conn = currentConnection.get(); - if (conn != null) { - throw new EnterpriseManagementDAOException("A transaction is already active within the context of " + - "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + - "transaction is already active is a sign of improper transaction handling"); - } - try { - conn = dataSource.getConnection(); - } catch (SQLException e) { - throw new EnterpriseManagementDAOException("Error occurred while opening connection", e); - } - currentConnection.set(conn); - } - - public static Connection getConnection() throws EnterpriseManagementDAOException { + public static Connection getConnection() throws MobileDeviceManagementDAOException { if (currentConnection.get() == null) { try { currentConnection.set(dataSource.getConnection()); } catch (SQLException e) { - throw new EnterpriseManagementDAOException("Error occurred while retrieving data source connection", + throw new MobileDeviceManagementDAOException("Error occurred while retrieving data source connection", e); } } return currentConnection.get(); } - public static void commitTransaction() throws EnterpriseManagementDAOException { + public static void commitTransaction() throws MobileDeviceManagementDAOException { try { Connection conn = currentConnection.get(); if (conn != null) { @@ -95,11 +81,11 @@ public class AndroidDAOFactory extends AbstractMobileDeviceManagementDAOFactory } } } catch (SQLException e) { - throw new EnterpriseManagementDAOException("Error occurred while committing the transaction", e); + throw new MobileDeviceManagementDAOException("Error occurred while committing the transaction", e); } } - public static void closeConnection() { + public static void closeConnection() throws MobileDeviceManagementDAOException { Connection conn = currentConnection.get(); try { if (conn != null) { @@ -111,7 +97,7 @@ public class AndroidDAOFactory extends AbstractMobileDeviceManagementDAOFactory currentConnection.remove(); } - public static void rollbackTransaction() { + public static void rollbackTransaction() throws MobileDeviceManagementDAOException { try { Connection conn = currentConnection.get(); if (conn != null) { @@ -123,7 +109,7 @@ public class AndroidDAOFactory extends AbstractMobileDeviceManagementDAOFactory } } } catch (SQLException e) { - log.warn("Error occurred while roll-backing the transaction", e); + throw new MobileDeviceManagementDAOException("Error occurred while rollback the transaction", e); } } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AndroidFeatureManagementDAOException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AndroidFeatureManagementDAOException.java new file mode 100644 index 000000000..61db0cc04 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/AndroidFeatureManagementDAOException.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.mobile.android.impl.dao; + +public class AndroidFeatureManagementDAOException extends MobileDeviceManagementDAOException { + + private String message; + private static final long serialVersionUID = 2021891706072918865L; + + /** + * Constructs a new MobileDeviceManagementDAOException with the specified detail message and + * nested exception. + * + * @param message error message + * @param nestedException exception + */ + public AndroidFeatureManagementDAOException(String message, Exception nestedException) { + super(message, nestedException); + setErrorMessage(message); + } + + /** + * Constructs a new MobileDeviceManagementDAOException with the specified detail message + * and cause. + * + * @param message the detail message. + * @param cause the cause of this exception. + */ + public AndroidFeatureManagementDAOException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + /** + * Constructs a new MobileDeviceManagementDAOException with the specified detail message. + * + * @param message the detail message. + */ + public AndroidFeatureManagementDAOException(String message) { + super(message); + setErrorMessage(message); + } + + /** + * Constructs a new MobileDeviceManagementDAOException with the specified and cause. + * + * @param cause the cause of this exception. + */ + public AndroidFeatureManagementDAOException(Throwable cause) { + super(cause); + } + + public String getMessage() { + return message; + } + + public void setErrorMessage(String errorMessage) { + this.message = errorMessage; + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceDAO.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceDAO.java new file mode 100644 index 000000000..d9209a1cb --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceDAO.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.dao; + +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileDevice; +import java.util.List; + +/** + * This class represents the key operations associated with persisting mobile-device related + * information. + */ +public interface MobileDeviceDAO { + + /** + * Fetches a MobileDevice from MDM database. + * + * @param mblDeviceId Id of the Mobile-Device. + * @return MobileDevice corresponding to given device-id. + * @throws MobileDeviceManagementDAOException + */ + MobileDevice getMobileDevice(String mblDeviceId) throws MobileDeviceManagementDAOException; + + /** + * Adds a new MobileDevice to the MDM database. + * + * @param mobileDevice MobileDevice to be added. + * @return The status of the operation. + * @throws MobileDeviceManagementDAOException + */ + boolean addMobileDevice(MobileDevice mobileDevice) throws MobileDeviceManagementDAOException; + + /** + * Updates MobileDevice information in MDM database. + * + * @param mobileDevice MobileDevice to be updated. + * @return The status of the operation. + * @throws MobileDeviceManagementDAOException + */ + boolean updateMobileDevice(MobileDevice mobileDevice) throws MobileDeviceManagementDAOException; + + /** + * Deletes a given MobileDevice from MDM database. + * + * @param mblDeviceId Id of MobileDevice to be deleted. + * @return The status of the operation. + * @throws MobileDeviceManagementDAOException + */ + boolean deleteMobileDevice(String mblDeviceId) throws MobileDeviceManagementDAOException; + + /** + * Fetches all MobileDevices from MDM database. + * + * @return List of MobileDevices. + * @throws MobileDeviceManagementDAOException + */ + List getAllMobileDevices() throws MobileDeviceManagementDAOException; + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/MobileDeviceManagementDAOException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceManagementDAOException.java similarity index 97% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/MobileDeviceManagementDAOException.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceManagementDAOException.java index 395da6acd..f87ddbfec 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/MobileDeviceManagementDAOException.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceManagementDAOException.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.exception; +package org.wso2.carbon.device.mgt.mobile.android.impl.dao; /** * Custom exception class for mobile device specific data access related exceptions. diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/MobileDeviceManagementDAOFactory.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceManagementDAOFactory.java similarity index 83% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/MobileDeviceManagementDAOFactory.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceManagementDAOFactory.java index 6ba69f723..1b28ac285 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/MobileDeviceManagementDAOFactory.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileDeviceManagementDAOFactory.java @@ -16,9 +16,12 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.core.dao; +package org.wso2.carbon.device.mgt.mobile.android.impl.dao; public interface MobileDeviceManagementDAOFactory { + MobileDeviceDAO getMobileDeviceDAO(); + + MobileFeatureDAO getMobileFeatureDAO(); } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileFeatureDAO.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileFeatureDAO.java new file mode 100644 index 000000000..b9a4d72af --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/MobileFeatureDAO.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.dao; + +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileFeature; + +import java.util.List; + +/** + * This class represents the key operations associated with persisting mobile feature related + * information. + */ +public interface MobileFeatureDAO { + + /** + * Adds a new MobileFeature to Mobile-Feature table. + * + * @param mobileFeature MobileFeature object that holds data related to the feature to be inserted. + * @return boolean status of the operation. + * @throws MobileDeviceManagementDAOException + */ + boolean addFeature(MobileFeature mobileFeature) throws MobileDeviceManagementDAOException; + + /** + * Adda a list of MobileFeatures to Mobile-Feature table. + * + * @param mobileFeatures List of MobileFeature objects. + * @return boolean status of the operation. + * @throws MobileDeviceManagementDAOException + */ + boolean addFeatures(List mobileFeatures) throws MobileDeviceManagementDAOException; + + /** + * Updates a MobileFeature in Mobile-Feature table. + * + * @param mobileFeature MobileFeature object that holds data has to be updated. + * @return The status of the operation. + * @throws MobileDeviceManagementDAOException + */ + boolean updateFeature(MobileFeature mobileFeature) throws MobileDeviceManagementDAOException; + + /** + * Deletes a MobileFeature from Mobile-Feature table when the feature id is given. + * + * @param mblFeatureId MobileFeature id of the MobileFeature to be deleted. + * @return The status of the operation. + * @throws MobileDeviceManagementDAOException + */ + boolean deleteFeatureById(int mblFeatureId) throws MobileDeviceManagementDAOException; + + /** + * Deletes a MobileFeature from Mobile-Feature table when the feature code is given. + * + * @param mblFeatureCode MobileFeature code of the feature to be deleted. + * @return The status of the operation. + * @throws MobileDeviceManagementDAOException + */ + boolean deleteFeatureByCode(String mblFeatureCode) throws MobileDeviceManagementDAOException; + + /** + * Retrieves a given MobileFeature from Mobile-Feature table when the feature id is given. + * + * @param mblFeatureId Feature id of the feature to be retrieved. + * @return MobileFeature object that holds data of the feature represented by featureId. + * @throws MobileDeviceManagementDAOException + */ + MobileFeature getFeatureById(int mblFeatureId) throws MobileDeviceManagementDAOException; + + /** + * Retrieves a given MobileFeature from Mobile-Feature table when the feature code is given. + * + * @param mblFeatureCode Feature code of the feature to be retrieved. + * @return MobileFeature object that holds data of the feature represented by featureCode. + * @throws MobileDeviceManagementDAOException + */ + MobileFeature getFeatureByCode(String mblFeatureCode) throws MobileDeviceManagementDAOException; + + /** + * Retrieves all MobileFeatures of a MobileDevice type from Mobile-Feature table. + * + * @param deviceType MobileDevice type of the MobileFeatures to be retrieved + * @return MobileFeature object list. + * @throws MobileDeviceManagementDAOException + */ + List getFeatureByDeviceType(String deviceType) throws MobileDeviceManagementDAOException; + + /** + * Retrieve all the MobileFeatures from Mobile-Feature table. + * + * @return MobileFeature object list. + * @throws MobileDeviceManagementDAOException + */ + List getAllFeatures() throws MobileDeviceManagementDAOException; +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidDeviceDAOImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidDeviceDAOImpl.java new file mode 100644 index 000000000..416a4d90d --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidDeviceDAOImpl.java @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.AndroidDAOFactory; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileDeviceDAO; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.util.MobileDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileDevice; +import org.wso2.carbon.device.mgt.mobile.android.impl.util.AndroidPluginConstants; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Implements MobileDeviceDAO for Android Devices. + */ +public class AndroidDeviceDAOImpl implements MobileDeviceDAO{ + + private static final Log log = LogFactory.getLog(AndroidDeviceDAOImpl.class); + + @Override + public MobileDevice getMobileDevice(String mblDeviceId) throws MobileDeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + MobileDevice mobileDevice = null; + ResultSet rs = null; + try { + conn = AndroidDAOFactory.getConnection(); + String selectDBQuery = + "SELECT DEVICE_ID, FCM_TOKEN, DEVICE_INFO, DEVICE_MODEL, SERIAL, " + + "VENDOR, MAC_ADDRESS, DEVICE_NAME, LATITUDE, LONGITUDE, IMEI, IMSI, OS_VERSION, OS_BUILD_DATE" + + " FROM AD_DEVICE WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, mblDeviceId); + rs = stmt.executeQuery(); + + if (rs.next()) { + mobileDevice = new MobileDevice(); + mobileDevice.setMobileDeviceId(rs.getString(AndroidPluginConstants.DEVICE_ID)); + mobileDevice.setModel(rs.getString(AndroidPluginConstants.DEVICE_MODEL)); + mobileDevice.setSerial(rs.getString(AndroidPluginConstants.SERIAL)); + mobileDevice.setVendor(rs.getString(AndroidPluginConstants.VENDOR)); + mobileDevice.setLatitude(rs.getString(AndroidPluginConstants.LATITUDE)); + mobileDevice.setLongitude(rs.getString(AndroidPluginConstants.LONGITUDE)); + mobileDevice.setImei(rs.getString(AndroidPluginConstants.IMEI)); + mobileDevice.setImsi(rs.getString(AndroidPluginConstants.IMSI)); + mobileDevice.setOsVersion(rs.getString(AndroidPluginConstants.OS_VERSION)); + mobileDevice.setOsBuildDate(rs.getString(AndroidPluginConstants.OS_BUILD_DATE)); + + Map propertyMap = new HashMap(); + propertyMap.put(AndroidPluginConstants.FCM_TOKEN, rs.getString(AndroidPluginConstants.FCM_TOKEN)); + propertyMap.put(AndroidPluginConstants.DEVICE_INFO, rs.getString(AndroidPluginConstants.DEVICE_INFO)); + propertyMap.put(AndroidPluginConstants.DEVICE_NAME, rs.getString(AndroidPluginConstants.DEVICE_NAME)); + mobileDevice.setDeviceProperties(propertyMap); + + if (log.isDebugEnabled()) { + log.debug("Android device " + mblDeviceId + " data has been fetched from " + + "Android database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching Android device : '" + mblDeviceId + "'"; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); + AndroidDAOFactory.closeConnection(); + } + + return mobileDevice; + } + + @Override + public boolean addMobileDevice(MobileDevice mobileDevice) throws MobileDeviceManagementDAOException { + boolean status = false; + Connection conn; + PreparedStatement stmt = null; + try { + conn = AndroidDAOFactory.getConnection(); + String createDBQuery = + "INSERT INTO AD_DEVICE(DEVICE_ID, FCM_TOKEN, DEVICE_INFO, SERIAL, " + + "VENDOR, MAC_ADDRESS, DEVICE_NAME, LATITUDE, LONGITUDE, IMEI, IMSI, " + + "OS_VERSION, DEVICE_MODEL, OS_BUILD_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + stmt = conn.prepareStatement(createDBQuery); + stmt.setString(1, mobileDevice.getMobileDeviceId()); + + Map properties = mobileDevice.getDeviceProperties(); + stmt.setString(2, properties.get(AndroidPluginConstants.FCM_TOKEN)); + stmt.setString(3, properties.get(AndroidPluginConstants.DEVICE_INFO)); + stmt.setString(4, mobileDevice.getSerial()); + stmt.setString(5, mobileDevice.getVendor()); + stmt.setString(6, mobileDevice.getMobileDeviceId()); + stmt.setString(7, properties.get(AndroidPluginConstants.DEVICE_NAME)); + stmt.setString(8, mobileDevice.getLatitude()); + stmt.setString(9, mobileDevice.getLongitude()); + stmt.setString(10, mobileDevice.getImei()); + stmt.setString(11, mobileDevice.getImsi()); + stmt.setString(12, mobileDevice.getOsVersion()); + stmt.setString(13, mobileDevice.getModel()); + stmt.setString(14, mobileDevice.getOsBuildDate()); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Android device " + mobileDevice.getMobileDeviceId() + " data has been" + + " added to the Android database."); + } + } + } catch (SQLException e) { + throw new MobileDeviceManagementDAOException("Error occurred while adding the Android device '" + + mobileDevice.getMobileDeviceId() + "' information to the Android plugin data store.", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public boolean updateMobileDevice(MobileDevice mobileDevice) throws MobileDeviceManagementDAOException { + boolean status = false; + Connection conn; + PreparedStatement stmt = null; + try { + conn = AndroidDAOFactory.getConnection(); + String updateDBQuery = + "UPDATE AD_DEVICE SET FCM_TOKEN = ?, DEVICE_INFO = ?, SERIAL = ?, VENDOR = ?, " + + "MAC_ADDRESS = ?, DEVICE_NAME = ?, LATITUDE = ?, LONGITUDE = ?, IMEI = ?, " + + "IMSI = ?, OS_VERSION = ?, DEVICE_MODEL = ?, OS_BUILD_DATE = ? WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(updateDBQuery); + + Map properties = mobileDevice.getDeviceProperties(); + stmt.setString(1, properties.get(AndroidPluginConstants.FCM_TOKEN)); + stmt.setString(2, properties.get(AndroidPluginConstants.DEVICE_INFO)); + stmt.setString(3, mobileDevice.getSerial()); + stmt.setString(4, mobileDevice.getVendor()); + stmt.setString(5, properties.get(AndroidPluginConstants.MAC_ADDRESS)); + stmt.setString(6, properties.get(AndroidPluginConstants.DEVICE_NAME)); + stmt.setString(7, mobileDevice.getLatitude()); + stmt.setString(8, mobileDevice.getLongitude()); + stmt.setString(9, mobileDevice.getImei()); + stmt.setString(10, mobileDevice.getImsi()); + stmt.setString(11, mobileDevice.getOsVersion()); + stmt.setString(12, mobileDevice.getModel()); + stmt.setString(13, mobileDevice.getOsBuildDate()); + stmt.setString(14, mobileDevice.getMobileDeviceId()); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Android device " + mobileDevice.getMobileDeviceId() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the Android device '" + + mobileDevice.getMobileDeviceId() + "' data."; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public boolean deleteMobileDevice(String mblDeviceId) + throws MobileDeviceManagementDAOException { + boolean status = false; + Connection conn; + PreparedStatement stmt = null; + try { + conn = AndroidDAOFactory.getConnection(); + String deleteDBQuery = + "DELETE FROM AD_DEVICE WHERE DEVICE_ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, mblDeviceId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Android device " + mblDeviceId + " data has deleted" + + " from the Android database."); + } + } + } catch (SQLException e) { + throw new MobileDeviceManagementDAOException("Error occurred while deleting android device '" + + mblDeviceId + "'", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public List getAllMobileDevices() throws MobileDeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + MobileDevice mobileDevice; + List mobileDevices = new ArrayList(); + try { + conn = AndroidDAOFactory.getConnection(); + String selectDBQuery = + "SELECT DEVICE_ID, FCM_TOKEN, DEVICE_INFO, DEVICE_MODEL, SERIAL, " + + "VENDOR, MAC_ADDRESS, DEVICE_NAME, LATITUDE, LONGITUDE, IMEI, IMSI, OS_VERSION, OS_BUILD_DATE " + + "FROM AD_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + rs = stmt.executeQuery(); + + while (rs.next()) { + mobileDevice = new MobileDevice(); + mobileDevice.setMobileDeviceId(rs.getString(AndroidPluginConstants.DEVICE_ID)); + mobileDevice.setModel(rs.getString(AndroidPluginConstants.DEVICE_MODEL)); + mobileDevice.setSerial(rs.getString(AndroidPluginConstants.SERIAL)); + mobileDevice.setVendor(rs.getString(AndroidPluginConstants.VENDOR)); + mobileDevice.setLatitude(rs.getString(AndroidPluginConstants.LATITUDE)); + mobileDevice.setLongitude(rs.getString(AndroidPluginConstants.LONGITUDE)); + mobileDevice.setImei(rs.getString(AndroidPluginConstants.IMEI)); + mobileDevice.setImsi(rs.getString(AndroidPluginConstants.IMSI)); + mobileDevice.setOsVersion(rs.getString(AndroidPluginConstants.OS_VERSION)); + mobileDevice.setOsBuildDate(rs.getString(AndroidPluginConstants.OS_BUILD_DATE)); + + Map propertyMap = new HashMap<>(); + propertyMap.put(AndroidPluginConstants.FCM_TOKEN, rs.getString(AndroidPluginConstants.FCM_TOKEN)); + propertyMap.put(AndroidPluginConstants.DEVICE_INFO, rs.getString(AndroidPluginConstants.DEVICE_INFO)); + propertyMap.put(AndroidPluginConstants.DEVICE_NAME, rs.getString(AndroidPluginConstants.DEVICE_NAME)); + mobileDevice.setDeviceProperties(propertyMap); + + mobileDevices.add(mobileDevice); + } + if (log.isDebugEnabled()) { + log.debug("All Android device details have fetched from Android database."); + } + return mobileDevices; + } catch (SQLException e) { + throw new MobileDeviceManagementDAOException("Error occurred while fetching all Android device data", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); + AndroidDAOFactory.closeConnection(); + } + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/AndroidDeviceMgtPluginException.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidDeviceMgtPluginException.java similarity index 87% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/AndroidDeviceMgtPluginException.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidDeviceMgtPluginException.java index d73a1e8cc..4a0b6a1c7 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/exception/AndroidDeviceMgtPluginException.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidDeviceMgtPluginException.java @@ -15,11 +15,10 @@ * specific language governing permissions and limitations * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.exception; +package org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl; -import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; -public class AndroidDeviceMgtPluginException extends DeviceManagementException { +public class AndroidDeviceMgtPluginException extends Exception{ private static final long serialVersionUID = -2297311387874900305L; private String errorMessage; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidFeatureDAOImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidFeatureDAOImpl.java new file mode 100644 index 000000000..7a6de77b5 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/AndroidFeatureDAOImpl.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.AndroidDAOFactory; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.AndroidFeatureManagementDAOException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileFeatureDAO; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.util.MobileDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileFeature; +import org.wso2.carbon.device.mgt.mobile.android.impl.util.AndroidPluginConstants; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class AndroidFeatureDAOImpl implements MobileFeatureDAO { + + private static final Log log = LogFactory.getLog(AndroidFeatureDAOImpl.class); + + public AndroidFeatureDAOImpl() { + + } + + @Override + public boolean addFeature(MobileFeature mobileFeature) throws MobileDeviceManagementDAOException { + PreparedStatement stmt = null; + boolean status = false; + Connection conn; + try { + conn = AndroidDAOFactory.getConnection(); + String sql = "INSERT INTO AD_FEATURE(CODE, NAME, DESCRIPTION) VALUES (?, ?, ?)"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, mobileFeature.getCode()); + stmt.setString(2, mobileFeature.getName()); + stmt.setString(3, mobileFeature.getDescription()); + stmt.executeUpdate(); + status = true; + } catch (SQLException e) { + throw new AndroidFeatureManagementDAOException( + "Error occurred while adding android feature '" + + mobileFeature.getName() + "' into the metadata repository", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public boolean addFeatures(List mobileFeatures) throws MobileDeviceManagementDAOException { + PreparedStatement stmt = null; + MobileFeature mobileFeature; + boolean status = false; + Connection conn; + try { + conn = AndroidDAOFactory.getConnection(); + stmt = conn.prepareStatement("INSERT INTO AD_FEATURE(CODE, NAME, DESCRIPTION) VALUES (?, ?, ?)"); + for (int i = 0; i < mobileFeatures.size(); i++) { + mobileFeature = mobileFeatures.get(i); + stmt.setString(1, mobileFeature.getCode()); + stmt.setString(2, mobileFeature.getName()); + stmt.setString(3, mobileFeature.getDescription()); + stmt.addBatch(); + } + stmt.executeBatch(); + status = true; + } catch (SQLException e) { + throw new AndroidFeatureManagementDAOException( + "Error occurred while adding android features into the metadata repository", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public boolean updateFeature(MobileFeature mobileFeature) throws MobileDeviceManagementDAOException { + boolean status = false; + Connection conn; + PreparedStatement stmt = null; + try { + conn = AndroidDAOFactory.getConnection(); + String updateDBQuery = + "UPDATE AD_FEATURE SET NAME = ?, DESCRIPTION = ?" + + "WHERE CODE = ?"; + + stmt = conn.prepareStatement(updateDBQuery); + stmt.setString(1, mobileFeature.getName()); + stmt.setString(2, mobileFeature.getDescription()); + stmt.setString(3, mobileFeature.getCode()); + + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Android Feature " + mobileFeature.getCode() + " data has been " + + "modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while updating the Android Feature '" + + mobileFeature.getCode() + "' to the Android db."; + log.error(msg, e); + throw new AndroidFeatureManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public boolean deleteFeatureById(int mblFeatureId) throws MobileDeviceManagementDAOException { + + PreparedStatement stmt = null; + boolean status = false; + Connection conn; + try { + conn = AndroidDAOFactory.getConnection(); + String sql = "DELETE FROM AD_FEATURE WHERE ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, mblFeatureId); + stmt.execute(); + status = true; + } catch (SQLException e) { + throw new AndroidFeatureManagementDAOException( + "Error occurred while deleting android feature '" + + mblFeatureId + "' from Android database.", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public boolean deleteFeatureByCode(String mblFeatureCode) throws MobileDeviceManagementDAOException { + PreparedStatement stmt = null; + boolean status = false; + Connection conn; + try { + conn = AndroidDAOFactory.getConnection(); + String sql = "DELETE FROM AD_FEATURE WHERE CODE = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, mblFeatureCode); + stmt.execute(); + status = true; + } catch (SQLException e) { + throw new AndroidFeatureManagementDAOException( + "Error occurred while deleting android feature '" + + mblFeatureCode + "' from Android database.", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public MobileFeature getFeatureById(int mblFeatureId) throws MobileDeviceManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Connection conn; + try { + conn = AndroidDAOFactory.getConnection(); + String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM AD_FEATURE WHERE ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, mblFeatureId); + rs = stmt.executeQuery(); + + MobileFeature mobileFeature = null; + if (rs.next()) { + mobileFeature = new MobileFeature(); + mobileFeature.setId(rs.getInt(AndroidPluginConstants.ANDROID_FEATURE_ID)); + mobileFeature.setCode(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_CODE)); + mobileFeature.setName(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_NAME)); + mobileFeature.setDescription(rs.getString(AndroidPluginConstants. + ANDROID_FEATURE_DESCRIPTION)); + mobileFeature.setDeviceType( + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + } + return mobileFeature; + } catch (SQLException e) { + throw new AndroidFeatureManagementDAOException( + "Error occurred while retrieving android feature '" + + mblFeatureId + "' from the Android database.", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); + AndroidDAOFactory.closeConnection(); + } + } + + @Override + public MobileFeature getFeatureByCode(String mblFeatureCode) throws MobileDeviceManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Connection conn; + + try { + conn = AndroidDAOFactory.getConnection(); + String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM AD_FEATURE WHERE CODE = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, mblFeatureCode); + rs = stmt.executeQuery(); + + MobileFeature mobileFeature = null; + if (rs.next()) { + mobileFeature = new MobileFeature(); + mobileFeature.setId(rs.getInt(AndroidPluginConstants.ANDROID_FEATURE_ID)); + mobileFeature.setCode(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_CODE)); + mobileFeature.setName(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_NAME)); + mobileFeature.setDescription(rs.getString(AndroidPluginConstants. + ANDROID_FEATURE_DESCRIPTION)); + mobileFeature.setDeviceType( + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + } + return mobileFeature; + } catch (SQLException e) { + throw new AndroidFeatureManagementDAOException( + "Error occurred while retrieving android feature '" + + mblFeatureCode + "' from the Android database.", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); + AndroidDAOFactory.closeConnection(); + } + } + + @Override + public List getFeatureByDeviceType(String deviceType) + throws MobileDeviceManagementDAOException { + return this.getAllFeatures(); + } + + @Override + public List getAllFeatures() throws MobileDeviceManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Connection conn = null; + List features = new ArrayList<>(); + try { + conn = AndroidDAOFactory.getConnection(); + String sql = "SELECT ID, CODE, NAME, DESCRIPTION FROM AD_FEATURE"; + stmt = conn.prepareStatement(sql); + rs = stmt.executeQuery(); + MobileFeature mobileFeature = null; + + while (rs.next()) { + mobileFeature = new MobileFeature(); + mobileFeature.setId(rs.getInt(AndroidPluginConstants.ANDROID_FEATURE_ID)); + mobileFeature.setCode(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_CODE)); + mobileFeature.setName(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_NAME)); + mobileFeature.setDescription(rs.getString(AndroidPluginConstants.ANDROID_FEATURE_DESCRIPTION)); + mobileFeature.setDeviceType( + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID); + features.add(mobileFeature); + } + return features; + } catch (SQLException e) { + throw new AndroidFeatureManagementDAOException("Error occurred while retrieving all " + + "android features from the android database.", e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(stmt, rs); + AndroidDAOFactory.closeConnection(); + } + } +} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/MobileFeatureDAOImpl.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/MobileFeatureDAOImpl.java new file mode 100644 index 000000000..eeade1e6a --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/impl/MobileFeatureDAOImpl.java @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.MobileFeatureDAO; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.util.MobileDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileFeature; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * Implementation of MobileFeatureDAO. + */ +public class MobileFeatureDAOImpl implements MobileFeatureDAO { + + private DataSource dataSource; + private static final Log log = LogFactory.getLog(MobileFeatureDAOImpl.class); + + public MobileFeatureDAOImpl(DataSource dataSource) { + this.dataSource = dataSource; + } + + @Override + public boolean addFeature(MobileFeature mobileFeature) + throws MobileDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String createDBQuery = + "INSERT INTO AD_FEATURE(CODE, NAME, DESCRIPTION, DEVICE_TYPE) VALUES (?, ?, ?, ?)"; + + stmt = conn.prepareStatement(createDBQuery); + stmt.setString(1, mobileFeature.getCode()); + stmt.setString(2, mobileFeature.getName()); + stmt.setString(3, mobileFeature.getDescription()); + stmt.setString(4, mobileFeature.getDeviceType()); + int rows = stmt.executeUpdate(); + if (rows > 0) { + if (log.isDebugEnabled()) { + log.debug("Added a new MobileFeature " + mobileFeature.getCode() + " to the MDM database."); + } + status = true; + } + } catch (SQLException e) { + String msg = "Error occurred while adding feature code - '" + + mobileFeature.getCode() + "' to feature table"; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null); + } + return status; + } + + @Override + public boolean addFeatures(List mobileFeatures) throws MobileDeviceManagementDAOException { + return false; + } + + @Override + public boolean updateFeature(MobileFeature mobileFeature) + throws MobileDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String updateDBQuery = + "UPDATE AD_FEATURE SET CODE = ?, NAME = ?, DESCRIPTION = ?, DEVICE_TYPE = ?" + + " WHERE ID = ?"; + stmt = conn.prepareStatement(updateDBQuery); + stmt.setString(1, mobileFeature.getCode()); + stmt.setString(2, mobileFeature.getName()); + stmt.setString(3, mobileFeature.getDescription()); + stmt.setString(4, mobileFeature.getDeviceType()); + stmt.setInt(5, mobileFeature.getId()); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Updated MobileFeature " + mobileFeature.getCode()); + } + } + } catch (SQLException e) { + String msg = "Error occurred while updating the feature with feature code - '" + + mobileFeature.getId() + "'"; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null); + } + return status; + } + + @Override + public boolean deleteFeatureByCode(String mblFeatureCode) + throws MobileDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String deleteDBQuery = + "DELETE FROM AD_FEATURE WHERE CODE = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, mblFeatureCode); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Deleted MobileFeature code " + mblFeatureCode + " from the MDM database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting feature with code - " + mblFeatureCode; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null); + } + return status; + } + + @Override + public boolean deleteFeatureById(int mblFeatureId) + throws MobileDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + String deleteDBQuery = + "DELETE FROM AD_FEATURE WHERE ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setInt(1, mblFeatureId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Deleted MobileFeature id " + mblFeatureId + " from the MDM database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting feature with id - " + mblFeatureId; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, null); + } + return status; + } + + @Override + public MobileFeature getFeatureByCode(String mblFeatureCode) + throws MobileDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + MobileFeature mobileFeature = null; + ResultSet resultSet = null; + try { + conn = this.getConnection(); + String selectDBQuery = + "SELECT ID, CODE, NAME, DESCRIPTION, DEVICE_TYPE FROM AD_FEATURE " + + "WHERE CODE = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, mblFeatureCode); + resultSet = stmt.executeQuery(); + if (resultSet.next()) { + mobileFeature = new MobileFeature(); + mobileFeature.setId(resultSet.getInt(1)); + mobileFeature.setCode(resultSet.getString(2)); + mobileFeature.setName(resultSet.getString(3)); + mobileFeature.setDescription(resultSet.getString(4)); + mobileFeature.setDeviceType(resultSet.getString(5)); + if (log.isDebugEnabled()) { + log.debug("Fetched MobileFeature " + mblFeatureCode + " from the MDM database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching feature code - '" + mblFeatureCode + "'"; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, resultSet); + } + return mobileFeature; + } + + @Override + public MobileFeature getFeatureById(int mblFeatureId) + throws MobileDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + MobileFeature mobileFeature = null; + ResultSet resultSet = null; + try { + conn = this.getConnection(); + String selectDBQuery = + "SELECT ID, CODE, NAME, DESCRIPTION, DEVICE_TYPE FROM AD_FEATURE" + + " WHERE ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setInt(1, mblFeatureId); + resultSet = stmt.executeQuery(); + if (resultSet.next()) { + mobileFeature = new MobileFeature(); + mobileFeature.setId(resultSet.getInt(1)); + mobileFeature.setCode(resultSet.getString(2)); + mobileFeature.setName(resultSet.getString(3)); + mobileFeature.setDescription(resultSet.getString(4)); + mobileFeature.setDeviceType(resultSet.getString(5)); + if (log.isDebugEnabled()) { + log.debug("Fetched MobileFeatureId" + mblFeatureId + " from the MDM database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching feature id - '" + mblFeatureId + "'"; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, resultSet); + } + return mobileFeature; + } + + @Override + public List getAllFeatures() throws MobileDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + MobileFeature mobileFeature; + List mobileFeatures = new ArrayList(); + ResultSet resultSet = null; + try { + conn = this.getConnection(); + String selectDBQuery = + "SELECT ID, CODE, NAME, DESCRIPTION, DEVICE_TYPE FROM AD_FEATURE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + mobileFeature = new MobileFeature(); + mobileFeature.setId(resultSet.getInt(1)); + mobileFeature.setCode(resultSet.getString(2)); + mobileFeature.setName(resultSet.getString(3)); + mobileFeature.setDescription(resultSet.getString(4)); + mobileFeature.setDeviceType(resultSet.getString(5)); + mobileFeatures.add(mobileFeature); + } + if (log.isDebugEnabled()) { + log.debug("Fetched all MobileFeatures from the MDM database."); + } + return mobileFeatures; + } catch (SQLException e) { + String msg = "Error occurred while fetching all features.'"; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, resultSet); + } + } + + @Override + public List getFeatureByDeviceType(String deviceType) throws MobileDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + MobileFeature mobileFeature; + List mobileFeatures = new ArrayList<>(); + ResultSet resultSet = null; + try { + conn = this.getConnection(); + String selectDBQuery = + "SELECT ID, CODE, NAME, DESCRIPTION, DEVICE_TYPE FROM AD_FEATURE" + + " WHERE DEVICE_TYPE = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, deviceType); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + mobileFeature = new MobileFeature(); + mobileFeature.setId(resultSet.getInt(1)); + mobileFeature.setCode(resultSet.getString(2)); + mobileFeature.setName(resultSet.getString(3)); + mobileFeature.setDescription(resultSet.getString(4)); + mobileFeature.setDeviceType(resultSet.getString(5)); + mobileFeatures.add(mobileFeature); + } + if (log.isDebugEnabled()) { + log.debug("Fetched all MobileFeatures of type " + deviceType + " from the MDM" + + " database."); + } + return mobileFeatures; + } catch (SQLException e) { + String msg = "Error occurred while fetching all features.'"; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } finally { + MobileDeviceManagementDAOUtil.cleanupResources(conn, stmt, resultSet); + } + } + + private Connection getConnection() throws MobileDeviceManagementDAOException { + try { + return dataSource.getConnection(); + } catch (SQLException e) { + String msg = "Error occurred while obtaining a connection from the mobile specific " + + "datasource."; + log.error(msg, e); + throw new MobileDeviceManagementDAOException(msg, e); + } + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/util/MobileDeviceManagementDAOUtil.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/util/MobileDeviceManagementDAOUtil.java similarity index 98% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/util/MobileDeviceManagementDAOUtil.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/util/MobileDeviceManagementDAOUtil.java index decfbdb3b..0251c13aa 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.core/src/main/java/org/wso2/carbon/device/mgt/mobile/android/core/dao/util/MobileDeviceManagementDAOUtil.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dao/util/MobileDeviceManagementDAOUtil.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.core.dao.util; +package org.wso2.carbon.device.mgt.mobile.android.impl.dao.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -28,6 +28,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Hashtable; +import java.util.List; /** * Utility method required by MobileDeviceManagement DAO classes. diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileDevice.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileDevice.java similarity index 79% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileDevice.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileDevice.java index 7644cb3cc..daadfa824 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileDevice.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileDevice.java @@ -16,9 +16,10 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.dto; +package org.wso2.carbon.device.mgt.mobile.android.impl.dto; import java.io.Serializable; +import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -33,10 +34,6 @@ public class MobileDevice implements Serializable { private String vendor; private String latitude; private String longitude; - private String altitude; - private String speed; - private String bearing; - private String distance; private String imei; private String imsi; private String serial; @@ -96,38 +93,6 @@ public class MobileDevice implements Serializable { this.longitude = longitude; } - public String getSpeed() { - return speed; - } - - public void setSpeed(String speed) { - this.speed = speed; - } - - public String getBearing() { - return bearing; - } - - public String getDistance() { - return distance; - } - - public void setDistance(String distance) { - this.distance = distance; - } - - public void setBearing(String bearing) { - this.bearing = bearing; - } - - public String getAltitude() { - return altitude; - } - - public void setAltitude(String altitude) { - this.altitude = altitude; - } - public String getImei() { return imei; } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileDeviceOperationMapping.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileDeviceOperationMapping.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileDeviceOperationMapping.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileDeviceOperationMapping.java index 279f93883..ae855e2ab 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileDeviceOperationMapping.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileDeviceOperationMapping.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.dto; +package org.wso2.carbon.device.mgt.mobile.android.impl.dto; /** * DTO of Mobile Device Operation Mappings. diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileFeature.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileFeature.java similarity index 59% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileFeature.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileFeature.java index 576fd92c7..6568c9d5c 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileFeature.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileFeature.java @@ -16,25 +16,7 @@ * under the License. */ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common.dto; +package org.wso2.carbon.device.mgt.mobile.android.impl.dto; import java.io.Serializable; @@ -47,8 +29,6 @@ public class MobileFeature implements Serializable { private String deviceType; private String code; private String name; - private String type; - private boolean hidden; private String description; public int getId() { @@ -75,22 +55,6 @@ public class MobileFeature implements Serializable { this.name = name; } - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public boolean isHidden() { - return hidden; - } - - public void setHidden(boolean hidden) { - this.hidden = hidden; - } - public String getDescription() { return description; } diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileFeatureProperty.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileFeatureProperty.java new file mode 100644 index 000000000..fb226d107 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileFeatureProperty.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.dto; + +/** + * DTO of Mobile feature property. Represents a property of a mobile feature. + */ +public class MobileFeatureProperty { + + private String property; + private Integer featureID; + + public Integer getFeatureID() { + return featureID; + } + + public void setFeatureID(Integer featureID) { + this.featureID = featureID; + } + + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + +} \ No newline at end of file diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileOperation.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileOperation.java similarity index 96% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileOperation.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileOperation.java index 5f1571394..fa9723484 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileOperation.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileOperation.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.dto; +package org.wso2.carbon.device.mgt.mobile.android.impl.dto; import java.util.List; diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileOperationProperty.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileOperationProperty.java similarity index 95% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileOperationProperty.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileOperationProperty.java index 04f7b58d5..5147bb004 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/dto/MobileOperationProperty.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/dto/MobileOperationProperty.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.device.mgt.mobile.android.common.dto; +package org.wso2.carbon.device.mgt.mobile.android.impl.dto; /** * DTO of Mobile Operation property. diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/AndroidPluginConstants.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidPluginConstants.java similarity index 70% rename from components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/AndroidPluginConstants.java rename to components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidPluginConstants.java index dbf5e77f6..09b278e2c 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.common/src/main/java/org/wso2/carbon/device/mgt/mobile/android/common/AndroidPluginConstants.java +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidPluginConstants.java @@ -16,25 +16,7 @@ * under the License. */ -/* - * Copyright (c) 2019, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.device.mgt.mobile.android.common; +package org.wso2.carbon.device.mgt.mobile.android.impl.util; /** * Defines constants used by android plugin. @@ -57,15 +39,10 @@ public final class AndroidPluginConstants { public static final String OS_BUILD_DATE = "OS_BUILD_DATE"; public static final String MAC_ADDRESS = "MAC"; - public static final String GOOGLE_AFW_EMM_ANDROID_ID = "googleEMMAndroidId"; - public static final String GOOGLE_AFW_DEVICE_ID = "googleEMMDeviceId"; - //Properties related to AD_FEATURE table public static final String ANDROID_FEATURE_ID = "ID"; public static final String ANDROID_FEATURE_CODE = "CODE"; public static final String ANDROID_FEATURE_NAME = "NAME"; - public static final String ANDROID_FEATURE_TYPE = "TYPE"; - public static final String ANDROID_FEATURE_HIDDEN = "HIDDEN"; public static final String ANDROID_FEATURE_DESCRIPTION = "DESCRIPTION"; public static final class NotifierType { diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidPluginUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidPluginUtils.java new file mode 100644 index 000000000..40ea3c18b --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidPluginUtils.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.util; + +import org.wso2.carbon.device.mgt.common.license.mgt.License; +import org.wso2.carbon.device.mgt.mobile.android.impl.AndroidDeviceManagementService; + +/** + * Contains utility methods used by Android plugin. + */ +public class AndroidPluginUtils { + + public static License getDefaultLicense() { + License license = new License(); + license.setName(AndroidDeviceManagementService.DEVICE_TYPE_ANDROID); + license.setLanguage("en_US"); + license.setVersion("1.0.0"); + license.setText("This End User License Agreement (\"Agreement\") is a legal agreement between you (\"You\") " + + "and WSO2, Inc., regarding the enrollment of Your personal mobile device (\"Device\") in SoR's " + + "mobile device management program, and the loading to and removal from Your Device and Your use " + + "of certain applications and any associated software and user documentation, whether provided in " + + "\"online\" or electronic format, used in connection with the operation of or provision of services " + + "to WSO2, Inc., BY SELECTING \"I ACCEPT\" DURING INSTALLATION, YOU ARE ENROLLING YOUR DEVICE, AND " + + "THEREBY AUTHORIZING SOR OR ITS AGENTS TO INSTALL, UPDATE AND REMOVE THE APPS FROM YOUR DEVICE AS " + + "DESCRIBED IN THIS AGREEMENT. YOU ARE ALSO EXPLICITLY ACKNOWLEDGING AND AGREEING THAT (1) THIS IS " + + "A BINDING CONTRACT AND (2) YOU HAVE READ AND AGREE TO THE TERMS OF THIS AGREEMENT.\n" + + "\n" + + "IF YOU DO NOT ACCEPT THESE TERMS, DO NOT ENROLL YOUR DEVICE AND DO NOT PROCEED ANY FURTHER.\n" + + "\n" + + "You agree that: (1) You understand and agree to be bound by the terms and conditions contained " + + "in this Agreement, and (2) You are at least 21 years old and have the legal capacity to enter " + + "into this Agreement as defined by the laws of Your jurisdiction. SoR shall have the right, " + + "without prior notice, to terminate or suspend (i) this Agreement, (ii) the enrollment of Your " + + "Device, or (iii) the functioning of the Apps in the event of a violation of this Agreement or " + + "the cessation of Your relationship with SoR (including termination of Your employment if You are " + + "an employee or expiration or termination of Your applicable franchise or supply agreement if You " + + "are a franchisee of or supplier to the WSO2 WSO2, Inc., system). SoR expressly reserves all " + + "rights not expressly granted herein."); + return license; + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidUtils.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidUtils.java new file mode 100644 index 000000000..583a6cef0 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/AndroidUtils.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.util; + +import java.util.Map; + +/** + * Contains utility methods used by Android plugin. + */ +public class AndroidUtils { + + public static String getDeviceProperty(Map deviceProperties, String property) { + return deviceProperties.get(property); + } +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/MobileDeviceManagementUtil.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/MobileDeviceManagementUtil.java new file mode 100644 index 000000000..163763919 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/impl/util/MobileDeviceManagementUtil.java @@ -0,0 +1,339 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.common.Feature; +import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.mobile.android.impl.dao.impl.AndroidDeviceMgtPluginException; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileDevice; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileDeviceOperationMapping; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileFeature; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileOperation; +import org.wso2.carbon.device.mgt.mobile.android.impl.dto.MobileOperationProperty; +import org.wso2.carbon.device.mgt.mobile.android.internal.AndroidDeviceManagementDataHolder; +import org.wso2.carbon.registry.api.RegistryException; +import org.wso2.carbon.registry.api.Resource; +import org.wso2.carbon.registry.core.Registry; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * Provides utility methods required by the mobile device management bundle. + */ +public class MobileDeviceManagementUtil { + + private static final Log log = LogFactory.getLog(MobileDeviceManagementUtil.class); + private static final String MOBILE_DEVICE_IMEI = "IMEI"; + private static final String MOBILE_DEVICE_IMSI = "IMSI"; + private static final String MOBILE_DEVICE_VENDOR = "VENDOR"; + private static final String MOBILE_DEVICE_OS_VERSION = "OS_VERSION"; + private static final String MOBILE_DEVICE_MODEL = "DEVICE_MODEL"; + private static final String MOBILE_DEVICE_LATITUDE = "LATITUDE"; + private static final String MOBILE_DEVICE_LONGITUDE = "LONGITUDE"; + private static final String MOBILE_DEVICE_SERIAL = "SERIAL"; + private static final String MOBILE_DEVICE_OS_BUILD_DATE = "OS_BUILD_DATE"; + + public static Document convertToDocument(File file) throws DeviceManagementException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + try { + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + return docBuilder.parse(file); + } catch (Exception e) { + throw new DeviceManagementException( + "Error occurred while parsing file, while converting " + + "to a org.w3c.dom.Document : " + e.getMessage(), e); + } + } + + private static String getPropertyValue(Device device, String property) { + if (device != null && device.getProperties() != null) { + for (Device.Property prop : device.getProperties()) { + if (property.equals(prop.getName())) { + return prop.getValue(); + } + } + } + return null; + } + + private static Device.Property getProperty(String property, String value) { + if (property != null) { + Device.Property prop = new Device.Property(); + prop.setName(property); + prop.setValue(value); + return prop; + } + return null; + } + + public static MobileDevice convertToMobileDevice(Device device) { + MobileDevice mobileDevice = null; + if (device != null) { + mobileDevice = new MobileDevice(); + mobileDevice.setMobileDeviceId(device.getDeviceIdentifier()); + mobileDevice.setImei(getPropertyValue(device, MOBILE_DEVICE_IMEI)); + mobileDevice.setImsi(getPropertyValue(device, MOBILE_DEVICE_IMSI)); + mobileDevice.setModel(getPropertyValue(device, MOBILE_DEVICE_MODEL)); + mobileDevice.setOsVersion(getPropertyValue(device, MOBILE_DEVICE_OS_VERSION)); + mobileDevice.setVendor(getPropertyValue(device, MOBILE_DEVICE_VENDOR)); + mobileDevice.setLatitude(getPropertyValue(device, MOBILE_DEVICE_LATITUDE)); + mobileDevice.setLongitude(getPropertyValue(device, MOBILE_DEVICE_LONGITUDE)); + mobileDevice.setSerial(getPropertyValue(device, MOBILE_DEVICE_SERIAL)); + mobileDevice.setOsBuildDate(getPropertyValue(device, MOBILE_DEVICE_OS_BUILD_DATE)); + + if (device.getProperties() != null) { + Map deviceProperties = new HashMap(); + for (Device.Property deviceProperty : device.getProperties()) { + deviceProperties.put(deviceProperty.getName(), deviceProperty.getValue()); + } + + mobileDevice.setDeviceProperties(deviceProperties); + } else { + mobileDevice.setDeviceProperties(new HashMap()); + } + } + return mobileDevice; + } + + public static Device convertToDevice(MobileDevice mobileDevice) { + Device device = null; + if (mobileDevice != null) { + device = new Device(); + List propertyList = new ArrayList(); + propertyList.add(getProperty(MOBILE_DEVICE_IMEI, mobileDevice.getImei())); + propertyList.add(getProperty(MOBILE_DEVICE_IMSI, mobileDevice.getImsi())); + propertyList.add(getProperty(MOBILE_DEVICE_MODEL, mobileDevice.getModel())); + propertyList.add(getProperty(MOBILE_DEVICE_OS_VERSION, mobileDevice.getOsVersion())); + propertyList.add(getProperty(MOBILE_DEVICE_OS_BUILD_DATE, mobileDevice.getOsBuildDate())); + propertyList.add(getProperty(MOBILE_DEVICE_VENDOR, mobileDevice.getVendor())); + if(mobileDevice.getLatitude() != null) { + propertyList.add(getProperty(MOBILE_DEVICE_LATITUDE, mobileDevice.getLatitude())); + } + if(mobileDevice.getLongitude() != null) { + propertyList.add(getProperty(MOBILE_DEVICE_LONGITUDE, mobileDevice.getLongitude())); + } + propertyList.add(getProperty(MOBILE_DEVICE_SERIAL, mobileDevice.getSerial())); + + if (mobileDevice.getDeviceProperties() != null) { + for (Map.Entry deviceProperty : mobileDevice.getDeviceProperties() + .entrySet()) { + propertyList + .add(getProperty(deviceProperty.getKey(), deviceProperty.getValue())); + } + } + + device.setProperties(propertyList); + device.setDeviceIdentifier(mobileDevice.getMobileDeviceId()); + } + return device; + } + + public static MobileOperation convertToMobileOperation(Operation operation) { + MobileOperation mobileOperation = new MobileOperation(); + MobileOperationProperty operationProperty; + List properties = new LinkedList(); + mobileOperation.setFeatureCode(operation.getCode()); + mobileOperation.setCreatedDate(new Date().getTime()); + Properties operationProperties = operation.getProperties(); + for (String key : operationProperties.stringPropertyNames()) { + operationProperty = new MobileOperationProperty(); + operationProperty.setProperty(key); + operationProperty.setValue(operationProperties.getProperty(key)); + properties.add(operationProperty); + } + mobileOperation.setProperties(properties); + return mobileOperation; + } + + public static List getMobileOperationIdsFromMobileDeviceOperations( + List mobileDeviceOperationMappings) { + List mobileOperationIds = new ArrayList(mobileDeviceOperationMappings.size()); + for (MobileDeviceOperationMapping mobileDeviceOperationMapping : mobileDeviceOperationMappings) { + mobileOperationIds.add(mobileDeviceOperationMapping.getOperationId()); + } + return mobileOperationIds; + } + + public static Operation convertMobileOperationToOperation(MobileOperation mobileOperation) { + Operation operation = new Operation(); + Properties properties = new Properties(); + operation.setCode(mobileOperation.getFeatureCode()); + for (MobileOperationProperty mobileOperationProperty : mobileOperation.getProperties()) { + properties + .put(mobileOperationProperty.getProperty(), mobileOperationProperty.getValue()); + } + operation.setProperties(properties); + return operation; + } + + public static MobileFeature convertToMobileFeature(Feature feature) { + MobileFeature mobileFeature = new MobileFeature(); + mobileFeature.setName(feature.getName()); + mobileFeature.setCode(feature.getCode()); + mobileFeature.setDescription(feature.getDescription()); + mobileFeature.setDeviceType(feature.getDeviceType()); + return mobileFeature; + } + + public static Feature convertToFeature(MobileFeature mobileFeature) { + Feature feature = new Feature(); + feature.setDescription(mobileFeature.getDescription()); + feature.setDeviceType(mobileFeature.getDeviceType()); + feature.setCode(mobileFeature.getCode()); + feature.setName(mobileFeature.getName()); + return feature; + } + + public static Registry getConfigurationRegistry() throws AndroidDeviceMgtPluginException { + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + return AndroidDeviceManagementDataHolder.getInstance().getRegistryService() + .getConfigSystemRegistry( + tenantId); + } catch (RegistryException e) { + throw new AndroidDeviceMgtPluginException( + "Error in retrieving conf registry instance: " + + e.getMessage(), e); + } + } + + public static Resource getRegistryResource(String path) throws AndroidDeviceMgtPluginException { + try { + if(MobileDeviceManagementUtil.getConfigurationRegistry().resourceExists(path)){ + return MobileDeviceManagementUtil.getConfigurationRegistry().get(path); + } + return null; + } catch (RegistryException e) { + throw new AndroidDeviceMgtPluginException("Error in retrieving registry resource : " + + e.getMessage(), e); + } + } + + public static boolean putRegistryResource(String path, + Resource resource) + throws AndroidDeviceMgtPluginException { + boolean status; + try { + MobileDeviceManagementUtil.getConfigurationRegistry().beginTransaction(); + MobileDeviceManagementUtil.getConfigurationRegistry().put(path, resource); + MobileDeviceManagementUtil.getConfigurationRegistry().commitTransaction(); + status = true; + } catch (RegistryException e) { + throw new AndroidDeviceMgtPluginException( + "Error occurred while persisting registry resource : " + + e.getMessage(), e); + } + return status; + } + + public static String getResourcePath(String resourceName, String platform) { + String regPath = ""; + switch (platform) { + case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID: + regPath = AndroidPluginConstants.MobilePluginConstants + .MOBILE_CONFIG_REGISTRY_ROOT + "/" + + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID + + "/" + resourceName; + break; + case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS: + regPath = AndroidPluginConstants.MobilePluginConstants.MOBILE_CONFIG_REGISTRY_ROOT + "/" + + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS + + "/" + resourceName; + break; + case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS: + regPath = AndroidPluginConstants.MobilePluginConstants.MOBILE_CONFIG_REGISTRY_ROOT + "/" + + DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS + + "/" + resourceName; + break; + } + return regPath; + } + + public static String getPlatformConfigPath(String platform) { + String regPath = ""; + switch (platform) { + case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID: + regPath = DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID; + break; + case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS: + regPath = DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS; + break; + case DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS: + regPath = DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS; + break; + } + return regPath; + } + + public static boolean createRegistryCollection(String path) + throws AndroidDeviceMgtPluginException { + try { + if (! MobileDeviceManagementUtil.getConfigurationRegistry().resourceExists(path)) { + Resource resource = MobileDeviceManagementUtil.getConfigurationRegistry().newCollection(); + MobileDeviceManagementUtil.getConfigurationRegistry().beginTransaction(); + MobileDeviceManagementUtil.getConfigurationRegistry().put(path, resource); + MobileDeviceManagementUtil.getConfigurationRegistry().commitTransaction(); + } + return true; + } catch (AndroidDeviceMgtPluginException e) { + throw new AndroidDeviceMgtPluginException( + "Error occurred while creating a registry collection : " + + e.getMessage(), e); + } catch (RegistryException e) { + throw new AndroidDeviceMgtPluginException( + "Error occurred while creating a registry collection : " + + e.getMessage(), e); + } + } + + public static List getMissingFeatures(List supportedFeatures, List existingFeatures) { + HashMap featureHashMap = new HashMap(); + for (Feature feature: existingFeatures) { + featureHashMap.put(feature.getCode(),feature); + } + List missingFeatures = new ArrayList(); + for (Feature supportedFeature : supportedFeatures) { + if (featureHashMap.get(supportedFeature.getCode()) != null) { + continue; + } + missingFeatures.add(supportedFeature); + } + return missingFeatures; + } +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/internal/AndroidDeviceManagementDataHolder.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/internal/AndroidDeviceManagementDataHolder.java new file mode 100644 index 000000000..94efdfbf7 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/internal/AndroidDeviceManagementDataHolder.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.internal; + +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.registry.core.service.RegistryService; + +/** + * DataHolder class of Mobile plugins component. + */ +public class AndroidDeviceManagementDataHolder { + + private RegistryService registryService; + private DeviceManagementService androidDeviceManagementService; + + private static AndroidDeviceManagementDataHolder thisInstance = new AndroidDeviceManagementDataHolder(); + + private AndroidDeviceManagementDataHolder() { + } + + public static AndroidDeviceManagementDataHolder getInstance() { + return thisInstance; + } + + public RegistryService getRegistryService() { + return registryService; + } + + public void setRegistryService(RegistryService registryService) { + this.registryService = registryService; + } + + public DeviceManagementService getAndroidDeviceManagementService() { + return androidDeviceManagementService; + } + + public void setAndroidDeviceManagementService( + DeviceManagementService androidDeviceManagementService) { + this.androidDeviceManagementService = androidDeviceManagementService; + } + +} diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/internal/AndroidDeviceManagementServiceComponent.java b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/internal/AndroidDeviceManagementServiceComponent.java new file mode 100644 index 000000000..84fbb3c17 --- /dev/null +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/src/main/java/org/wso2/carbon/device/mgt/mobile/android/internal/AndroidDeviceManagementServiceComponent.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.mobile.android.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.device.mgt.mobile.android.impl.AndroidDeviceManagementService; +import org.wso2.carbon.ndatasource.core.DataSourceService; +import org.wso2.carbon.registry.core.service.RegistryService; + +/** + * @scr.component name="org.wso2.carbon.device.mgt.mobile.android.impl.internal.AndroidDeviceManagementServiceComponent" + * immediate="true" + * @scr.reference name="org.wso2.carbon.ndatasource" + * interface="org.wso2.carbon.ndatasource.core.DataSourceService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDataSourceService" + * unbind="unsetDataSourceService" + * @scr.reference name="registry.service" + * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="0..1" + * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService" + *

    + * Adding reference to API Manager Configuration service is an unavoidable hack to get rid of NPEs thrown while + * initializing APIMgtDAOs attempting to register APIs programmatically. APIMgtDAO needs to be proper cleaned up + * to avoid as an ideal fix + */ +public class AndroidDeviceManagementServiceComponent { + + private static final Log log = LogFactory.getLog(AndroidDeviceManagementServiceComponent.class); + + protected void activate(ComponentContext ctx) { + + if (log.isDebugEnabled()) { + log.debug("Activating Android Mobile Device Management Service Component"); + } + try { + DeviceManagementService androidDeviceManagementService = new AndroidDeviceManagementService(); + AndroidDeviceManagementDataHolder.getInstance().setAndroidDeviceManagementService( + androidDeviceManagementService); + if (log.isDebugEnabled()) { + log.debug("Android Mobile Device Management Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Android Mobile Device Management Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Android Mobile Device Management Service Component"); + } + try { + if (log.isDebugEnabled()) { + log.debug( + "Android Mobile Device Management Service Component has been successfully de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating Android Mobile Device Management bundle", e); + } + } + + protected void setDataSourceService(DataSourceService dataSourceService) { + /* This is to avoid mobile device management component getting initialized before the underlying datasources + are registered */ + if (log.isDebugEnabled()) { + log.debug("Data source service set to android mobile service component"); + } + } + + protected void unsetDataSourceService(DataSourceService dataSourceService) { + //do nothing + } + + protected void setRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("RegistryService acquired"); + } + AndroidDeviceManagementDataHolder.getInstance().setRegistryService(registryService); + } + + protected void unsetRegistryService(RegistryService registryService) { + AndroidDeviceManagementDataHolder.getInstance().setRegistryService(null); + } + +} diff --git a/components/mobile-plugins/android-plugin/pom.xml b/components/mobile-plugins/android-plugin/pom.xml index efd6356b3..41d9b89e9 100644 --- a/components/mobile-plugins/android-plugin/pom.xml +++ b/components/mobile-plugins/android-plugin/pom.xml @@ -17,7 +17,8 @@ ~ under the License. --> - + org.wso2.carbon.devicemgt-plugins @@ -33,9 +34,7 @@ http://wso2.org - org.wso2.carbon.device.mgt.mobile.android.common - org.wso2.carbon.device.mgt.mobile.android.addons - org.wso2.carbon.device.mgt.mobile.android.core + org.wso2.carbon.device.mgt.mobile.android org.wso2.carbon.device.mgt.mobile.android.api org.wso2.carbon.device.mgt.mobile.android.emulator org.wso2.carbon.device.mgt.mobile.android.ui diff --git a/features/extensions-feature/io.entgra.health.check.api.feature/pom.xml b/features/extensions-feature/io.entgra.health.check.api.feature/pom.xml deleted file mode 100644 index 212663251..000000000 --- a/features/extensions-feature/io.entgra.health.check.api.feature/pom.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - org.wso2.carbon.devicemgt-plugins - extensions-feature - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - io.entgra.health.check.api.feature - 5.0.7-SNAPSHOT - pom - Entgra - Health Check API Feature - http://entgra.io - - - - - maven-resources-plugin - - - copy-resources - generate-resources - - copy-resources - - - src/main/resources - - - resources - - build.properties - p2.inf - - - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-jaxrs-war - package - - copy - - - - - org.wso2.carbon.devicemgt-plugins - health-check-api - war - true - - ${project.build.directory}/maven-shared-archive-resources/webapps/ - - api#health-check#v1.0.war - - - - - - - - org.wso2.maven - carbon-p2-plugin - ${carbon.p2.plugin.version} - - - p2-feature-generation - package - - p2-feature-gen - - - io.entgra.health.check.api - ../../../features/etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:true - - - - - - - - - diff --git a/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/api/health-check.xml b/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/api/health-check.xml deleted file mode 100755 index 59c5153ba..000000000 --- a/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/api/health-check.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - OK - - - - - - - - - - - diff --git a/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/build.properties b/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/build.properties deleted file mode 100644 index e6e21811e..000000000 --- a/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. -# -# Entgra (pvt) Ltd. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -custom = true diff --git a/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/p2.inf b/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/p2.inf deleted file mode 100644 index 464f7a84f..000000000 --- a/features/extensions-feature/io.entgra.health.check.api.feature/src/main/resources/p2.inf +++ /dev/null @@ -1,9 +0,0 @@ -instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/synapse-configs/);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/synapse-configs/default/);\ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/synapse-configs/default/api/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.health.check.api_${feature.version}/webapps/api#health-check#v1.0.war,target:${installFolder}/../../deployment/server/webapps/api#health-check#v1.0.war,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/io.entgra.health.check.api_${feature.version}/api/health-check.xml,target:${installFolder}/../../deployment/server/synapse-configs/default/api/health-check.xml,overwrite:true);\ \ No newline at end of file diff --git a/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/pom.xml b/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/pom.xml deleted file mode 100644 index 2e5703410..000000000 --- a/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/pom.xml +++ /dev/null @@ -1,151 +0,0 @@ - - - - - - org.wso2.carbon.devicemgt-plugins - extensions-feature - 5.0.7-SNAPSHOT - ../pom.xml - - 4.0.0 - - org.wso2.carbon.device.mgt.remote.session.feature - pom - WSO2 Carbon - Remote Session Manager - http://wso2.org - This feature contains the core bundles required iot Remote Sessions - - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.extensions.remote.session - - - io.github.openfeign - feign-jaxrs - ${io.github.openfeign.version} - - - io.github.openfeign - feign-gson - ${io.github.openfeign.version} - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy - package - - copy - - - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.extensions.remote.session.endpoint - ${carbon.devicemgt.plugins.version} - war - true - - ${project.build.directory}/maven-shared-archive-resources/webapps/ - - remote#session.war - - - - - - - - maven-resources-plugin - - - copy-resources - generate-resources - - copy-resources - - - src/main/resources - - - resources - - build.properties - p2.inf - - - - - - - - - org.wso2.maven - carbon-p2-plugin - ${carbon.p2.plugin.version} - - - p2-feature-generation - package - - p2-feature-gen - - - org.wso2.carbon.device.mgt.remote.session - ../../../features/etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:true - - - - - org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.extensions.remote.session:${carbon.devicemgt.plugins.version} - - - - org.wso2.carbon.identity.inbound.auth.oauth2:org.wso2.carbon.identity.oauth.stub:${identity.inbound.auth.oauth.version} - - - io.github.openfeign:feign-core:${io.github.openfeign.version} - - - io.github.openfeign:feign-slf4j:${io.github.openfeign.version} - - - io.github.openfeign:feign-gson:${io.github.openfeign.version} - - - - - - - - - - diff --git a/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/src/main/resources/build.properties b/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/src/main/resources/build.properties deleted file mode 100644 index e0fe0c513..000000000 --- a/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/src/main/resources/build.properties +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -# -# WSO2 Inc. licenses this file to you under the Apache License, -# Version 2.0 (the "License"); you may not use this file except -# in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -custom = true diff --git a/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/src/main/resources/p2.inf b/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/src/main/resources/p2.inf deleted file mode 100644 index 9efb7a994..000000000 --- a/features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/src/main/resources/p2.inf +++ /dev/null @@ -1,3 +0,0 @@ -instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.remote.session_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\ \ No newline at end of file diff --git a/features/extensions-feature/org.wso2.extension.siddhi.device.feature/pom.xml b/features/extensions-feature/org.wso2.extension.siddhi.device.feature/pom.xml deleted file mode 100644 index 1b1666843..000000000 --- a/features/extensions-feature/org.wso2.extension.siddhi.device.feature/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - 4.0.0 - - - org.wso2.carbon.devicemgt-plugins - extensions-feature - 5.0.7-SNAPSHOT - ../pom.xml - - - org.wso2.extension.siddhi.device.feature - pom - WSO2 Siddhi Execution Extension - Device Group Feature - http://wso2.org - This feature contains Siddhi extension feature for device groups - - - - org.wso2.carbon.devicemgt-plugins - org.wso2.extension.siddhi.device - - - - - - - org.wso2.maven - carbon-p2-plugin - ${carbon.p2.plugin.version} - - - p2-feature-generation - package - - p2-feature-gen - - - org.wso2.extension.siddhi.device - ../../etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:true - - - - - org.wso2.carbon.devicemgt-plugins:org.wso2.extension.siddhi.device:${carbon.devicemgt.plugins.version} - - - - - - - - - diff --git a/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/build.properties b/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/build.properties deleted file mode 100644 index 9c86577d7..000000000 --- a/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/build.properties +++ /dev/null @@ -1 +0,0 @@ -custom = true diff --git a/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/conf/siddhi-integration.xml b/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/conf/siddhi-integration.xml deleted file mode 100644 index 8b762e3e4..000000000 --- a/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/conf/siddhi-integration.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - https://${iot.gateway.host}:${iot.gateway.https.port}/api-application-registration/register - https://${iot.gateway.host}:${iot.gateway.https.port} - admin - admin - \ No newline at end of file diff --git a/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/p2.inf b/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/p2.inf deleted file mode 100644 index d55300665..000000000 --- a/features/extensions-feature/org.wso2.extension.siddhi.device.feature/src/main/resources/p2.inf +++ /dev/null @@ -1,2 +0,0 @@ -instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.extension.siddhi.device_${feature.version}/conf/siddhi-integration.xml,target:${installFolder}/../../conf/siddhi-integration.xml,overwrite:true);\ diff --git a/features/extensions-feature/org.wso2.extension.siddhi.execution.json.feature/pom.xml b/features/extensions-feature/org.wso2.extension.siddhi.execution.json.feature/pom.xml deleted file mode 100644 index 94b145887..000000000 --- a/features/extensions-feature/org.wso2.extension.siddhi.execution.json.feature/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - 4.0.0 - - - org.wso2.carbon.devicemgt-plugins - extensions-feature - 5.0.7-SNAPSHOT - ../pom.xml - - - org.wso2.extension.siddhi.execution.json.feature - pom - 5.0.7-SNAPSHOT - WSO2 Siddhi Execution Extension - Json Feature - http://wso2.org - This feature contains Siddhi extension feature for changing a json string to individual properties. - - - - org.wso2.carbon.devicemgt-plugins - org.wso2.extension.siddhi.execution.json - - - - - - - org.wso2.maven - carbon-p2-plugin - ${carbon.p2.plugin.version} - - - p2-feature-generation - package - - p2-feature-gen - - - org.wso2.extension.siddhi.execution.json - ../../etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:true - - - - - org.wso2.carbon.devicemgt-plugins:org.wso2.extension.siddhi.execution.json:${carbon.devicemgt.plugins.version} - - - - - - - - - diff --git a/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/pom.xml b/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/pom.xml deleted file mode 100644 index f8e82f290..000000000 --- a/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/pom.xml +++ /dev/null @@ -1,119 +0,0 @@ - - - - - - - - org.wso2.carbon.devicemgt-plugins - extensions-feature - 5.0.7-SNAPSHOT - ../pom.xml - - - 4.0.0 - org.wso2.gpl.siddhi.extension.geo.script.feature - GPL Siddhi Extension - Geo Script Feature - pom - - - - - maven-resources-plugin - - - copy-resources - generate-resources - - copy-resources - - - src/main/resources - - - resources - - build.properties - p2.inf - - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - unpack - package - - unpack - - - - - org.wso2.carbon.devicemgt-plugins - org.wso2.gpl.siddhi.extension.geo.script - ${project.version} - zip - true - - ${project.build.directory}/maven-shared-archive-resources/scripts - - **/* - - - - - - - - org.wso2.maven - carbon-p2-plugin - ${carbon.p2.plugin.version} - - - p2-feature-generation - package - - p2-feature-gen - - - org.wso2.gpl.siddhi.extension.geo.script - ../../../features/etc/feature.properties - - - org.wso2.carbon.p2.category.type:server - org.eclipse.equinox.p2.type.group:true - - - - org.wso2.carbon.core.server:${carbon.kernel.version} - - - - - - - - - diff --git a/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/src/main/resources/build.properties b/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/src/main/resources/build.properties deleted file mode 100644 index 9c86577d7..000000000 --- a/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/src/main/resources/build.properties +++ /dev/null @@ -1 +0,0 @@ -custom = true diff --git a/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/src/main/resources/p2.inf b/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/src/main/resources/p2.inf deleted file mode 100644 index d810a2aa0..000000000 --- a/features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/src/main/resources/p2.inf +++ /dev/null @@ -1,7 +0,0 @@ -instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../scripts);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.gpl.siddhi.extension.geo.script_${feature.version}/scripts/,target:${installFolder}/../../../scripts/,overwrite:true);\ - -instructions.unconfigure = \ -org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../scripts/gpl-siddhi-geo-extention);\ -org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../scripts/siddhi-geo-extention-deployer.xml);\ \ No newline at end of file diff --git a/features/extensions-feature/pom.xml b/features/extensions-feature/pom.xml index 40cb22ecd..55c54724e 100644 --- a/features/extensions-feature/pom.xml +++ b/features/extensions-feature/pom.xml @@ -17,7 +17,8 @@ ~ under the License. --> - + org.wso2.carbon.devicemgt-plugins @@ -34,15 +35,10 @@ http://wso2.org - io.entgra.health.check.api.feature org.wso2.carbon.device.mgt.adapter.feature org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.feature org.wso2.carbon.andes.extensions.device.mgt.api.feature - org.wso2.extension.siddhi.device.feature - org.wso2.extension.siddhi.execution.json.feature org.wso2.carbon.device.mgt.notification.listener.feature - org.wso2.gpl.siddhi.extension.geo.script.feature - org.wso2.carbon.device.mgt.remote.session.feature diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/pom.xml b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/pom.xml index d1b13a76a..4453656d3 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/pom.xml +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/pom.xml @@ -17,7 +17,8 @@ ~ under the License. --> - + org.wso2.carbon.devicemgt-plugins @@ -29,7 +30,6 @@ 4.0.0 org.wso2.carbon.device.mgt.mobile.android.feature pom - 5.0.7-SNAPSHOT WSO2 Carbon - Android Device Management Feature http://wso2.org This feature contains the core bundles required for Android Device Management @@ -39,11 +39,7 @@ org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.core - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.common + org.wso2.carbon.device.mgt.mobile.android com.h2database.wso2 @@ -247,10 +243,7 @@ - org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.mobile.android.core:${carbon.devicemgt.plugins.version} - - - org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.mobile.android.common:${carbon.devicemgt.plugins.version} + org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.mobile.android:${carbon.devicemgt.plugins.version} diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/conf/android-dbconfig.xml b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/conf/android-dbconfig.xml deleted file mode 100644 index 2f6c6c860..000000000 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/conf/android-dbconfig.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - jdbc/MobileAndroidDM_DS - - - diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/conf/mobile-config.xml b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/conf/mobile-config.xml index e22a61b63..be4a08fea 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/conf/mobile-config.xml +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/conf/mobile-config.xml @@ -25,11 +25,6 @@ jdbc/MobileAndroidDM_DS - - - jdbc/MobileWindowsDM_DS - - diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/h2.sql b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/h2.sql index 329290335..9eed9b2d5 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/h2.sql +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/h2.sql @@ -26,36 +26,6 @@ CREATE TABLE IF NOT EXISTS `AD_FEATURE` ( `ID` INT NOT NULL AUTO_INCREMENT, `CODE` VARCHAR(45) NOT NULL, `NAME` VARCHAR(100) NULL, - `TYPE` VARCHAR(20) NULL, - `HIDDEN` BOOLEAN DEFAULT FALSE, `DESCRIPTION` VARCHAR(200) NULL, PRIMARY KEY (`ID`)); --- ----------------------------------------------------- --- Table `AD_ENTERPRISE_USER_DEVICE` --- ----------------------------------------------------- - -CREATE TABLE IF NOT EXISTS `AD_ENTERPRISE_USER_DEVICE` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `ENTERPRISE_ID` VARCHAR(50) NULL, - `EMM_USERNAME` VARCHAR(100) NOT NULL, - `GOOGLE_USER_ID` VARCHAR(50) NULL, - `ANDROID_PLAY_DEVICE_ID` VARCHAR(50) NULL, - `EMM_DEVICE_ID` VARCHAR(50) NULL, - `TENANT_ID` INT(11) NULL DEFAULT '0', - `LAST_UPDATED_TIMESTAMP` TIMESTAMP NOT NULL, - PRIMARY KEY (`ID`)); - --- ----------------------------------------------------- --- Table `AD_ENTERPRISE_MANAGED_CONFIGS` --- ----------------------------------------------------- - -CREATE TABLE IF NOT EXISTS `AD_ENTERPRISE_MANAGED_CONFIGS` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `MCM_ID` VARCHAR(50) NULL, - `PROFILE_NAME` VARCHAR(100) NULL, - `PACKAGE_NAME` VARCHAR(100) NOT NULL, - `TENANT_ID` INT(11) NULL DEFAULT '0', - `LAST_UPDATED_TIMESTAMP` TIMESTAMP NOT NULL, - PRIMARY KEY (`ID`)); - diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/mssql.sql b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/mssql.sql index adbb578a4..2c22d4729 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/mssql.sql +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/mssql.sql @@ -27,30 +27,6 @@ CREATE TABLE AD_FEATURE ( ID INT NOT NULL IDENTITY, CODE VARCHAR(45) NOT NULL, NAME VARCHAR(100) NULL, - TYPE VARCHAR(20) NULL, - HIDDEN BIT DEFAULT 0, DESCRIPTION VARCHAR(200) NULL, PRIMARY KEY (ID) ); - -CREATE TABLE AD_ENTERPRISE_USER_DEVICE ( - [ID] INT NOT NULL IDENTITY, - [ENTERPRISE_ID] VARCHAR(50) NULL, - [EMM_USERNAME] VARCHAR(100) NOT NULL, - [GOOGLE_USER_ID] VARCHAR(50) NULL, - [ANDROID_PLAY_DEVICE_ID] VARCHAR(50) NULL, - [EMM_DEVICE_ID] VARCHAR(50) NULL, - [TENANT_ID] INT NULL DEFAULT '0', - [LAST_UPDATED_TIMESTAMP] DATETIME2(0) NOT NULL, - PRIMARY KEY ([ID]) -); - -CREATE TABLE AD_ENTERPRISE_MANAGED_CONFIGS ( - [ID] INT NOT NULL IDENTITY, - [MCM_ID] VARCHAR(50) NULL, - [PROFILE_NAME] VARCHAR(100) NULL, - [PACKAGE_NAME] VARCHAR(100) NOT NULL, - [TENANT_ID] INT NULL DEFAULT '0', - [LAST_UPDATED_TIMESTAMP] DATETIME2(0) NOT NULL, - PRIMARY KEY ([ID]) -) ; diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/mysql.sql b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/mysql.sql index f66dd121b..b7dcbe73c 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/mysql.sql +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/mysql.sql @@ -26,31 +26,7 @@ CREATE TABLE IF NOT EXISTS `AD_FEATURE` ( `ID` INT NOT NULL AUTO_INCREMENT, `CODE` VARCHAR(45) NOT NULL, `NAME` VARCHAR(100) NULL, - `TYPE` VARCHAR(20) NULL, - `HIDDEN` BIT DEFAULT 0, `DESCRIPTION` VARCHAR(200) NULL, PRIMARY KEY (`ID`) -) ENGINE = InnoDB; - -CREATE TABLE IF NOT EXISTS `AD_ENTERPRISE_USER_DEVICE` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `ENTERPRISE_ID` VARCHAR(50) NULL, - `EMM_USERNAME` VARCHAR(100) NOT NULL, - `GOOGLE_USER_ID` VARCHAR(50) NULL, - `ANDROID_PLAY_DEVICE_ID` VARCHAR(50) NULL, - `EMM_DEVICE_ID` VARCHAR(50) NULL, - `TENANT_ID` INT(11) NULL DEFAULT '0', - `LAST_UPDATED_TIMESTAMP` TIMESTAMP NOT NULL, - PRIMARY KEY (`ID`) -) ENGINE = InnoDB; - -CREATE TABLE IF NOT EXISTS `AD_ENTERPRISE_MANAGED_CONFIGS` ( - `ID` INT NOT NULL AUTO_INCREMENT, - `MCM_ID` VARCHAR(50) NULL, - `PROFILE_NAME` VARCHAR(100) NULL, - `PACKAGE_NAME` VARCHAR(100) NOT NULL, - `TENANT_ID` INT(11) NULL DEFAULT '0', - `LAST_UPDATED_TIMESTAMP` TIMESTAMP NOT NULL, - PRIMARY KEY (`ID`) -) ENGINE = InnoDB; + ) ENGINE = InnoDB; diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/oracle.sql b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/oracle.sql index 246ee5df9..703757e90 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/oracle.sql +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/oracle.sql @@ -27,8 +27,6 @@ CREATE TABLE AD_FEATURE ( ID INT NOT NULL, CODE VARCHAR(45) NOT NULL, NAME VARCHAR(100) NOT NULL, - TYPE VARCHAR(20) NULL, - HIDDEN BIT DEFAULT 0, DESCRIPTION VARCHAR(200) DEFAULT NULL, CONSTRAINT AD_FEATURE PRIMARY KEY (ID) ) @@ -50,49 +48,4 @@ FOR EACH ROW BEGIN SELECT AD_FEATURE_ID_INC_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; END; -/ - - -CREATE TABLE AD_ENTERPRISE_USER_DEVICE ( - ID NUMBER(10) NOT NULL, - ENTERPRISE_ID VARCHAR2(50) NULL, - EMM_USERNAME VARCHAR2(100) NOT NULL, - GOOGLE_USER_ID VARCHAR2(50) NULL, - ANDROID_PLAY_DEVICE_ID VARCHAR2(50) NULL, - EMM_DEVICE_ID VARCHAR2(50) NULL, - TENANT_ID NUMBER(10) DEFAULT '0' NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP(0) NOT NULL, - PRIMARY KEY (ID) -); - --- Generate ID using sequence and trigger -CREATE SEQUENCE AD_ENTERPRISE_USER_DEVICE_seq START WITH 1 INCREMENT BY 1; - -CREATE OR REPLACE TRIGGER AD_ENTERPRISE_USER_DEVICE_seq_tr - BEFORE INSERT ON AD_ENTERPRISE_USER_DEVICE FOR EACH ROW - WHEN (NEW.ID IS NULL) -BEGIN - SELECT AD_ENTERPRISE_USER_DEVICE_seq.NEXTVAL INTO :NEW.ID FROM DUAL; -END; -/ - -CREATE TABLE AD_ENTERPRISE_MANAGED_CONFIGS ( - ID NUMBER(10) NOT NULL, - MCM_ID VARCHAR2(50) NULL, - PROFILE_NAME VARCHAR2(100) NULL, - PACKAGE_NAME VARCHAR2(100) NOT NULL, - TENANT_ID NUMBER(10) DEFAULT '0' NULL, - LAST_UPDATED_TIMESTAMP TIMESTAMP(0) NOT NULL, - PRIMARY KEY (ID) -) ; - --- Generate ID using sequence and trigger -CREATE SEQUENCE AD_ENTERPRISE_MANAGED_CONFIGS_seq START WITH 1 INCREMENT BY 1; - -CREATE OR REPLACE TRIGGER AD_ENTERPRISE_MANAGED_CONFIGS_seq_tr - BEFORE INSERT ON AD_ENTERPRISE_MANAGED_CONFIGS FOR EACH ROW - WHEN (NEW.ID IS NULL) -BEGIN - SELECT AD_ENTERPRISE_MANAGED_CONFIGS_seq.NEXTVAL INTO :NEW.ID FROM DUAL; -END; / \ No newline at end of file diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/postgresql.sql b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/postgresql.sql index a34075d5a..20a014b86 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/postgresql.sql +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/dbscripts/plugins/postgresql.sql @@ -26,33 +26,5 @@ CREATE TABLE IF NOT EXISTS AD_FEATURE ( ID BIGSERIAL NOT NULL PRIMARY KEY, CODE VARCHAR(45) NOT NULL, NAME VARCHAR(100) NULL, - TYPE VARCHAR(20) NULL, - HIDDEN BOOLEAN DEFAULT FALSE, DESCRIPTION VARCHAR(200) NULL ); - -CREATE SEQUENCE AD_ENTERPRISE_USER_DEVICE_seq; - -CREATE TABLE IF NOT EXISTS AD_ENTERPRISE_USER_DEVICE ( - ID INT NOT NULL DEFAULT NEXTVAL ('AD_ENTERPRISE_USER_DEVICE_seq'), - ENTERPRISE_ID VARCHAR(50) NULL, - EMM_USERNAME VARCHAR(100) NOT NULL, - GOOGLE_USER_ID VARCHAR(50) NULL, - ANDROID_PLAY_DEVICE_ID VARCHAR(50) NULL, - EMM_DEVICE_ID VARCHAR(50) NULL, - TENANT_ID INT NULL DEFAULT '0', - LAST_UPDATED_TIMESTAMP TIMESTAMP(0) NOT NULL, - PRIMARY KEY (ID) -); - -CREATE SEQUENCE AD_ENTERPRISE_MANAGED_CONFIGS_seq; - -CREATE TABLE IF NOT EXISTS AD_ENTERPRISE_MANAGED_CONFIGS ( - ID INT NOT NULL DEFAULT NEXTVAL ('AD_ENTERPRISE_MANAGED_CONFIGS_seq'), - MCM_ID VARCHAR(50) NULL, - PROFILE_NAME VARCHAR(100) NULL, - PACKAGE_NAME VARCHAR(100) NOT NULL, - TENANT_ID INT NULL DEFAULT '0', - LAST_UPDATED_TIMESTAMP TIMESTAMP(0) NOT NULL, - PRIMARY KEY (ID) -) ; diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/devicetypes/android.xml b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/devicetypes/android.xml index 314a48bf2..898534284 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/devicetypes/android.xml +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/devicetypes/android.xml @@ -129,12 +129,6 @@ lock-message - - checkbox - hard-lock - - This feature is only available in OEM Mode. - @@ -171,85 +165,6 @@ - - Reboot - Reboot the device - - - - Change LockTask - Change LockTask mode of KIOSK device - - - - Upgrade Firmware - Upgrade Firmware - - Mute Enable mute in the device @@ -633,39 +548,6 @@ Unlock the device Unlock the device - - Send app restriction - Send remote configurations to an app - - true diff --git a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/p2.inf b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/p2.inf index 5edb8b23b..e188ddf4e 100644 --- a/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/p2.inf +++ b/features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/src/main/resources/p2.inf @@ -12,7 +12,6 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.android_${feature.version}/apis/admin--Android-Mutual-SSL-Configuration-Management.xml,target:${installFolder}/../../deployment/server/synapse-configs/default/api/admin--Android-Mutual-SSL-Configuration-Management.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.android_${feature.version}/apis/admin--Android-Mutual-SSL-Device-Management.xml,target:${installFolder}/../../deployment/server/synapse-configs/default/api/admin--Android-Mutual-SSL-Device-Management.xml,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.android_${feature.version}/apis/admin--Android-Mutual-SSL-Event-Receiver.xml,target:${installFolder}/../../deployment/server/synapse-configs/default/api/admin--Android-Mutual-SSL-Event-Receiver.xml,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.mobile.android_${feature.version}/conf/android-dbconfig.xml,target:${installFolder}/../../conf/android-dbconfig.xml,overwrite:true);\ instructions.unconfigure = \ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/mdm-android-agent.war);\ diff --git a/pom.xml b/pom.xml index 610f45466..64b5ae116 100644 --- a/pom.xml +++ b/pom.xml @@ -512,17 +512,7 @@ org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.common - ${carbon.devicemgt.plugins.version} - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.addons - ${carbon.devicemgt.plugins.version} - - - org.wso2.carbon.devicemgt-plugins - org.wso2.carbon.device.mgt.mobile.android.core + org.wso2.carbon.device.mgt.mobile.android ${carbon.devicemgt.plugins.version}