From 515e82671165164e8fa2e8f62512afd2a31a6353 Mon Sep 17 00:00:00 2001 From: Rushdi Date: Sun, 15 May 2022 03:00:43 +0530 Subject: [PATCH] Update with callable thread and add set/remove user permission on enroll/disenroll device --- .../mgt/jaxrs/service/api/TraccarService.java | 141 ++++ .../service/impl/TraccarServiceImpl.java | 59 ++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 + .../mgt/common/TrackerPermissionInfo.java | 54 ++ .../device/mgt/common/TrackerUserInfo.java | 46 ++ .../device/mgt/core/dao/TrackerDAO.java | 19 + .../core/dao/impl/tracker/TrackerDAOImpl.java | 70 ++ .../impl/DeviceInformationManagerImpl.java | 13 +- .../DeviceManagementProviderServiceImpl.java | 23 +- .../api/service/DeviceAPIClientService.java | 23 +- .../traccar/api/service/TraccarClient.java | 32 +- .../api/service/addons/TraccarClientImpl.java | 753 +++++++++-------- .../service/addons/TraccarClientImplCopy.java | 777 ++++++++++++++++++ .../impl/DeviceAPIClientServiceImpl.java | 94 +-- .../common/TraccarHandlerConstants.java | 9 +- .../core/traccar/common/util/TraccarUtil.java | 47 ++ .../src/test/resources/sql/h2.sql | 30 +- .../src/main/resources/dbscripts/cdm/h2.sql | 7 + 18 files changed, 1733 insertions(+), 466 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/TraccarService.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/TraccarServiceImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/TraccarService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/TraccarService.java new file mode 100644 index 0000000000..33af90ce10 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/TraccarService.java @@ -0,0 +1,141 @@ +/* + * 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.jaxrs.service.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.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList; +import org.wso2.carbon.device.mgt.jaxrs.common.ActivityIdList; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; + +import javax.validation.constraints.Size; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +/** + * traccar related REST-API. This can be used to manipulated traccar related details. + */ +@SwaggerDefinition( + info = @Info( + version = "1.0.0", + title = "", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = "name", value = "TraccarService"), + @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/traccar"), + }) + } + ), + tags = { + @Tag(name = "traccar_service", description = "") + } +) +@Scopes( + scopes = { + @Scope( + name = "Return Traccar User token ", + description = "Enroll a Traccar User if not exist and return the token", + key = "perm:traccar:user", + roles = {"Internal/devicemgt-user"}, + permissions = {"/device-mgt/traccar/manage"} + ) + } +) + +@Path("/traccar") +@Produces(MediaType.APPLICATION_JSON) +@Api(value = "Traccar Service", description = "Traccar Service") +public interface TraccarService { + + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/generate-token") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Return Traccar User Token", + tags = "Traccar Service", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:traccar:user") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully retrieved the operations.", + response = OperationList.class, + 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 has been modified the last " + + "time.\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.\n"), + @ApiResponse( + code = 400, + message = "The incoming request has more than one selection criteria defined via the query parameters.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "The search criteria did not match any device registered with the server.", + response = ErrorResponse.class), + @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 device list.", + response = ErrorResponse.class) + }) + Response getUser( + @ApiParam( + name = "userName", + value = "The user name.", + required = true) + @QueryParam("userName") String userName); +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/TraccarServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/TraccarServiceImpl.java new file mode 100644 index 0000000000..718d2a47fc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/TraccarServiceImpl.java @@ -0,0 +1,59 @@ +/* + * 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.jaxrs.service.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; +import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; +import org.wso2.carbon.device.mgt.jaxrs.service.api.TraccarService; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Path("/traccar") +@Produces(MediaType.APPLICATION_JSON) +public class TraccarServiceImpl implements TraccarService { + private static final Log log = LogFactory.getLog(TraccarServiceImpl.class); + + @GET + @Path("/generate-token") + @Override + public Response getUser(@QueryParam("userName") String userName) { + if (HttpReportingUtil.isTrackerEnabled()) { + JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(userName)); + + log.info("================="); + log.info(obj.toString()); + log.info("=================="); + if(obj.has("error")){ + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); + }else{ + return Response.status(Response.Status.OK).entity(obj.getString("token")).build(); + } + }else{ + return Response.status(Response.Status.BAD_REQUEST).entity("Traccar is not enabled").build(); + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index efce569c42..e80349a4b7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -49,6 +49,7 @@ + @@ -99,6 +100,7 @@ + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java new file mode 100644 index 0000000000..cb91e44bcf --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerPermissionInfo.java @@ -0,0 +1,54 @@ +/* + * 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.common; + +import java.io.Serializable; + +public class TrackerPermissionInfo implements Serializable { + + private static final long serialVersionUID = 1998101712L; + + private int traccarUserId; + private int traccarDeviceId; + + public TrackerPermissionInfo() { + } + + public TrackerPermissionInfo(int traccarUserId, int traccarDeviceId) { + this.traccarUserId = traccarUserId; + this.traccarDeviceId = traccarDeviceId; + } + + + public int getTraccarUserId() { + return traccarUserId; + } + + public void setTraccarUserId(int traccarUserId) { + this.traccarUserId = traccarUserId; + } + + public int getTraccarDeviceId() { + return traccarDeviceId; + } + + public void setTraccarDeviceId(int traccarDeviceId) { + this.traccarDeviceId = traccarDeviceId; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java new file mode 100644 index 0000000000..96d5c5137e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerUserInfo.java @@ -0,0 +1,46 @@ +/* + * 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.common; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + +@ApiModel(value = "User", description = "This class carries all information related to a managed Traccar User.") +public class TrackerUserInfo implements Serializable { + + private static final long serialVersionUID = 1998101712L; + + @ApiModelProperty(name = "userName", value = "The user's name that can be set on the device by the device user.", + required = true) + private String userName; + + public TrackerUserInfo() { + } + + + public String getUserName() { + return userName; + } + + public void setUserName(String UserName) { + this.userName = UserName; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java index 44e42120a7..6deffa8846 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.dao; import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; +import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; public interface TrackerDAO { @@ -90,6 +91,24 @@ public interface TrackerDAO { */ int removeTrackerGroup(int id) throws TrackerManagementDAOException; + /** + * give permission to a user to view traccar device. + * @param traccarUserId mapping table. + * @param deviceId mapping table. + * @throws TrackerManagementDAOException + */ + Boolean addTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; + + /** + * Remove a permission on viewing a device. + * @param traccarUserId mapping table. + * @param deviceId mapping table. + * @throws TrackerManagementDAOException + */ + Boolean removeTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; + + TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException; + /** * get trackerGroup info. * @param groupId of the device. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java index 18a4d13f9f..aad9ba8b08 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.dao.impl.tracker; import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; +import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; @@ -214,6 +215,68 @@ public class TrackerDAOImpl implements TrackerDAO { } } + @Override + public Boolean addTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DM_EXT_PERMISSION_MAPPING(TRACCAR_USER_ID, TRACCAR_DEVICE_ID) VALUES(?, ?)"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, traccarUserId); + stmt.setInt(2, deviceId); + stmt.execute(); + + return true; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while adding traccar user device mapping", e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public Boolean removeTrackerUssrDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_USER_ID=? AND TRACCAR_DEVICE_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, traccarUserId); + stmt.setInt(2, deviceId); + stmt.execute(); + + return true; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while removing traccar user device permission mapping", e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + TrackerPermissionInfo trackerPermissionInfo = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " + + "TRACCAR_DEVICE_ID = ? ORDER BY TRACCAR_DEVICE_ID DESC LIMIT 1"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + rs = stmt.executeQuery(); + if (rs.next()) { + trackerPermissionInfo = this.loadPermission(rs); + } + return trackerPermissionInfo; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + private TrackerGroupInfo loadTrackerGroup(ResultSet rs) throws SQLException { TrackerGroupInfo trackerGroupInfo = new TrackerGroupInfo(); trackerGroupInfo.setId(rs.getInt("ID")); @@ -233,4 +296,11 @@ public class TrackerDAOImpl implements TrackerDAO { trackerDeviceInfo.setStatus(rs.getInt("STATUS")); return trackerDeviceInfo; } + + private TrackerPermissionInfo loadPermission(ResultSet rs) throws SQLException { + TrackerPermissionInfo trackerPermissionInfo = new TrackerPermissionInfo(); + trackerPermissionInfo.setTraccarUserId(rs.getInt("TRACCAR_USER_ID")); + trackerPermissionInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID")); + return trackerPermissionInfo; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java index 53a833785b..438f118b2d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java @@ -53,6 +53,7 @@ import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.ExecutionException; public class DeviceInformationManagerImpl implements DeviceInformationManager { @@ -388,8 +389,16 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { //Tracker update GPS Location if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + } catch (ExecutionException e) { + log.error("ExecutionException : " + e); + //throw new RuntimeException(e); + } catch (InterruptedException e) { + log.error("InterruptedException : " + e); + //throw new RuntimeException(e); + } } //Tracker update GPS Location diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 7a62186377..4488f4da3a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -160,6 +160,17 @@ import java.text.Format; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; @@ -412,7 +423,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //enroll Traccar device if (HttpReportingUtil.isTrackerEnabled()) { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId); + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId); + } catch (ExecutionException e) { + log.error("ExecutionException : " + e); + //throw new RuntimeException(e); + } catch (InterruptedException e) { + log.error("InterruptedException : " + e); + //throw new RuntimeException(e); + } } //enroll Traccar device @@ -581,7 +600,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //procees to dis-enroll a device from traccar starts if (HttpReportingUtil.isTrackerEnabled()) { DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .disEndrollDevice(device.getId(), tenantId); + .disEnrollDevice(device.getId(), tenantId); } //procees to dis-enroll a device from traccar ends diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java index 99af81e5a9..28511f2868 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -21,9 +21,12 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; +import java.util.concurrent.ExecutionException; + public interface DeviceAPIClientService { /** @@ -33,7 +36,7 @@ public interface DeviceAPIClientService { * @param deviceLocation to be added to update location of the device * @throws TraccarConfigurationException errors thrown while inserting location of a device traccar configuration */ - void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId); + void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId) throws ExecutionException, InterruptedException; /** * Create device Traccar configuration records @@ -41,15 +44,7 @@ public interface DeviceAPIClientService { * @param device to be added * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration */ - void addDevice(Device device, int tenantId); - - /** - * Create device Traccar configuration records - * - * @param device to modify - * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration - */ - void updateDevice(Device device, int tenantId); + void addDevice(Device device, int tenantId) throws ExecutionException, InterruptedException; /** * Delete a device Traccar configuration records @@ -57,7 +52,7 @@ public interface DeviceAPIClientService { * @param deviceId to be delete a device * @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration */ - void disEndrollDevice(int deviceId, int tenantId); + void disEnrollDevice(int deviceId, int tenantId); /** * Delete a device Traccar configuration records @@ -65,7 +60,7 @@ public interface DeviceAPIClientService { * @param group to be add a group * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration */ - void addGroup(DeviceGroup group, int groupID, int tenantId); + void addGroup(DeviceGroup group, int groupID, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; /** * Delete a device Traccar configuration records @@ -73,7 +68,7 @@ public interface DeviceAPIClientService { * @param group to be update the group * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration */ - void updateGroup(DeviceGroup group, int groupID, int tenantId); + void updateGroup(DeviceGroup group, int groupID, int tenantId) throws ExecutionException, InterruptedException, TraccarConfigurationException, TrackerAlreadyExistException; /** * Delete a device Traccar configuration records @@ -82,5 +77,5 @@ public interface DeviceAPIClientService { * @param tenantId to delete a group * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration */ - void deleteGroup(int groupId, int tenantId); + void deleteGroup(int groupId, int tenantId) throws ExecutionException, InterruptedException, TraccarConfigurationException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java index 1be320687b..c44162a30a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java @@ -27,33 +27,39 @@ import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; +import java.util.concurrent.ExecutionException; + public interface TraccarClient { - void addDevice(TraccarDevice deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException; + String fetchAllDevices() throws TraccarConfigurationException, ExecutionException, InterruptedException; - void updateDevice(TraccarDevice deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException; + void addDevice(TraccarDevice deviceInfo, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException; + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; - void disEndrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException; + void disEnrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException; void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws - TraccarConfigurationException, TrackerAlreadyExistException; + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) - throws TraccarConfigurationException, TrackerAlreadyExistException; + throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + + void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException; + + void setPermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException; - void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException; + void removePermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException; - void fetchAllUsers(String createUser, TraccarUser traccarUser, int deviceId) throws TraccarConfigurationException; + String fetchAllUsers() throws TraccarConfigurationException, ExecutionException, InterruptedException; - void createUser(TraccarUser traccarUser, String method, int deviceId) throws TraccarConfigurationException; + String fetchUserInfo(String userName) throws TraccarConfigurationException, ExecutionException, InterruptedException; - void updateUser(JSONObject traccarUser) throws TraccarConfigurationException; + String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException; - void setPermission(int userId, int deviceId) throws TraccarConfigurationException; + String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException; + String returnUser(String userName) throws TraccarConfigurationException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java index 078dbef2dc..e24e855ae6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImpl.java @@ -29,17 +29,18 @@ import okhttp3.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; -import org.json.JSONException; import org.json.JSONObject; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; +import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException; import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOFactory; import org.wso2.carbon.device.mgt.core.traccar.api.service.TraccarClient; +import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarGroups; @@ -47,16 +48,20 @@ import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarGateway; +import org.wso2.carbon.device.mgt.core.traccar.common.util.TraccarUtil; import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationManager; -import java.io.IOException; import java.sql.SQLException; -import java.util.ArrayList; +import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.Date; -import java.util.List; +import java.util.Objects; import java.util.Random; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class TraccarClientImpl implements TraccarClient { @@ -79,246 +84,240 @@ public class TraccarClientImpl implements TraccarClient { .connectTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .readTimeout(45, TimeUnit.SECONDS) - .connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS)) + .connectionPool(new ConnectionPool(100,50,TimeUnit.SECONDS)) .build(); this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO(); } - private class TrackerExecutor implements Runnable { - final int deviceId; - final int groupId; - final int tenantId; + private class OkHttpClientThreadPool implements Callable { + final String publisherUrlWithContext; final JSONObject payload; - final String context; - final String publisherUrl; private final String method; - private final String type; - private TrackerExecutor(int id, int tenantId, String publisherUrl, String context, JSONObject payload, - String method, String type) { - this.deviceId = id; - this.groupId = id; - this.tenantId = tenantId; + private OkHttpClientThreadPool(String publisherUrlWithContext, JSONObject payload, String method) { + this.publisherUrlWithContext = publisherUrlWithContext; this.payload = payload; - this.context = context; - this.publisherUrl = publisherUrl; this.method = method; - this.type = type; } - public void run() { + @Override + public String call() throws Exception { RequestBody requestBody; Request.Builder builder = new Request.Builder(); Request request; Response response; - if(method==TraccarHandlerConstants.Methods.POST){ + if(Objects.equals(method, TraccarHandlerConstants.Methods.POST)){ requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.post(requestBody); - }else if(method==TraccarHandlerConstants.Methods.PUT){ + }else if(Objects.equals(method, TraccarHandlerConstants.Methods.PUT)){ requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.put(requestBody); - }else if(method==TraccarHandlerConstants.Methods.DELETE){ + }else if(Objects.equals(method, TraccarHandlerConstants.Methods.DELETE)){ builder = builder.delete(); } - request = builder.url(publisherUrl + context).addHeader(authorization, authorizationKey).build(); + request = builder.url(endpoint+publisherUrlWithContext).addHeader(authorization, authorizationKey).build(); + response = client.newCall(request).execute(); + return response.body().string(); + } + } + + public String fetchAllUsers() throws ExecutionException, InterruptedException { + String method = TraccarHandlerConstants.Methods.GET; + String url = defaultPort+"/api/users"; + + Future result = executor.submit(new OkHttpClientThreadPool(url, null, method)); + String res = result.get(); + //executor.shutdown(); + return res; + } - try { - response = client.newCall(request).execute(); - if(method==TraccarHandlerConstants.Methods.POST){ - String result = response.body().string(); - log.info(result); - if(type==TraccarHandlerConstants.Types.PERMISSION){ - String msg =""; - if(result == ""){ - msg ="Successfully the device is assigned to the user"; - }else{ - msg = "Error occurred while fetching users ."; - } - log.info(msg); - }else if(result.charAt(0)=='{'){ - JSONObject obj = new JSONObject(result); - if (obj.has("id")){ - int traccarId = obj.getInt("id"); - try { - TrackerManagementDAOFactory.beginTransaction(); - if(type==TraccarHandlerConstants.Types.DEVICE){ - trackerDAO.addTrackerDevice(traccarId, deviceId, tenantId); - TrackerDeviceInfo res = trackerDAO.getTrackerDevice(deviceId, tenantId); - if(res.getStatus()==0){ - trackerDAO.updateTrackerDeviceIdANDStatus(res.getTraccarDeviceId(), deviceId, tenantId, 1); - - TraccarUser traccarUser = new TraccarUser(); - traccarUser.setName(username); - traccarUser.setLogin(username); - traccarUser.setEmail(username); - traccarUser.setPassword(generateRandomString(10)); - traccarUser.setToken(generateRandomString(32)); - traccarUser.setDeviceLimit(-1); - - log.info("============================="); - log.info(new Gson().toJson(traccarUser)); - log.info("============================="); - //device is available - //device is not available - //user is available - //user is not available - fetchAllUsers(TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE, traccarUser, traccarId); - } - }else if(type==TraccarHandlerConstants.Types.GROUP){ - trackerDAO.addTrackerGroup(traccarId, groupId, tenantId); - TrackerGroupInfo res = trackerDAO.getTrackerGroup(groupId, tenantId); - if(res.getStatus()==0){ - trackerDAO.updateTrackerGroupIdANDStatus(res.getTraccarGroupId(), groupId, tenantId, 1); - } - }else if(type==TraccarHandlerConstants.Types.USER_CREATE){ - log.info("============="); - log.info("User inserted"); - log.info("============="); - }else if(type==TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE){ - int userId = traccarId; - log.info("============="); - log.info("User inserted and setting to create session"); - log.info("============="); - setPermission(userId, deviceId); - } - TrackerManagementDAOFactory.commitTransaction(); - } catch (JSONException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred on JSON object ."; - log.error(msg, e); - } catch (TransactionManagementException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - String msg = "Error occurred establishing the DB connection ."; - log.error(msg, e); - } catch (TrackerManagementDAOException e) { - TrackerManagementDAOFactory.rollbackTransaction(); - String msg = null; - if(type==TraccarHandlerConstants.Types.DEVICE){ - msg = "Already device with deviceId " + deviceId + " exists" ; - }else if(type==TraccarHandlerConstants.Types.GROUP){ - msg = "Already the group with groupId - " + groupId + " exists!"; - }else if(type==TraccarHandlerConstants.Types.USER){ - msg = "Error occurred while fetching users."; - }else if(type==TraccarHandlerConstants.Types.PERMISSION){ - msg = "Error occurred while assigning the device to the user." + traccarId + deviceId; - } - log.error(msg, e); - } finally { - TrackerManagementDAOFactory.closeConnection(); - } - } - response.close(); - } - if (log.isDebugEnabled()) { - log.debug("Successfully the request is proceed and communicated with Traccar"); - } - }else if(method==TraccarHandlerConstants.Methods.GET){ - if(type!=TraccarHandlerConstants.Types.DEVICE){ - response = client.newCall(request).execute(); - String result = response.body().string(); - - JSONArray fetchAllUsers = new JSONArray(result); - int userAvailability = 0; - int userId = 0; - for(int i=0; i res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + //executor.shutdown(); + + return result; + } + + public String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException { + String method = TraccarHandlerConstants.Methods.PUT; + String url = defaultPort+"/api/users/"+userId; + JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser); - } catch (IOException | TraccarConfigurationException e) { - log.error("Couldnt connect to traccar.", e); + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + //executor.shutdown(); + return result; + } + + public void setPermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException { + JSONObject payload = new JSONObject(); + payload.put("userId", userId); + payload.put("deviceId", deviceId); + + String method = TraccarHandlerConstants.Methods.POST; + String url = defaultPort+"/api/permissions"; + + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + //executor.shutdown(); + + if(result!=null){ + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.addTrackerUssrDevicePermission(userId, deviceId); + TrackerManagementDAOFactory.commitTransaction(); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); } } } - /** - * Add Traccar Device operation. - * @param deviceInfo with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId - * Model, Contact, Category, fenceIds - * @throws TraccarConfigurationException Failed while add Traccar Device the operation - */ - public void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { - TrackerDeviceInfo res = null; - try { - TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerDevice(deviceInfo.getId(), tenantId); - if(res!=null){ - String msg = "The device already exit"; - log.error(msg); - throw new TrackerAlreadyExistException(msg); + public void removePermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException { + JSONObject payload = new JSONObject(); + payload.put("userId", userId); + payload.put("deviceId", deviceId); + + String method = TraccarHandlerConstants.Methods.DELETE; + String url = defaultPort+"/api/permissions"; + + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + //executor.shutdown(); + + if(result!=null){ + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.removeTrackerUssrDevicePermission(userId, deviceId); + TrackerManagementDAOFactory.commitTransaction(); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); } - } catch (TrackerManagementDAOException e) { - String msg = "Error occurred while mapping with deviceId ."; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (SQLException e) { - String msg = "Error occurred establishing the DB connection ."; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } finally { - TrackerManagementDAOFactory.closeConnection(); } + } + + public String fetchAllDevices() throws ExecutionException, InterruptedException { + String method = TraccarHandlerConstants.Methods.GET; + String url = defaultPort+"/api/devices"; - JSONObject payload = payload(deviceInfo); - String context = defaultPort+"/api/devices"; - Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); + Future result = executor.submit(new OkHttpClientThreadPool(url, null, method)); + String res = result.get(); + //executor.shutdown(); + return res; } /** - * update Traccar Device operation. - * @param deviceInfo with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId + * Add Traccar Device operation. + * @param traccarDevice with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId * Model, Contact, Category, fenceIds * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void updateDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { - TrackerDeviceInfo res = null; + public void addDevice(TraccarDevice traccarDevice, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerDeviceInfo trackerDeviceInfo = null; try { TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerDevice(deviceInfo.getId(), tenantId); + trackerDeviceInfo = trackerDAO.getTrackerDevice(traccarDevice.getId(), tenantId); + if(trackerDeviceInfo!=null){ + String msg = "The device already exist"; + log.error(msg); + throw new TrackerAlreadyExistException(msg); + } } catch (TrackerManagementDAOException e) { String msg = "Error occurred while mapping with deviceId ."; log.error(msg, e); @@ -331,105 +330,92 @@ public class TraccarClientImpl implements TraccarClient { TrackerManagementDAOFactory.closeConnection(); } - if ((res==null) || (res.getTraccarDeviceId()==0)){ - try { - TraccarDevice device = deviceInfo; - String lastUpdatedTime = String.valueOf((new Date().getTime())); - device.setLastUpdate(lastUpdatedTime); - addDevice(deviceInfo, tenantId); - } catch (TraccarConfigurationException e) { - String msg = "Error occurred while mapping with groupId"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (TrackerAlreadyExistException e) { - String msg = "The group already exist"; - log.error(msg, e); - throw new TrackerAlreadyExistException(msg, e); - } - }else if (res!=null && (res.getTraccarDeviceId()!=0 && res.getStatus()==0)){ - //update the traccarGroupId and status - try { - TrackerManagementDAOFactory.beginTransaction(); - trackerDAO.updateTrackerDeviceIdANDStatus(res.getTraccarDeviceId(), deviceInfo.getId(), tenantId, 1); - TrackerManagementDAOFactory.commitTransaction(); - } catch (TransactionManagementException e) { - String msg = "Error occurred establishing the DB connection ."; - log.error(msg, e); - } catch (TrackerManagementDAOException e) { - String msg="Could not add the traccar group"; - log.error(msg, e); - } finally{ - TrackerManagementDAOFactory.closeConnection(); + if(trackerDeviceInfo==null){ + //add the device + String method = TraccarHandlerConstants.Methods.POST; + String url = defaultPort+"/api/devices"; + JSONObject payload = TraccarUtil.TraccarDevicePayload(traccarDevice); + + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); + if(result.charAt(0)=='{'){ + JSONObject obj = new JSONObject(result); + if (obj.has("id")){ + int traccarDeviceId = obj.getInt("id"); + int deviceId = traccarDevice.getId(); + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); + trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); + + if(trackerDeviceInfo.getStatus()==0){ + trackerDAO.updateTrackerDeviceIdANDStatus(trackerDeviceInfo.getTraccarDeviceId(), deviceId, tenantId, 1); + } + TrackerManagementDAOFactory.commitTransaction(); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + JSONObject returnUser = new JSONObject(returnUser(username)); + setPermission(returnUser.getInt("id"),deviceId); + }else{ + log.error("Something went wrong_1: " + result); + } + }else{ + log.error("Something went wrong_2: " + result); } - }else{ - JSONObject payload = payload(deviceInfo); - String context = defaultPort+"/api/devices"; - Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); } - } - - private JSONObject payload(TraccarDevice deviceInfo){ - JSONObject payload = new JSONObject(); - payload.put("name", deviceInfo.getDeviceName()); - payload.put("uniqueId", deviceInfo.getUniqueId()); - payload.put("status", deviceInfo.getStatus()); - payload.put("disabled", deviceInfo.getDisabled()); - payload.put("lastUpdate", deviceInfo.getLastUpdate()); - payload.put("positionId", deviceInfo.getPositionId()); - payload.put("groupId", deviceInfo.getGroupId()); - payload.put("phone", deviceInfo.getPhone()); - payload.put("model", deviceInfo.getModel()); - payload.put("contact", deviceInfo.getContact()); - payload.put("category", deviceInfo.getCategory()); - List geoFenceIds = new ArrayList<>(); - payload.put("geofenceIds", geoFenceIds); - payload.put("attributes", new JSONObject()); - return payload; + //executor.shutdown(); } /** * Add Device GPS Location operation. * @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition */ - public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { - TrackerDeviceInfo res = null; + public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerDeviceInfo trackerDeviceInfo = null; try { TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerDevice(device.getId(), tenantId); + trackerDeviceInfo = trackerDAO.getTrackerDevice(device.getId(), tenantId); + log.info(trackerDeviceInfo); } catch (SQLException e) { String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } catch (TrackerManagementDAOException e) { - String msg="Could add new device location"; + String msg="Could not add new device location"; log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } finally{ TrackerManagementDAOFactory.closeConnection(); } - if (res == null){ - try { - addDevice(device, tenantId); - } catch (TraccarConfigurationException e) { - String msg = "Error occurred add the new device"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (TrackerAlreadyExistException e) { - String msg = "The device already exist"; - log.error(msg, e); - throw new TrackerAlreadyExistException(msg, e); - } + //check if the device is already exist before updating the location + if (trackerDeviceInfo == null){ + //add device if not exist + log.info(trackerDeviceInfo); + addDevice(device, tenantId); }else{ - String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ - "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ + //Update Location + String method = TraccarHandlerConstants.Methods.GET; + String url = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+ + "×tamp="+deviceInfo.getTimestamp()+"&lat="+deviceInfo.getLat()+ + "&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ "&speed="+deviceInfo.getSpeed()+"&ignition=true"; - Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, - TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); - log.info("Device GPS location added on traccar"); - } + executor.submit(new OkHttpClientThreadPool(url, null, method)); + //executor.shutdown(); + } } /** @@ -437,36 +423,54 @@ public class TraccarClientImpl implements TraccarClient { * @param deviceId identified via deviceIdentifier * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation */ - public void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { - TrackerDeviceInfo res = null; - JSONObject obj = null; + public void disEnrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { + TrackerDeviceInfo trackerDeviceInfo = null; + TrackerPermissionInfo trackerPermissionInfo = null; + JSONObject trackerDevice = null; + try { TrackerManagementDAOFactory.beginTransaction(); - res = trackerDAO.getTrackerDevice(deviceId, tenantId); - if(res!=null){ - obj = new JSONObject(res); - if(obj!=null){ - trackerDAO.removeTrackerDevice(deviceId, tenantId); - TrackerManagementDAOFactory.commitTransaction(); - } + trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); + trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(deviceId); + if(trackerDeviceInfo!=null){ + trackerDevice = new JSONObject(trackerDeviceInfo); + trackerDAO.removeTrackerDevice(deviceId, tenantId); + TrackerManagementDAOFactory.commitTransaction(); + } } catch (TransactionManagementException e) { TrackerManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred establishing the DB connection"; log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } catch (TrackerManagementDAOException e) { TrackerManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while mapping with deviceId"; log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } - if(obj != null){ - String context = defaultPort+"/api/devices/"+obj.getInt("traccarDeviceId"); - Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarDeviceId"), tenantId, endpoint, context, null, - TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); + //Delete from traccar + if(trackerDevice!=null){ + String method = TraccarHandlerConstants.Methods.DELETE; + String url = defaultPort+"/api/devices/"+trackerDevice.getInt("traccarDeviceId"); + executor.submit(new OkHttpClientThreadPool(url, null, method)); + //executor.shutdown(); + //remove permissions + + log.info(new Gson().toJson(trackerPermissionInfo)); + log.info(trackerPermissionInfo); + if(trackerPermissionInfo!=null){ + try { + removePermission(trackerPermissionInfo.getTraccarUserId(),deviceId); + } catch (ExecutionException e) { + throw new RuntimeException(e); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } } } @@ -475,38 +479,71 @@ public class TraccarClientImpl implements TraccarClient { * @param groupInfo with groupName * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { - TrackerGroupInfo res = null; + public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerGroupInfo trackerGroupInfo = null; try { TrackerManagementDAOFactory.openConnection(); - res = trackerDAO.getTrackerGroup(groupId, tenantId); - if (res!=null){ + trackerGroupInfo = trackerDAO.getTrackerGroup(groupId, tenantId); + if (trackerGroupInfo!=null){ String msg = "The group already exit"; log.error(msg); throw new TrackerAlreadyExistException(msg); } } catch (TrackerManagementDAOException e) { - String msg = "Error occurred while mapping with deviceId ."; + String msg = "Error occurred while mapping with groupId."; log.error(msg, e); throw new TraccarConfigurationException(msg, e); } catch (SQLException e) { - String msg = "Error occurred establishing the DB connection ."; + String msg = "Error occurred establishing the DB connection."; log.error(msg, e); throw new TraccarConfigurationException(msg, e); } finally { TrackerManagementDAOFactory.closeConnection(); } - if (res==null){ - JSONObject payload = new JSONObject(); - payload.put("name", groupInfo.getName()); - payload.put("attributes", new JSONObject()); + JSONObject payload = new JSONObject(); + payload.put("name", groupInfo.getName()); + payload.put("attributes", new JSONObject()); + + String method = TraccarHandlerConstants.Methods.POST; + String url = defaultPort+"/api/groups"; + + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method)); + String result = res.get(); - String context = defaultPort+"/api/groups"; - Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); + if(result.charAt(0)=='{'){ + JSONObject obj = new JSONObject(result); + if (obj.has("id")){ + int traccarGroupId = obj.getInt("id"); + + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.addTrackerGroup(traccarGroupId, groupId, tenantId); + trackerGroupInfo = trackerDAO.getTrackerGroup(groupId, tenantId); + if(trackerGroupInfo.getStatus()==0){ + trackerDAO.updateTrackerGroupIdANDStatus(trackerGroupInfo.getTraccarGroupId(), groupId, tenantId, 1); + } + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + TrackerManagementDAOFactory.rollbackTransaction(); + throw new TraccarConfigurationException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + TrackerManagementDAOFactory.rollbackTransaction(); + throw new TraccarConfigurationException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + }else{ + log.error("Something went wrong_1: " + result); + } + }else{ + log.error("Something went wrong_2: " + result); } + //executor.shutdown(); } /** @@ -514,7 +551,8 @@ public class TraccarClientImpl implements TraccarClient { * @param groupInfo with groupName * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { + public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerGroupInfo res = null; try { TrackerManagementDAOFactory.openConnection(); @@ -531,29 +569,23 @@ public class TraccarClientImpl implements TraccarClient { if ((res==null) || (res.getTraccarGroupId()==0)){ //add a new traccar group - try { - addGroup(groupInfo, groupId, tenantId); - } catch (TraccarConfigurationException e) { - String msg = "Error occurred while mapping with groupId"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } catch (TrackerAlreadyExistException e) { - String msg = "The group already exist"; - log.error(msg, e); - throw new TrackerAlreadyExistException(msg, e); - } + addGroup(groupInfo, groupId, tenantId); }else if (res!=null && (res.getTraccarGroupId()!=0 && res.getStatus()==0)){ //update the traccargroupId and status try { TrackerManagementDAOFactory.beginTransaction(); trackerDAO.updateTrackerGroupIdANDStatus(res.getTraccarGroupId(), groupId, tenantId, 1); TrackerManagementDAOFactory.commitTransaction(); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg="Could not update the traccar group"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); - } catch (TrackerManagementDAOException e) { - String msg="Could not add the traccar group"; - log.error(msg, e); + throw new TraccarConfigurationException(msg, e); } finally{ TrackerManagementDAOFactory.closeConnection(); } @@ -564,10 +596,11 @@ public class TraccarClientImpl implements TraccarClient { payload.put("name", groupInfo.getName()); payload.put("attributes", new JSONObject()); - String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); - Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, - TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); + String method = TraccarHandlerConstants.Methods.PUT; + String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + + executor.submit(new OkHttpClientThreadPool(url, payload, method)); + //executor.shutdown(); } } @@ -576,7 +609,7 @@ public class TraccarClientImpl implements TraccarClient { * @param groupId * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException { + public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException { TrackerGroupInfo res = null; JSONObject obj = null; try { @@ -587,6 +620,12 @@ public class TraccarClientImpl implements TraccarClient { if(obj!=null){ trackerDAO.removeTrackerGroup(obj.getInt("id")); TrackerManagementDAOFactory.commitTransaction(); + + String method = TraccarHandlerConstants.Methods.DELETE; + String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + + executor.submit(new OkHttpClientThreadPool(url, null, method)); + //executor.shutdown(); } } } catch (TransactionManagementException e) { @@ -600,66 +639,6 @@ public class TraccarClientImpl implements TraccarClient { } finally { TrackerManagementDAOFactory.closeConnection(); } - - if(obj!=null){ - String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); - Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarGroupId"), tenantId, endpoint, context, - null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.GROUP); - executor.execute(trackerExecutor); - } - } - - public void fetchAllUsers(String type, TraccarUser traccarUser, int deviceId) throws TraccarConfigurationException { - String context = defaultPort+"/api/users/"; - - JSONObject payload = new JSONObject(); - payload.put("data", traccarUser); - - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, - payload, TraccarHandlerConstants.Methods.GET, type); - executor.execute(trackerExecutor); - } - - private JSONObject TraccarUserPayload(TraccarUser traccarUser){ - JSONObject payload = new JSONObject(); - payload.put("name", traccarUser.getName()); - payload.put("login", traccarUser.getLogin()); - payload.put("email", traccarUser.getEmail()); - payload.put("password", traccarUser.getPassword()); - payload.put("token", traccarUser.getToken()); - payload.put("administrator", traccarUser.getAdministrator()); - payload.put("deviceLimit", traccarUser.getDeviceLimit()); - payload.put("userLimit", traccarUser.getUserLimit()); - payload.put("disabled", traccarUser.getDisabled()); - payload.put("deviceReadonly", traccarUser.getDeviceReadonly()); - return payload; - } - public void createUser(TraccarUser traccarUser, String type, int deviceId) throws TraccarConfigurationException { - JSONObject payload = TraccarUserPayload(traccarUser); - - String context = defaultPort+"/api/users"; - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, type); - executor.execute(trackerExecutor); - } - - public void updateUser(JSONObject traccarUser) throws TraccarConfigurationException { - /*JSONObject payload = traccarUser; - String context = defaultPort+"/api/users"; - Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.USER); - executor.execute(trackerExecutor);*/ - } - - public void setPermission(int userId, int deviceId) throws TraccarConfigurationException { - JSONObject payload = new JSONObject(); - payload.put("userId", userId); - payload.put("deviceId", deviceId); - - String context = defaultPort+"/api/permissions"; - Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, - TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.PERMISSION); - executor.execute(trackerExecutor); } public String generateRandomString(int len) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java new file mode 100644 index 0000000000..b6dfd01b35 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TraccarClientImplCopy.java @@ -0,0 +1,777 @@ +/* + * Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. + * + * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited. + * + * Licensed under the Entgra Commercial License, Version 1.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://entgra.io/licenses/entgra-commercial/1.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.core.traccar.api.service.addons; + +import com.google.gson.Gson; +import okhttp3.ConnectionPool; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; +import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException; +import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; +import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; +import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.traccar.api.service.TraccarClient; +import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarGroups; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser; +import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; +import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarGateway; +import org.wso2.carbon.device.mgt.core.traccar.common.util.TraccarUtil; +import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationManager; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.Date; +import java.util.Objects; +import java.util.Random; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +public class TraccarClientImplCopy /*implements TraccarClient*/ { + private static final Log log = LogFactory.getLog(TraccarClientImplCopy.class); + private static final int THREAD_POOL_SIZE = 50; + private final OkHttpClient client; + private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); + final TraccarGateway traccarGateway = getTraccarGateway(); + final String endpoint = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.ENDPOINT).getValue(); + final String authorization = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.AUTHORIZATION).getValue(); + final String authorizationKey = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.AUTHORIZATION_KEY).getValue(); + final String defaultPort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.DEFAULT_PORT).getValue(); + final String locationUpdatePort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.LOCATION_UPDATE_PORT).getValue(); + + final String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); + private final TrackerDAO trackerDAO; + + public TraccarClientImplCopy() { + client = new OkHttpClient.Builder() + .connectTimeout(30, TimeUnit.SECONDS) + .writeTimeout(30, TimeUnit.SECONDS) + .readTimeout(45, TimeUnit.SECONDS) + .connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS)) + .build(); + this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO(); + } + + private class TrackerExecutor implements Runnable { + final int deviceId; + final int groupId; + final int tenantId; + final JSONObject payload; + final String context; + final String publisherUrl; + private final String method; + private final String type; + + private TrackerExecutor(int id, int tenantId, String publisherUrl, String context, JSONObject payload, + String method, String type) { + this.deviceId = id; + this.groupId = id; + this.tenantId = tenantId; + this.payload = payload; + this.context = context; + this.publisherUrl = publisherUrl; + this.method = method; + this.type = type; + } + + public void run() { + RequestBody requestBody; + Request.Builder builder = new Request.Builder(); + Request request; + Response response; + + if(Objects.equals(method, TraccarHandlerConstants.Methods.POST)){ + requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); + builder = builder.post(requestBody); + }else if(Objects.equals(method, TraccarHandlerConstants.Methods.PUT)){ + requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); + builder = builder.put(requestBody); + }else if(Objects.equals(method, TraccarHandlerConstants.Methods.DELETE)){ + builder = builder.delete(); + } + + request = builder.url(publisherUrl + context).addHeader(authorization, authorizationKey).build(); + String msg; + try { + response = client.newCall(request).execute(); + if(Objects.equals(method, TraccarHandlerConstants.Methods.POST)){ + String result = response.body().string(); + log.info(result); + if(Objects.equals(type, TraccarHandlerConstants.Types.PERMISSION)){ + if(result.equals("")){ + msg ="Successfully the device is assigned to the user"; + }else{ + msg = "Error occurred while fetching users ."; + } + log.info(msg); + }else if(result.charAt(0)=='{'){ + JSONObject obj = new JSONObject(result); + if (obj.has("id")){ + int traccarId = obj.getInt("id"); + try { + TrackerManagementDAOFactory.beginTransaction(); + if(Objects.equals(type, TraccarHandlerConstants.Types.DEVICE)){ + trackerDAO.addTrackerDevice(traccarId, deviceId, tenantId); + TrackerDeviceInfo res = trackerDAO.getTrackerDevice(deviceId, tenantId); + if(res.getStatus()==0){ + trackerDAO.updateTrackerDeviceIdANDStatus(res.getTraccarDeviceId(), deviceId, tenantId, 1); + + TraccarUser traccarUser = new TraccarUser(); + traccarUser.setName(username); + traccarUser.setLogin(username); + traccarUser.setEmail(username); + traccarUser.setPassword(generateRandomString(10)); + traccarUser.setToken(generateRandomString(32)); + traccarUser.setDeviceLimit(-1); + + log.info("=============="+new Gson().toJson(traccarUser)+"=============="); + //device is available + //device is not available + //user is available + //user is not available + fetchAllUsers(TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE, traccarUser, traccarId); + } + }else if(Objects.equals(type, TraccarHandlerConstants.Types.GROUP)){ + trackerDAO.addTrackerGroup(traccarId, groupId, tenantId); + TrackerGroupInfo res = trackerDAO.getTrackerGroup(groupId, tenantId); + if(res.getStatus()==0){ + trackerDAO.updateTrackerGroupIdANDStatus(res.getTraccarGroupId(), groupId, tenantId, 1); + } + }else if(Objects.equals(type, TraccarHandlerConstants.Types.USER_CREATE)){ + log.info("=============User inserted============="); + }else if(Objects.equals(type, TraccarHandlerConstants.Types.USER_CREATE_WITH_INSERT_DEVICE)){ + int userId = traccarId; + log.info("=============User inserted and setting to create session============="); + setPermission(userId, deviceId); + } + TrackerManagementDAOFactory.commitTransaction(); + } catch (JSONException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + msg = "Error occurred on JSON object ."; + log.error(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + msg = null; + switch (type) { + case TraccarHandlerConstants.Types.DEVICE: + msg = "Already device with deviceId " + deviceId + " exists"; + break; + case TraccarHandlerConstants.Types.GROUP: + msg = "Already the group with groupId - " + groupId + " exists!"; + break; + case TraccarHandlerConstants.Types.USER: + msg = "Error occurred while fetching users."; + break; + case TraccarHandlerConstants.Types.PERMISSION: + msg = "Error occurred while assigning the device to the user." + traccarId + deviceId; + break; + } + log.error(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + } + response.close(); + } + if (log.isDebugEnabled()) { + log.debug("Successfully the request is proceed and communicated with Traccar"); + } + }else if(Objects.equals(method, TraccarHandlerConstants.Methods.GET)){ + if(!Objects.equals(type, TraccarHandlerConstants.Types.DEVICE)){ + response = client.newCall(request).execute(); + String result = response.body().string(); + + JSONArray fetchAllUsers = new JSONArray(result); + int userAvailability = 0; + int userId = 0; + for(int i=0; i geoFenceIds = new ArrayList<>(); + payload.put("geofenceIds", geoFenceIds); + payload.put("attributes", new JSONObject()); + return payload; + }*/ + + /** + * Add Device GPS Location operation. + * @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition + */ + public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { + TrackerDeviceInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTrackerDevice(device.getId(), tenantId); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + String msg="Could add new device location"; + log.error(msg, e); + } finally{ + TrackerManagementDAOFactory.closeConnection(); + } + + if (res == null){ + try { + addDevice(device, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred add the new device"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The device already exist"; + log.error(msg, e); + throw new TrackerAlreadyExistException(msg, e); + } + }else{ + String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ + "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ + "&speed="+deviceInfo.getSpeed()+"&ignition=true"; + Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, + TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); + executor.execute(trackerExecutor); + log.info("Device GPS location added on traccar"); + } + + } + + /** + * Dis-enroll a Device operation. + * @param deviceId identified via deviceIdentifier + * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation + */ + public void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { + TrackerDeviceInfo res = null; + JSONObject obj = null; + try { + TrackerManagementDAOFactory.beginTransaction(); + res = trackerDAO.getTrackerDevice(deviceId, tenantId); + if(res!=null){ + obj = new JSONObject(res); + if(obj!=null){ + trackerDAO.removeTrackerDevice(deviceId, tenantId); + TrackerManagementDAOFactory.commitTransaction(); + } + } + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection"; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId"; + log.error(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + if(obj != null){ + String context = defaultPort+"/api/devices/"+obj.getInt("traccarDeviceId"); + Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarDeviceId"), tenantId, endpoint, context, null, + TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE); + executor.execute(trackerExecutor); + } + } + + /** + * Add Traccar Device operation. + * @param groupInfo with groupName + * @throws TraccarConfigurationException Failed while add Traccar Device the operation + */ + public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { + TrackerGroupInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTrackerGroup(groupId, tenantId); + if (res!=null){ + String msg = "The group already exit"; + log.error(msg); + throw new TrackerAlreadyExistException(msg); + } + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + + log.info("response.body().string()"); + try { + OkHttpClient client = new OkHttpClient().newBuilder() + .build(); + Request request = new Request.Builder() + .url("http://localhost/?token=b2zNFM9CvXAaHVxaQcLw22GgCXnaluy9") + .method("GET", null) + .build(); + Response response = client.newCall(request).execute(); + log.info(response.body().string()); + + /*Desktop desktop = java.awt.Desktop.getDesktop(); + URI oURL = new URI("http://localhost:8085"); + desktop.browse(oURL);*/ + } catch (IOException e) { + log.info("IOException e" +e); + } catch (Exception e) { + log.info("Exception e" +e ); + } + log.info("response.body().string()"); + + + if (res==null){ + JSONObject payload = new JSONObject(); + payload.put("name", groupInfo.getName()); + payload.put("attributes", new JSONObject()); + + String context = defaultPort+"/api/groups"; + Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP); + executor.execute(trackerExecutor); + } + } + + /** + * update Traccar Group operation. + * @param groupInfo with groupName + * @throws TraccarConfigurationException Failed while add Traccar Device the operation + */ + public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { + TrackerGroupInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTrackerGroup(groupId, tenantId); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + String msg="Could not find traccar group details"; + log.error(msg, e); + } finally{ + TrackerManagementDAOFactory.closeConnection(); + } + + if ((res==null) || (res.getTraccarGroupId()==0)){ + //add a new traccar group + try { + addGroup(groupInfo, groupId, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The group already exist"; + log.error(msg, e); + throw new TrackerAlreadyExistException(msg, e); + } + }else if (res!=null && (res.getTraccarGroupId()!=0 && res.getStatus()==0)){ + //update the traccargroupId and status + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.updateTrackerGroupIdANDStatus(res.getTraccarGroupId(), groupId, tenantId, 1); + TrackerManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + String msg="Could not add the traccar group"; + log.error(msg, e); + } finally{ + TrackerManagementDAOFactory.closeConnection(); + } + }else{ + JSONObject obj = new JSONObject(res); + JSONObject payload = new JSONObject(); + payload.put("id", obj.getInt("traccarGroupId")); + payload.put("name", groupInfo.getName()); + payload.put("attributes", new JSONObject()); + + String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP); + executor.execute(trackerExecutor); + } + } + + /** + * Add Traccar Device operation. + * @param groupId + * @throws TraccarConfigurationException Failed while add Traccar Device the operation + */ + public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException { + TrackerGroupInfo res = null; + JSONObject obj = null; + try { + TrackerManagementDAOFactory.beginTransaction(); + res = trackerDAO.getTrackerGroup(groupId, tenantId); + if(res!=null){ + obj = new JSONObject(res); + if(obj!=null){ + trackerDAO.removeTrackerGroup(obj.getInt("id")); + TrackerManagementDAOFactory.commitTransaction(); + } + } + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection"; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + if(obj!=null){ + String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarGroupId"), tenantId, endpoint, context, + null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.GROUP); + executor.execute(trackerExecutor); + } + } + + public void fetchAllUsers(String type, TraccarUser traccarUser, int deviceId) throws TraccarConfigurationException { + String context = defaultPort+"/api/users/"; + + JSONObject payload = new JSONObject(); + payload.put("data", traccarUser); + + Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, + payload, TraccarHandlerConstants.Methods.GET, type); + executor.execute(trackerExecutor); + } + + /*private JSONObject TraccarUserPayload(TraccarUser traccarUser){ + JSONObject payload = new JSONObject(); + payload.put("id", traccarUser.getId()); + payload.put("name", traccarUser.getName()); + payload.put("login", traccarUser.getLogin()); + payload.put("email", traccarUser.getEmail()); + payload.put("password", traccarUser.getPassword()); + payload.put("token", traccarUser.getToken()); + payload.put("administrator", traccarUser.getAdministrator()); + payload.put("deviceLimit", traccarUser.getDeviceLimit()); + payload.put("userLimit", traccarUser.getUserLimit()); + payload.put("disabled", traccarUser.getDisabled()); + payload.put("deviceReadonly", traccarUser.getDeviceReadonly()); + payload.put("readonly", traccarUser.getReadonly()); + payload.put("expirationTime", traccarUser.getExpirationTime()); + + return payload; + }*/ + public void createUser(TraccarUser traccarUser, String type, int deviceId) throws TraccarConfigurationException { + JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser); + + String context = defaultPort+"/api/users"; + Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, type); + executor.execute(trackerExecutor); + } + + public void updateUser(JSONObject traccarUser) throws TraccarConfigurationException { + /*JSONObject payload = traccarUser; + String context = defaultPort+"/api/users"; + Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, payload, + TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.USER); + executor.execute(trackerExecutor);*/ + } + + public void setPermission(int userId, int deviceId) throws TraccarConfigurationException { + JSONObject payload = new JSONObject(); + payload.put("userId", userId); + payload.put("deviceId", deviceId); + + String context = defaultPort+"/api/permissions"; + Runnable trackerExecutor = new TrackerExecutor(deviceId, 0, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.PERMISSION); + executor.execute(trackerExecutor); + } + + public String fetchAllUsers() { + OkHttpClient client = new OkHttpClient().newBuilder().build(); + Request request = new Request.Builder() + .url(endpoint+defaultPort+"/api/users") + .method("GET", null) + .addHeader(authorization, authorizationKey) + .build(); + try { + Response response = client.newCall(request).execute(); + return response.body().string(); + } catch (IOException e) { + return e.toString(); + } + } + + public String fetchUserInfo(String userName) throws TraccarConfigurationException { + String allUsers = fetchAllUsers(); //get all users + JSONArray fetchAllUsers = new JSONArray(allUsers); //loop users + for(int i=0; i geoFenceIds = new ArrayList<>(); + payload.put("geofenceIds", geoFenceIds); + payload.put("attributes", new JSONObject()); + return payload; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql index fb88cd3910..005db8fb7d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql @@ -573,4 +573,32 @@ CREATE TABLE IF NOT EXISTS DM_BILLING ( PRIMARY KEY (INVOICE_ID), CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); \ No newline at end of file +); +-- DM_EXT_GROUP_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING ( + ID INT NOT NULL AUTO_INCREMENT, + TRACCAR_GROUP_ID INT DEFAULT 0, + GROUP_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + STATUS INT DEFAULT 0, + PRIMARY KEY (ID) +); +-- END OF DM_EXT_GROUP_MAPPING TABLE-- + +-- END OF DM_EXT_DEVICE_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING ( + ID INT NOT NULL AUTO_INCREMENT, + TRACCAR_DEVICE_ID INT DEFAULT 0, + DEVICE_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + STATUS INT DEFAULT 0, + PRIMARY KEY (ID) +); +-- END OF DM_EXT_DEVICE_MAPPING TABLE-- + +-- END OF DM_EXT_PERMISSION_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING ( + TRACCAR_DEVICE_ID INT DEFAULT 0, + TRACCAR_USER_ID INT DEFAULT 0 +); +-- END OF DM_EXT_PERMISSION_MAPPING TABLE-- diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql index 7e941e6be1..6fa6f7c497 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -770,3 +770,10 @@ CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING ( PRIMARY KEY (ID) ); -- END OF DM_EXT_DEVICE_MAPPING TABLE-- + +-- END OF DM_EXT_PERMISSION_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING ( + TRACCAR_DEVICE_ID INT DEFAULT 0, + TRACCAR_USER_ID INT DEFAULT 0 +); +-- END OF DM_EXT_PERMISSION_MAPPING TABLE--