diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index e2d88ea046a..07ecbf8a236 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -583,6 +583,59 @@ public interface DeviceManagementService { @QueryParam("limit") int limit); + @GET + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Getting Details of Registered Devices Owned by an Authenticated User to generate token for Traccar", + notes = "Provides details of devices enrolled by authenticated users to generate token for Traccar.", + tags = "Device Management", + extensions = { + @Extension(properties = { + @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") + }) + } + ) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.", + response = DeviceList.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 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.\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) + }) + @Path("/traccar-user-token") + Response getTraccarUserToken(); + @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{groupId}/location-history") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 6e6882cfb85..576dfbf0fa3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -42,6 +42,8 @@ import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.json.JSONException; +import org.json.JSONObject; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import io.entgra.application.mgt.common.ApplicationInstallResponse; @@ -60,6 +62,8 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; 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.authorization.DeviceAccessAuthorizationException; @@ -87,6 +91,7 @@ import org.wso2.carbon.device.mgt.common.search.PropertyMap; import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; +import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; 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.dto.DeviceType; @@ -97,7 +102,10 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; +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.util.DeviceManagerUtil; +import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance; @@ -124,12 +132,25 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import javax.validation.Valid; import javax.validation.constraints.Size; -import javax.ws.rs.*; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +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.QueryParam; import javax.ws.rs.core.Response; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; +import java.util.Date; +import java.util.List; +import java.util.ArrayList; +import java.util.Properties; +import java.util.concurrent.ExecutionException; @Path("/devices") public class DeviceManagementServiceImpl implements DeviceManagementService { @@ -463,6 +484,99 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { } } + @GET + @Override + @Path("/traccar-user-token") + public Response getTraccarUserToken() { + + if (HttpReportingUtil.isTrackerEnabled()) { + String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser)); + + if (obj.has("error")) { + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); + } else { + int userId = obj.getInt("id"); + List traccarValidIdList = new ArrayList<>(); + /*Get Device Id List*/ + try { + DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); + DeviceAccessAuthorizationService deviceAccessAuthorizationService = + DeviceMgtAPIUtils.getDeviceAccessAuthorizationService(); + PaginationRequest request = new PaginationRequest(0, 0); + PaginationResult result; + DeviceList devices = new DeviceList(); + List status = new ArrayList<>(); + status.add("ACTIVE"); + status.add("INACTIVE"); + status.add("CREATED"); + status.add("UNREACHABLE"); + request.setStatusList(status); + // this is the user who initiates the request + String authorizedUser = MultitenantUtils.getTenantAwareUsername(currentUser); + // check whether the user is device-mgt admin + if (!deviceAccessAuthorizationService.isDeviceAdminUser()) { + request.setOwner(authorizedUser); + } + + result = dms.getAllDevicesIds(request); + if (result == null || result.getData() == null || result.getData().isEmpty()) { + devices.setList(new ArrayList()); + devices.setCount(0); + } else { + devices.setList((List) result.getData()); + devices.setCount(result.getRecordsTotal()); + } + + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + for (Device device : devices.getList()) { + TrackerDeviceInfo trackerDevice = DeviceAPIClientServiceImpl + .getTrackerDevice(device.getId(), tenantId); + int traccarDeviceId = trackerDevice.getTraccarDeviceId(); + boolean getPermission = DeviceAPIClientServiceImpl.getUserIdofPermissionByDeviceIdNUserId(traccarDeviceId, userId); + traccarValidIdList.add(traccarDeviceId); + if (!getPermission) { + DeviceAPIClientServiceImpl.addTrackerUserDevicePermission(userId, traccarDeviceId); + } + } + //Remove necessary + List getAllUserDevices = + DeviceAPIClientServiceImpl.getUserIdofPermissionByUserIdNIdList(userId, traccarValidIdList); + for (TrackerPermissionInfo getAllUserDevice : getAllUserDevices) { + DeviceAPIClientServiceImpl.removeTrackerUserDevicePermission( + getAllUserDevice.getTraccarUserId(), + getAllUserDevice.getTraccarDeviceId(), + TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE); + } + } catch (DeviceManagementException e) { + String msg = "Error occurred while fetching all enrolled devices. "; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (DeviceAccessAuthorizationException e) { + String msg = "Error occurred while checking device access authorization. "; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (ExecutionException e) { + String msg = "Execution error occurred handling traccar device permissions"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (InterruptedException e) { + String msg = "Interruption error occurred handling traccar device permissions"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + /*Get Device Id List*/ + 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(); + } + } + /** * Validate group Id and group Id greater than 0 and exist. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java index 840d155d440..cc35a55c9d0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Device.java @@ -129,6 +129,10 @@ public class Device implements Serializable { this.deviceStatusInfo = deviceStatusInfo; } + public Device(String deviceId) { + this.deviceIdentifier = deviceId; + } + public int getId() { return id; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java new file mode 100644 index 00000000000..c97c2a4d9dc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerDeviceInfo.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022, 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.common; + +import java.io.Serializable; + +public class TrackerDeviceInfo implements Serializable { + + private static final long serialVersionUID = 11545107900391993L; + + private int id; + private int traccarDeviceId; + private int deviceId; + private int tenantId; + private int status; + + public TrackerDeviceInfo() { + } + + public TrackerDeviceInfo(int traccarDeviceId, int deviceId, int tenantId) { + this.traccarDeviceId = traccarDeviceId; + this.deviceId = deviceId; + this.tenantId = tenantId; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getTraccarDeviceId() { + return traccarDeviceId; + } + + public void setTraccarDeviceId(int traccarDeviceId) { + this.traccarDeviceId = traccarDeviceId; + } + + public int getDeviceId() { + return deviceId; + } + + public void setDeviceId(int deviceId) { + this.deviceId = deviceId; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java new file mode 100644 index 00000000000..03a9cfef0c8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/TrackerGroupInfo.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2022, 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.common; + +import java.io.Serializable; + +public class TrackerGroupInfo implements Serializable { + + private static final long serialVersionUID = 2156646949297006690L; + + private int id; + private int traccarGroupId; + private int groupId; + private int tenantId; + private int status; + + public TrackerGroupInfo() { + } + + public TrackerGroupInfo(int traccarGroupId, int groupId, int tenantId) { + this.traccarGroupId = traccarGroupId; + this.groupId = groupId; + this.tenantId = tenantId; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getTraccarGroupId() { + return traccarGroupId; + } + + public void setTraccarGroupId(int traccarGroupId) { + this.traccarGroupId = traccarGroupId; + } + + public int getGroupId() { + return groupId; + } + + public void setGroupId(int groupId) { + this.groupId = groupId; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } +} 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 00000000000..25341ea19ac --- /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) 2022, 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.common; + +import java.io.Serializable; + +public class TrackerPermissionInfo implements Serializable { + + private static final long serialVersionUID = -8648202903090812913L; + + 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 00000000000..3354dc4e011 --- /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) 2022, 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.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 = -6808358733610879805L; + + @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.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java new file mode 100644 index 00000000000..114ab5cb757 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/TrackerAlreadyExistException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022, 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.common.exceptions; + +/** + * This class represents a custom exception specified for group management + */ +public class TrackerAlreadyExistException extends Exception { + + private static final long serialVersionUID = 5241722939654800965L; + private String errorMessage; + + public TrackerAlreadyExistException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public TrackerAlreadyExistException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public TrackerAlreadyExistException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public TrackerAlreadyExistException() { + super(); + } + + public TrackerAlreadyExistException(Throwable cause) { + super(cause); + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index 2ae7d03cdc0..0f08c7fc0fc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -342,6 +342,11 @@ com.google.guava guava + + com.squareup.okhttp3 + okhttp + compile + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java index 8f23228bef9..fcf414ff087 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java @@ -16,21 +16,21 @@ * under the License. */ /* - * Copyright (c) 2020, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. + * Copyright (c) 2022, 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 + * 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 + * 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.core.dao; @@ -301,6 +301,16 @@ public interface DeviceDAO { */ List getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException; + /** + * This method is used to retrieve the devices of a given tenant as a paginated result. + * + * @param request PaginationRequest object holding the data for pagination + * @param tenantId tenant id. + * @return returns paginated list of devices. + * @throws DeviceManagementDAOException + */ + List getDevicesIds(PaginationRequest request, int tenantId) throws DeviceManagementDAOException; + /** * This method is used to retrieve the devices of a given tenant as a paginated result, along the lines of * activeServerCount and serverIndex diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java index 6b594664f4f..230a958d198 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -27,12 +27,11 @@ import org.wso2.carbon.device.mgt.common.exceptions.UnsupportedDatabaseEngineExc import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.device.mgt.core.dao.impl.*; -import org.wso2.carbon.device.mgt.core.dao.impl.event.GenericEventConfigDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.GenericDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.OracleDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.PostgreSQLDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.SQLServerDeviceDAOImpl; -import org.wso2.carbon.device.mgt.core.dao.impl.event.H2EventConfigDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.impl.tracker.TrackerDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.impl.DeviceDetailsDAOImpl; @@ -130,6 +129,23 @@ public class DeviceManagementDAOFactory { return new BillingDAOImpl(); } + + public static TrackerDAO getTrackerDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new TrackerDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + public static DeviceStatusDAO getDeviceStatusDAO() { return new DeviceStatusDAOImpl(); } 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 new file mode 100644 index 00000000000..c7ce47b0c34 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerDAO.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2022, 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.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; + +import java.util.List; + +public interface TrackerDAO { + + /** + * Add new Device. + * @param traccarDeviceId to be added. + * @param deviceId of the device. + * @param tenantId of the group. + * @return boolean value. + * @throws TrackerManagementDAOException + */ + void addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException; + + /** + * get trackerDevice info. + * @param deviceId of the device. + * @param tenantId of the group. + * @return Tracker Device Info. + * @throws TrackerManagementDAOException + */ + TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException; + + /** + * update trackerDevice status and traccarDeviceId. + * @param traccarDeviceId of the Device. + * @param deviceId of the device. + * @param tenantId of the group. + * @param status of the device. + * @throws TrackerManagementDAOException + */ + void updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException; + + /** + * Remove a Device. + * @param deviceId of the device. + * @param tenantId of the group. + * @return sql execution result. + * @throws TrackerManagementDAOException + */ + void removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException; + + /** + * Add new Group. + * @param traccarGroupId to be added. + * @param groupId of the group. + * @param tenantId of the group. + * @throws TrackerManagementDAOException + */ + void addTrackerGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException; + + /** + * Update status and traccarGroupId of a Group. + * @param traccarGroupId to be added. + * @param groupId of the group. + * @param tenantId of the group. + * @param status of the group. + * @return boolean value. + * @throws TrackerManagementDAOException + */ + Boolean updateTrackerGroupIdANDStatus(int traccarGroupId, int groupId, int tenantId, int status) throws TrackerManagementDAOException; + + /** + * Remove a Group. + * @param id of groups. + * @return boolean value. + * @throws TrackerManagementDAOException + */ + int removeTrackerGroup(int id) throws TrackerManagementDAOException; + + /** + * get trackerGroup info. + * @param groupId of the device. + * @param tenantId of the group. + * @return Tracker Device Info. + * @throws TrackerManagementDAOException + */ + TrackerGroupInfo getTrackerGroup(int groupId, int tenantId) throws TrackerManagementDAOException; + + /** + * give permission to a user to view traccar device. + * @param traccarUserId mapping table. + * @param deviceId mapping table. + * @return boolean value. + * @throws TrackerManagementDAOException + */ + Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; + + /** + * Remove a permission on viewing a device. + * @param deviceId of permissions. + * @return boolean value. + * @throws TrackerManagementDAOException + */ + Boolean removeTrackerUserDevicePermission(int deviceId, int userId, int removeType) throws TrackerManagementDAOException; + + /** + * get list of userDevicePermissions by. + * @param deviceId of permissions. + * @return Tracker Permission Info. + * @throws TrackerManagementDAOException + */ + List getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException; + /** + * get list of userDevicePermissions by. + * @param userId of permissions. + * @param NotInDeviceIdList list of permissions. + * @return Tracker Permission Info. + * @throws TrackerManagementDAOException + */ + List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws TrackerManagementDAOException; + + /** + * get list of userDevicePermissions by. + * @param deviceId of permissions. + * @param userId of permissions. + * @return Tracker Permission Info. + * @throws TrackerManagementDAOException + */ + Boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException; + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOException.java new file mode 100644 index 00000000000..bb0f3cc2a27 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOException.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022, 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.core.dao; + +/** + * Custom exception class for data access related exceptions. + */ +public class TrackerManagementDAOException extends Exception { + + private String message; + private static final long serialVersionUID = 2021891706072918864L; + + /** + * Constructs a new exception with the specified detail message and nested exception. + * + * @param message error message + * @param nestedException exception + */ + public TrackerManagementDAOException(String message, Exception nestedException) { + super(message, nestedException); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified detail message and cause. + * + * @param message the detail message. + * @param cause the cause of this exception. + */ + public TrackerManagementDAOException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified detail message + * + * @param message the detail message. + */ + public TrackerManagementDAOException(String message) { + super(message); + setErrorMessage(message); + } + + /** + * Constructs a new exception with the specified and cause. + * + * @param cause the cause of this exception. + */ + public TrackerManagementDAOException(Throwable cause) { + super(cause); + } + + public String getMessage() { + return message; + } + + public void setErrorMessage(String errorMessage) { + this.message = errorMessage; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOFactory.java new file mode 100644 index 00000000000..1839425b25a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/TrackerManagementDAOFactory.java @@ -0,0 +1,241 @@ +/* + * Copyright (c) 2022, 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.core.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.common.exceptions.IllegalTransactionStateException; +import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.exceptions.UnsupportedDatabaseEngineException; +import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; +import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; +import org.wso2.carbon.device.mgt.core.dao.impl.tracker.TrackerDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Hashtable; +import java.util.List; + +/** + * This class intends to act as the primary entity that hides all DAO instantiation related complexities and logic so + * that the business objection handling layer doesn't need to be aware of the same providing seamless plug-ability of + * different data sources, connection acquisition mechanisms as well as different forms of DAO implementations to the + * high-level implementations that require device management related metadata persistence. + *

+ * In addition, this also provides means to handle transactions across multiple device management related DAO objects. + * Any high-level business logic that requires transaction handling to be done via utility methods provided in + * TrackerManagementDAOFactory should adhere the following guidelines to avoid any unexpected behaviour that can cause + * as a result of improper use of the aforementioned utility method. + *

+ * Any transaction that commits data into the underlying data persistence mechanism MUST follow the sequence of + * operations mentioned below. + *

+ *

+ * {@code
+ * try {
+ *      TrackerManagementDAOFactory.beginTransaction();
+ *      .....
+ *      TrackerManagementDAOFactory.commitTransaction();
+ *      return success;
+ * } catch (Exception e) {
+ *      TrackerManagementDAOFactory.rollbackTransaction();
+ *      throw new DeviceManagementException("Error occurred while ...", e);
+ * } finally {
+ *      TrackerManagementDAOFactory.closeConnection();
+ * }
+ * }
+ * 
+ *

+ * Any transaction that retrieves data from the underlying data persistence mechanism MUST follow the sequence of + * operations mentioned below. + *

+ *

+ * {@code
+ * try {
+ *      TrackerManagementDAOFactory.openConnection();
+ *      .....
+ * } catch (Exception e) {
+ *      throw new DeviceManagementException("Error occurred while ..., e);
+ * } finally {
+ *      TrackerManagementDAOFactory.closeConnection();
+ * }
+ * }
+ * 
+ */ +public class TrackerManagementDAOFactory { + + private static DataSource dataSource; + private static String databaseEngine; + private static final Log log = LogFactory.getLog(TrackerManagementDAOFactory.class); + private static ThreadLocal currentConnection = new ThreadLocal<>(); + + + public static TrackerDAO getTrackerDAO() { + if (databaseEngine != null) { + switch (databaseEngine) { + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new TrackerDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); + } + + + public static void init(DataSourceConfig config) { + dataSource = resolveDataSource(config); + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } + } + + public static void init(DataSource dtSource) { + dataSource = dtSource; + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } + } + + public static void beginTransaction() throws TransactionManagementException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("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(); + conn.setAutoCommit(false); + currentConnection.set(conn); + } catch (SQLException e) { + throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e); + } + } + + public static void openConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn != null) { + throw new IllegalTransactionStateException("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"); + } + conn = dataSource.getConnection(); + currentConnection.set(conn); + } + + public static Connection getConnection() throws SQLException { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + return conn; + } + + public static void commitTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.commit(); + } catch (SQLException e) { + log.error("Error occurred while committing the transaction", e); + } + } + + public static void rollbackTransaction() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.rollback(); + } catch (SQLException e) { + log.warn("Error occurred while roll-backing the transaction", e); + } + } + + public static void closeConnection() { + Connection conn = currentConnection.get(); + if (conn == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally been caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + try { + conn.close(); + } catch (SQLException e) { + log.warn("Error occurred while close the connection"); + } + currentConnection.remove(); + } + + + /** + * Resolve data source from the data source definition + * + * @param config data source configuration + * @return data source resolved from the data source definition + */ + private static DataSource resolveDataSource(DataSourceConfig config) { + DataSource dataSource = null; + if (config == null) { + throw new RuntimeException( + "Device Management Repository data source configuration " + "is null and " + + "thus, is not initialized"); + } + JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition(); + if (jndiConfig != null) { + if (log.isDebugEnabled()) { + log.debug("Initializing Device Management Repository data source using the JNDI " + + "Lookup Definition"); + } + List jndiPropertyList = + jndiConfig.getJndiProperties(); + if (jndiPropertyList != null) { + Hashtable jndiProperties = new Hashtable(); + for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) { + jndiProperties.put(prop.getName(), prop.getValue()); + } + dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties); + } else { + dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null); + } + } + return dataSource; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 368daaf7133..1f42fc698f2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -188,6 +188,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //Return only not removed id list @Override public List getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { @@ -217,7 +218,82 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { } @Override - public List getAllocatedDevices(PaginationRequest request, int tenantId, int activeServerCount, int serverIndex) + public List getDevicesIds(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List statusList = request.getStatusList(); + boolean isStatusProvided = false; + + try { + conn = getConnection(); + String sql = "SELECT " + + "d1.ID AS DEVICE_ID, " + + "d1.DEVICE_IDENTIFICATION, " + + "e.STATUS, " + + "e.OWNER, " + + "e.IS_TRANSFERRED, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e, " + + "(SELECT d.ID, " + + "d.DEVICE_IDENTIFICATION " + + "FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " + + "WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? "; + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDeviceIds(rs); + devices.add(device); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + + @Override + public List getAllocatedDevices(PaginationRequest request, int tenantId, + int activeServerCount, int serverIndex) throws DeviceManagementDAOException { List devices; String deviceType = request.getDeviceType(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index beef6f15421..49b4f88c2a3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -188,6 +188,81 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //Return only not removed id list + @Override + public List getDevicesIds(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List statusList = request.getStatusList(); + boolean isStatusProvided = false; + + try { + conn = getConnection(); + String sql = "SELECT " + + "d1.ID AS DEVICE_ID, " + + "d1.DEVICE_IDENTIFICATION, " + + "e.STATUS, " + + "e.OWNER, " + + "e.IS_TRANSFERRED, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e, " + + "(SELECT d.ID, " + + "d.DEVICE_IDENTIFICATION " + + "FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " + + "WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? "; + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDeviceIds(rs); + devices.add(device); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + @Override public List getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { return null; @@ -195,7 +270,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getAllocatedDevices(PaginationRequest request, int tenantId, - int activeServerCount, int serverIndex) + int activeServerCount, int serverIndex) throws DeviceManagementDAOException { Connection conn; List devices = null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index eb358004abf..133464a633f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -179,6 +179,81 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //Return only not removed id list + @Override + public List getDevicesIds(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List statusList = request.getStatusList(); + boolean isStatusProvided = false; + + try { + conn = getConnection(); + String sql = "SELECT " + + "d1.ID AS DEVICE_ID, " + + "d1.DEVICE_IDENTIFICATION, " + + "e.STATUS, " + + "e.OWNER, " + + "e.IS_TRANSFERRED, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e, " + + "(SELECT d.ID, " + + "d.DEVICE_IDENTIFICATION " + + "FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " + + "WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? "; + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDeviceIds(rs); + devices.add(device); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + @Override public List getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { return null; @@ -186,7 +261,7 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { @Override public List getAllocatedDevices(PaginationRequest request, int tenantId, - int activeServerCount, int serverIndex) + int activeServerCount, int serverIndex) throws DeviceManagementDAOException { Connection conn; List devices = null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index f9e087e64e2..7686ada7ea7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -189,6 +189,81 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { } } + //Return only not removed id list + @Override + public List getDevicesIds(PaginationRequest request, int tenantId) + throws DeviceManagementDAOException { + Connection conn; + List devices = null; + String owner = request.getOwner(); + boolean isOwnerProvided = false; + String ownership = request.getOwnership(); + boolean isOwnershipProvided = false; + List statusList = request.getStatusList(); + boolean isStatusProvided = false; + + try { + conn = getConnection(); + String sql = "SELECT " + + "d1.ID AS DEVICE_ID, " + + "d1.DEVICE_IDENTIFICATION, " + + "e.STATUS, " + + "e.OWNER, " + + "e.IS_TRANSFERRED, " + + "e.ID AS ENROLMENT_ID " + + "FROM DM_ENROLMENT e, " + + "(SELECT d.ID, " + + "d.DEVICE_IDENTIFICATION " + + "FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " + + "WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? "; + //Add the query for ownership + if (ownership != null && !ownership.isEmpty()) { + sql = sql + " AND e.OWNERSHIP = ?"; + isOwnershipProvided = true; + } + //Add the query for owner + if (owner != null && !owner.isEmpty()) { + sql = sql + " AND e.OWNER = ?"; + isOwnerProvided = true; + } + if (statusList != null && !statusList.isEmpty()) { + sql += buildStatusQuery(statusList); + isStatusProvided = true; + } + + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + int paramIdx = 1; + stmt.setInt(paramIdx++, tenantId); + stmt.setInt(paramIdx++, tenantId); + if (isOwnershipProvided) { + stmt.setString(paramIdx++, ownership); + } + if (isOwnerProvided) { + stmt.setString(paramIdx++, owner); + } + if (isStatusProvided) { + for (String status : statusList) { + stmt.setString(paramIdx++, status); + } + } + + try (ResultSet rs = stmt.executeQuery()) { + devices = new ArrayList<>(); + while (rs.next()) { + Device device = DeviceManagementDAOUtil.loadDeviceIds(rs); + devices.add(device); + } + return devices; + } + } + } catch (SQLException e) { + String msg = "Error occurred while retrieving information of all " + + "registered devices"; + log.error(msg, e); + throw new DeviceManagementDAOException(msg, e); + } + } + @Override public List getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { return null; 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 new file mode 100644 index 00000000000..43d21b4d0e9 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/tracker/TrackerDAOImpl.java @@ -0,0 +1,366 @@ +/* + * Copyright (c) 2022, 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.core.dao.impl.tracker; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +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; +import org.wso2.carbon.device.mgt.core.dao.util.TrackerManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; + +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 TrackerDAOImpl implements TrackerDAO { + + private static final Log log = LogFactory.getLog(TrackerDAOImpl.class); + + @Override + public void addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) + throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DM_EXT_DEVICE_MAPPING(TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID) VALUES(?, ?, ?)"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, traccarDeviceId); + stmt.setInt(2, deviceId); + stmt.setInt(3, tenantId); + stmt.execute(); + } catch (SQLException e) { + String msg = "Error occurred while adding on trackerDevice mapping table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) + throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "UPDATE DM_EXT_DEVICE_MAPPING SET STATUS=?, TRACCAR_DEVICE_ID=? WHERE DEVICE_ID=? AND TENANT_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, status); + stmt.setInt(2, traccarDeviceId); + stmt.setInt(3, deviceId); + stmt.setInt(4, tenantId); + stmt.execute(); + } catch (SQLException e) { + String msg = "Error occurred while updating status on trackerDevice mapping table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public void removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_EXT_DEVICE_MAPPING WHERE DEVICE_ID = ? AND TENANT_ID = ? "; + stmt = conn.prepareStatement(sql, new String[]{"id"}); + stmt.setInt(1, deviceId); + stmt.setInt(2, tenantId); + stmt.executeUpdate(); + } catch (SQLException e) { + String msg = "Error occurred while removing on trackerDevice table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT ID, TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID, STATUS FROM DM_EXT_DEVICE_MAPPING WHERE " + + "DEVICE_ID = ? AND TENANT_ID = ? ORDER BY ID DESC LIMIT 1"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, tenantId); + rs = stmt.executeQuery(); + if (rs.next()) { + return TrackerManagementDAOUtil.loadTrackerDevice(rs); + } + return null; + } catch (SQLException e) { + String msg = "Error occurred while retrieving data from the trackerDevice table "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public void addTrackerGroup(int traccarGroupId, int groupId, int tenantId) + throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DM_EXT_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID, STATUS) VALUES(?, ?, ?, ?)"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, traccarGroupId); + stmt.setInt(2, groupId); + stmt.setInt(3, tenantId); + stmt.setInt(4, 1); + stmt.execute(); + } catch (SQLException e) { + String msg = "Error occurred while adding on traccarGroup mapping table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public Boolean updateTrackerGroupIdANDStatus(int traccarGroupId, int groupId, int tenantId, int status) + throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "UPDATE DM_EXT_GROUP_MAPPING SET STATUS=?, TRACCAR_GROUP_ID=? WHERE GROUP_ID=? AND TENANT_ID=?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, status); + stmt.setInt(2, traccarGroupId); + stmt.setInt(3, groupId); + stmt.setInt(4, tenantId); + stmt.execute(); + + return true; + } catch (SQLException e) { + String msg = "Error occurred while updating status on traccarGroup mapping table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public int removeTrackerGroup(int id) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + int status = -1; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_EXT_GROUP_MAPPING WHERE ID = ? "; + stmt = conn.prepareStatement(sql, new String[]{"id"}); + stmt.setInt(1, id); + stmt.executeUpdate(); + rs = stmt.getGeneratedKeys(); + if (rs.next()) { + status = 1; + } + return status; + } catch (SQLException e) { + String msg = "Error occurred while removing from traccarGroup mapping table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public TrackerGroupInfo getTrackerGroup(int groupId, int tenantId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + TrackerGroupInfo trackerGroupInfo = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT ID, TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID, STATUS FROM DM_EXT_GROUP_MAPPING WHERE " + + "GROUP_ID = ? AND TENANT_ID = ? ORDER BY ID DESC LIMIT 1"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + rs = stmt.executeQuery(); + if (rs.next()) { + trackerGroupInfo = TrackerManagementDAOUtil.loadTrackerGroup(rs); + } + return trackerGroupInfo; + } catch (SQLException e) { + String msg = "Error occurred while retrieving data from the traccarGroup mapping table "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public Boolean addTrackerUserDevicePermission(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) { + String msg = "Error occurred while adding permission on permissions mapping table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public Boolean removeTrackerUserDevicePermission(int deviceId, int userId, int removeType) + throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_DEVICE_ID = ?"; + // TODO: Recheck the usage of below if condition + if (removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE) { + sql = sql + " AND TRACCAR_USER_ID = ? "; + } + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + if (removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE) { + stmt.setInt(2, userId); + } + stmt.execute(); + return true; + } catch (SQLException e) { + String msg = "Error occurred while removing permission from permissions mapping table"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public List getUserIdofPermissionByDeviceId(int deviceId) + throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + List 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 ASC"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + rs = stmt.executeQuery(); + trackerPermissionInfo = new ArrayList<>(); + while (rs.next()) { + TrackerPermissionInfo loadPermission = TrackerManagementDAOUtil.loadPermission(rs); + trackerPermissionInfo.add(loadPermission); + } + return trackerPermissionInfo; + } catch (SQLException e) { + String msg = "Error occurred while retrieving permissions data from permissions mapping table "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) + throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + List trackerPermissionInfo = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " + + "TRACCAR_USER_ID = ? "; + if (NotInDeviceIdList != null && (!NotInDeviceIdList.isEmpty())) { + sql += TrackerManagementDAOUtil.buildDeviceIdNotInQuery(NotInDeviceIdList); + } + sql += " ORDER BY TRACCAR_USER_ID ASC"; + + stmt = conn.prepareStatement(sql); + int paramIdx = 1; + stmt.setInt(paramIdx++, userId); + if (NotInDeviceIdList != null && (!NotInDeviceIdList.isEmpty())) { + for (int id : NotInDeviceIdList) { + stmt.setInt(paramIdx++, id); + } + } + rs = stmt.executeQuery(); + trackerPermissionInfo = new ArrayList<>(); + while (rs.next()) { + TrackerPermissionInfo loadPermission = TrackerManagementDAOUtil.loadPermission(rs); + trackerPermissionInfo.add(loadPermission); + } + return trackerPermissionInfo; + } catch (SQLException e) { + String msg = "Error occurred while retrieving data from the permissions mapping table "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public Boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + try { + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " + + "TRACCAR_DEVICE_ID = ? AND TRACCAR_USER_ID = ? ORDER BY TRACCAR_DEVICE_ID DESC"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, deviceId); + stmt.setInt(2, userId); + + rs = stmt.executeQuery(); + return rs.next(); + } catch (SQLException e) { + String msg = "Error occurred while retrieving permissions data from permissions mapping table "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOUtil.cleanupResources(stmt, rs); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java index 1f031e7c4e0..91b549d9e63 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java @@ -173,6 +173,14 @@ public final class DeviceManagementDAOUtil { return enrolmentInfo; } + public static EnrolmentInfo loadEnrolmentStatus(ResultSet rs) throws SQLException { + EnrolmentInfo enrolmentInfo = new EnrolmentInfo(); + enrolmentInfo.setId(rs.getInt("ENROLMENT_ID")); + enrolmentInfo.setTransferred(rs.getBoolean("IS_TRANSFERRED")); + enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS"))); + return enrolmentInfo; + } + public static EnrolmentInfo loadMatchingEnrolment(ResultSet rs) throws SQLException { Map enrolmentInfos = new HashMap<>(); EnrolmentInfo enrolmentInfo = loadEnrolment(rs); @@ -218,6 +226,14 @@ public final class DeviceManagementDAOUtil { return device; } + public static Device loadDeviceIds(ResultSet rs) throws SQLException { + Device device = new Device(); + device.setId(rs.getInt("DEVICE_ID")); + device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + device.setEnrolmentInfo(loadEnrolmentStatus(rs)); + return device; + } + public static DeviceBilling loadDeviceBilling(ResultSet rs) throws SQLException { DeviceBilling device = new DeviceBilling(); device.setId(rs.getInt("ID")); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java new file mode 100644 index 00000000000..b36d3ec6683 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/TrackerManagementDAOUtil.java @@ -0,0 +1,124 @@ +/* Copyright (c) 2022, 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.core.dao.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +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.TrackerManagementDAOException; + +import javax.naming.InitialContext; +import javax.sql.DataSource; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Hashtable; +import java.util.List; +import java.util.StringJoiner; + +/** + * This class represents utilities required to work with group management data + */ +public final class TrackerManagementDAOUtil { + + private static final Log log = LogFactory.getLog(TrackerManagementDAOUtil.class); + + /** + * Cleanup resources used to transaction + * + * @param stmt Prepared statement used + * @param rs Obtained results set + */ + public static void cleanupResources(PreparedStatement 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); + } + } + } + + /** + * Lookup datasource using name and jndi properties + * + * @param dataSourceName Name of datasource to lookup + * @param jndiProperties Hash table of JNDI Properties + * @return datasource looked + */ + public static DataSource lookupDataSource(String dataSourceName, final Hashtable jndiProperties) { + try { + if (jndiProperties == null || jndiProperties.isEmpty()) { + return (DataSource) InitialContext.doLookup(dataSourceName); + } + final InitialContext context = new InitialContext(jndiProperties); + return (DataSource) context.lookup(dataSourceName); + } catch (Exception e) { + String msg = "Error in looking up data source: " + e.getMessage(); + log.error(msg, e); + throw new RuntimeException(msg, e); + } + } + + public static TrackerGroupInfo loadTrackerGroup(ResultSet rs) throws SQLException { + TrackerGroupInfo trackerGroupInfo = new TrackerGroupInfo(); + trackerGroupInfo.setId(rs.getInt("ID")); + trackerGroupInfo.setTraccarGroupId(rs.getInt("TRACCAR_GROUP_ID")); + trackerGroupInfo.setGroupId(rs.getInt("GROUP_ID")); + trackerGroupInfo.setTenantId(rs.getInt("TENANT_ID")); + trackerGroupInfo.setStatus(rs.getInt("STATUS")); + return trackerGroupInfo; + } + + public static TrackerDeviceInfo loadTrackerDevice(ResultSet rs) throws SQLException { + TrackerDeviceInfo trackerDeviceInfo = new TrackerDeviceInfo(); + trackerDeviceInfo.setId(rs.getInt("ID")); + trackerDeviceInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID")); + trackerDeviceInfo.setDeviceId(rs.getInt("DEVICE_ID")); + trackerDeviceInfo.setTenantId(rs.getInt("TENANT_ID")); + trackerDeviceInfo.setStatus(rs.getInt("STATUS")); + return trackerDeviceInfo; + } + + public static 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; + } + + public static String buildDeviceIdNotInQuery(List DeviceIdList) throws TrackerManagementDAOException { + if (DeviceIdList == null || DeviceIdList.isEmpty()) { + String msg = "SQL query build for Device Id list failed. Device Id list cannot be empty or null"; + log.error(msg); + throw new TrackerManagementDAOException(msg); + } + StringJoiner joiner = new StringJoiner(",", " AND TRACCAR_DEVICE_ID NOT IN(", ")"); + DeviceIdList.stream().map(status -> "?").forEach(joiner::add); + return joiner.toString(); + } +} 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 47f13ae9681..e9e5b0aaf5c 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 { @@ -385,6 +386,31 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { // LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload // ); } + + //Tracker update GPS Location + if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId()); + } catch (ExecutionException e) { + log.error("ExecutionException : " + e); + //throw new RuntimeException(e); + //Exception was not thrown due to being conflicted with non-traccar features + } catch (InterruptedException e) { + log.error("InterruptedException : " + e); + //throw new RuntimeException(e); + //Exception was not thrown due to being conflicted with non-traccar features + } + } else { + if(!HttpReportingUtil.isLocationPublishing()) { + log.info("Location publishing is disabled"); + } + if (!HttpReportingUtil.isTrackerEnabled()) { + log.info("Traccar is disabled"); + } + } + //Tracker update GPS Location + DeviceManagementDAOFactory.commitTransaction(); } catch (TransactionManagementException e) { throw new DeviceDetailsMgtException("Transactional error occurred while adding the device location " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java index 5cb1a1c9ab6..6a69cb02ba5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -41,6 +41,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; +import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.registry.core.service.RegistryService; @@ -83,6 +84,7 @@ public class DeviceManagementDataHolder { private GeoFenceEventOperationManager geoFenceEventOperationManager; private ExecutorService eventConfigExecutors; private OperationTimeoutTaskManagerService operationTimeoutTaskManagerService; + private DeviceAPIClientService deviceAPIClientService; private final Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap( new HashMap<>()); @@ -349,4 +351,12 @@ public class DeviceManagementDataHolder { OperationTimeoutTaskManagerService operationTimeoutTaskManagerService) { this.operationTimeoutTaskManagerService = operationTimeoutTaskManagerService; } + + public DeviceAPIClientService getDeviceAPIClientService() { + return deviceAPIClientService; + } + + public void setDeviceAPIClientService(DeviceAPIClientService deviceAPIClientService) { + this.deviceAPIClientService = deviceAPIClientService; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 4c031163aa7..a266a40499d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -53,6 +53,7 @@ import org.wso2.carbon.device.mgt.core.config.ui.UIConfigurationManager; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.EventManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOFactory; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.event.config.EventConfigurationProviderServiceImpl; @@ -78,6 +79,8 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceIm import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; +import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; +import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceMgtTenantMgtListener; @@ -190,6 +193,7 @@ public class DeviceManagementServiceComponent { DeviceManagementDAOFactory.init(dsConfig); GroupManagementDAOFactory.init(dsConfig); + TrackerManagementDAOFactory.init(dsConfig); NotificationManagementDAOFactory.init(dsConfig); OperationManagementDAOFactory.init(dsConfig); MetadataManagementDAOFactory.init(dsConfig); @@ -302,6 +306,11 @@ public class DeviceManagementServiceComponent { DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider); bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null); + /* Registering Device API Client Service */ + DeviceAPIClientService deviceAPIClientService = new DeviceAPIClientServiceImpl(); + DeviceManagementDataHolder.getInstance().setDeviceAPIClientService(deviceAPIClientService); + bundleContext.registerService(DeviceAPIClientService.class.getName(), deviceAPIClientService, null); + /* Registering Group Management Service */ GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl(); String defaultGroups = diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 4b1a424d27a..a84deb88944 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -66,7 +66,6 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; -import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; import java.sql.SQLException; import java.sql.Timestamp; @@ -187,6 +186,16 @@ public interface DeviceManagementProviderService { */ PaginationResult getAllDevices(PaginationRequest request) throws DeviceManagementException; + /** + * Method to retrieve all the devices with pagination support. + * + * @param request PaginationRequest object holding the data for pagination + * @return PaginationResult - Result including the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ + PaginationResult getAllDevicesIds(PaginationRequest request) throws DeviceManagementException; + /** * Method to retrieve all the devices with pagination support. * @@ -220,6 +229,16 @@ public interface DeviceManagementProviderService { + /** + * Method to retrieve all the devices with pagination support. + * + * @param request PaginationRequest object holding the data for pagination + * @return PaginationResult - Result including the required parameters necessary to do pagination. + * @throws DeviceManagementException If some unusual behaviour is observed while fetching the + * devices. + */ + PaginationResult getAllDevicesIdList(PaginationRequest request) throws DeviceManagementException; + /** * Returns the device of specified id. * 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 d9bb601faeb..c777ea87995 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 @@ -32,6 +32,7 @@ * specific language governing permissions and limitations * under the License. */ + package org.wso2.carbon.device.mgt.core.service; import com.google.common.reflect.TypeToken; @@ -50,7 +51,24 @@ import org.apache.http.protocol.HTTP; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.common.ActivityPaginationRequest; +import org.wso2.carbon.device.mgt.common.Billing; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceEnrollmentInfoNotification; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManager; +import org.wso2.carbon.device.mgt.common.DeviceNotification; +import org.wso2.carbon.device.mgt.common.DevicePropertyNotification; +import org.wso2.carbon.device.mgt.common.DeviceTransferRequest; +import org.wso2.carbon.device.mgt.common.DynamicTaskContext; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.FeatureManager; +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.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.Application; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; @@ -104,7 +122,14 @@ import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; 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.dao.*; +import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO; +import org.wso2.carbon.device.mgt.core.dao.BillingDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.DeviceStatusDAO; +import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; +import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; @@ -112,7 +137,6 @@ import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; -import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate; 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.internal.PluginInitializationListener; @@ -120,6 +144,7 @@ import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; +import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.email.sender.core.ContentProviderInfo; import org.wso2.carbon.email.sender.core.EmailContext; import org.wso2.carbon.email.sender.core.EmailSendingFailedException; @@ -141,12 +166,21 @@ import java.sql.SQLException; import java.sql.Timestamp; import java.text.Format; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collection; +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.TimeUnit; +import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; -//import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; - public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, PluginInitializationListener { @@ -394,6 +428,24 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv status = true; } + //enroll Traccar device + if (HttpReportingUtil.isTrackerEnabled()) { + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId); + } catch (ExecutionException e) { + log.error("ExecutionException : " + e); + //throw new RuntimeException(e); + //Exception was not thrown due to being conflicted with non-traccar features + } catch (InterruptedException e) { + log.error("InterruptedException : " + e); + //throw new RuntimeException(e); + //Exception was not thrown due to being conflicted with non-traccar features + } + } else { + log.info("Traccar is disabled"); + } + //enroll Traccar device + if (status) { addDeviceToGroups(deviceIdentifier, device.getEnrolmentInfo().getOwnership()); if (enrollmentConfiguration != null) { @@ -455,6 +507,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } deviceDAO.updateDevice(device, tenantId); enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), tenantId); + DeviceManagementDAOFactory.commitTransaction(); this.removeDeviceFromCache(deviceIdentifier); } catch (DeviceManagementDAOException e) { @@ -554,6 +607,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceDAO.updateDevice(device, tenantId); DeviceManagementDAOFactory.commitTransaction(); this.removeDeviceFromCache(deviceId); + + //procees to dis-enroll a device from traccar starts + if (HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .disEnrollDevice(device.getId(), tenantId); + } + //procees to dis-enroll a device from traccar ends + } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); String msg = "Error occurred while dis-enrolling '" + deviceId.getType() + @@ -1176,6 +1237,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return paginationResult; } + @Override + public PaginationResult getAllDevicesIds(PaginationRequest request) throws DeviceManagementException { + return this.getAllDevicesIdList(request); + } + @Override public PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException { if (request == null) { @@ -1236,6 +1302,48 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return paginationResult; } + @Override + public PaginationResult getAllDevicesIdList(PaginationRequest request) throws DeviceManagementException { + if (request == null) { + String msg = "Received incomplete pagination request for method getAllDevicesIdList"; + log.error(msg); + throw new DeviceManagementException(msg); + } + if (log.isDebugEnabled()) { + log.debug("Get devices with pagination " + request.toString()); + } + PaginationResult paginationResult = new PaginationResult(); + List allDevices; + int count = 0; + int tenantId = this.getTenantId(); + DeviceManagerUtil.validateDeviceListPageSize(request); + + try { + DeviceManagementDAOFactory.openConnection(); + allDevices = deviceDAO.getDevicesIds(request, tenantId); + count = deviceDAO.getDeviceCount(request, tenantId); + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while retrieving device list pertaining to the current tenant"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred while opening a connection to the data source"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } catch (Exception e) { + String msg = "Error occurred in getAllDevices"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + paginationResult.setData(allDevices); + + paginationResult.setRecordsFiltered(count); + paginationResult.setRecordsTotal(count); + return paginationResult; + } + @Override public Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException { if (deviceId == null) { @@ -3872,9 +3980,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv deviceLocation.setSpeed(Float.parseFloat(speed)); deviceLocation.setBearing(Float.parseFloat(bearing)); deviceInformationManager.addDeviceLocation(device, deviceLocation); - } catch (Exception e) { + } catch (DeviceDetailsMgtException e) { //We are not failing the execution since this is not critical for the functionality. But logging as // a warning for reference. + //Exception was not thrown due to being conflicted with non-traccar features log.warn("Error occurred while trying to add '" + device.getType() + "' device '" + device.getDeviceIdentifier() + "' (id:'" + device.getId() + "') location (lat:" + latitude + ", lon:" + longitude + ", altitude: " + altitude + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java index 029191d2468..cd560eef40c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java @@ -65,6 +65,7 @@ import org.wso2.carbon.device.mgt.core.geo.task.GeoFenceEventOperationManager; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; +import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; @@ -131,8 +132,24 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid this.groupDAO.addGroupProperties(deviceGroup, updatedGroupID, tenantId); } GroupManagementDAOFactory.commitTransaction(); + + //add new group in traccar + if (HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .addGroup(deviceGroup, updatedGroupID, tenantId); + } + //add new group in traccar } else { - throw new GroupAlreadyExistException("Group already exists with name '" + deviceGroup.getName() + "'."); + // add a group if not exist in traccar starts + if (HttpReportingUtil.isTrackerEnabled()){ + existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId); + int groupId = existingGroup.getGroupId(); + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .addGroup(deviceGroup, groupId, tenantId); + } + // add a group if not exist in traccar starts + + throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName()); } } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); @@ -213,6 +230,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid if (deviceGroup.getGroupProperties() != null && deviceGroup.getGroupProperties().size() > 0) { this.groupDAO.updateGroupProperties(deviceGroup, groupId, tenantId); } + + //procees to update a group in traccar starts + if (HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .updateGroup(deviceGroup, groupId, tenantId); + } + //procees to update a group in traccar starts + GroupManagementDAOFactory.commitTransaction(); } else { throw new GroupNotExistException("Group with ID - '" + groupId + "' doesn't exists!"); @@ -271,6 +296,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } } + + //procees to delete a group from traccar starts + if (HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .deleteGroup(groupId, tenantId); + } + //procees to delete a group from traccar ends + if (isDeleteChildren) { groupIdsToDelete.add(groupId); groupDAO.deleteGroupsMapping(groupIdsToDelete, tenantId); @@ -287,6 +320,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid if (log.isDebugEnabled()) { log.debug("DeviceGroup " + deviceGroup.getName() + " removed."); } + return true; } catch (GroupManagementDAOException e) { GroupManagementDAOFactory.rollbackTransaction(); 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 new file mode 100644 index 00000000000..605d4f7a46b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -0,0 +1,84 @@ +/* + * 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; + +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.dao.TrackerManagementDAOException; +import java.util.concurrent.ExecutionException; + +public interface DeviceAPIClientService { + + /** + * Add GPS location of a device Traccar configuration records + * + * @param device to be added to update location of the device + * @param deviceLocation to be added to update location of the device + * @throws TrackerManagementDAOException errors thrown while inserting location of a traccar device + */ + void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId) throws + ExecutionException, InterruptedException; + + /** + * Create device Traccar configuration records + * + * @param device to be added + * @throws TrackerManagementDAOException errors thrown while creating a traccar device + */ + void addDevice(Device device, int tenantId) throws ExecutionException, InterruptedException; + + /** + * Delete a device Traccar configuration records + * + * @param deviceId to be delete a device + * @throws TrackerManagementDAOException errors thrown while deleting a traccar device + */ + void disEnrollDevice(int deviceId, int tenantId) throws ExecutionException, InterruptedException; + + /** + * Delete a device Traccar configuration records + * + * @param group to be add a group + * @throws TrackerManagementDAOException errors thrown while adding a traccar group + */ + void addGroup(DeviceGroup group, int groupID, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + + /** + * Delete a device Traccar configuration records + * + * @param group to be update the group + * @throws TrackerManagementDAOException errors thrown while adding a traccar group + */ + void updateGroup(DeviceGroup group, int groupID, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + + /** + * Delete a device Traccar configuration records + * + * @param groupId to delete a group + * @param tenantId to delete a group + * @throws TrackerManagementDAOException errors thrown while adding a traccar group + */ + void deleteGroup(int groupId, int tenantId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; +} 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 new file mode 100644 index 00000000000..e8beae1053e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/TraccarClient.java @@ -0,0 +1,79 @@ +/* + * 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; + +import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; +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.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 java.sql.SQLException; +import java.util.List; +import java.util.concurrent.ExecutionException; + +public interface TraccarClient { + + void addDevice(TraccarDevice deviceInfo, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + + void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + + void disEnrollDevice(int traccarDeviceId, int tenantId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; + + void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + + void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException; + + void deleteGroup(int traccarGroupId, int tenantId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; + + void setPermission(int userId, int deviceId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; + + void removePermission(int userId, int deviceId, int removeType) throws + TrackerManagementDAOException, ExecutionException, InterruptedException; + + List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) + throws TrackerManagementDAOException; + + boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws + TrackerManagementDAOException, SQLException; + + TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws + TrackerManagementDAOException, SQLException; + + String fetchAllUsers() throws TrackerManagementDAOException, ExecutionException, InterruptedException; + + String fetchUserInfo(String userName) throws TrackerManagementDAOException, ExecutionException, InterruptedException; + + String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException; + + String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException; + + String returnUser(String userName) throws TrackerManagementDAOException; +} 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 new file mode 100644 index 00000000000..526de67f616 --- /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/TraccarClientImpl.java @@ -0,0 +1,753 @@ +/* + * Copyright (C) 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 okhttp3.ConnectionPool; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONArray; +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; +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.TraccarGateway; +import org.wso2.carbon.device.mgt.core.traccar.common.util.TraccarUtil; +import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationManager; +import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; + +import java.sql.SQLException; +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 { + private static final Log log = LogFactory.getLog(TraccarClientImpl.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 TraccarClientImpl() { + client = new OkHttpClient.Builder() + .connectTimeout(30, TimeUnit.SECONDS) + .writeTimeout(30, TimeUnit.SECONDS) + .readTimeout(45, TimeUnit.SECONDS) + .connectionPool(new ConnectionPool(100, 50, TimeUnit.SECONDS)) + .build(); + this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO(); + } + + private class OkHttpClientThreadPool implements Callable { + final String publisherUrlWithContext; + final JSONObject payload; + private final String method; + private String authorizeKey; + private String serverUri; + + private OkHttpClientThreadPool(String publisherUrlWithContext, JSONObject payload, String method, + String authorizeKey, String serverUri) { + this.publisherUrlWithContext = publisherUrlWithContext; + this.payload = payload; + this.method = method; + this.authorizeKey = authorizeKey; + this.serverUri = serverUri; + } + + @Override + public String call() throws Exception { + 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)) { + if (publisherUrlWithContext.contains("permission")) { + requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); + builder = builder.delete(requestBody); + } else { + builder = builder.delete(); + } + } + + request = builder.url(serverUri + publisherUrlWithContext).addHeader(authorization, authorizeKey).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, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + return result.get(); + } + + public String fetchUserInfo(String userName) throws ExecutionException, InterruptedException { + String allUsers = fetchAllUsers(); //get all users + JSONArray fetchAllUsers = new JSONArray(allUsers); //loop users + for (int i = 0; i < fetchAllUsers.length(); i++) { + // if login is null then check the name or if login is not null then check the login + if (fetchAllUsers.getJSONObject(i).isNull("login")) { + if (Objects.equals(fetchAllUsers.getJSONObject(i).getString("name"), userName)) { + return fetchAllUsers.getJSONObject(i).toString(); + } + } else { + if (Objects.equals(fetchAllUsers.getJSONObject(i).getString("login"), userName) || + Objects.equals(fetchAllUsers.getJSONObject(i).getString("name"), userName)) { + return fetchAllUsers.getJSONObject(i).toString(); + } + } + } + + return TraccarHandlerConstants.Types.USER_NOT_FOUND; + } + + public String returnUser(String userName) throws TrackerManagementDAOException { + try { + String result = DeviceAPIClientServiceImpl.fetchUserInfo(userName); + Date today = new Date(); + LocalDateTime tomorrow = LocalDateTime.from(today.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1); + String token = DeviceAPIClientServiceImpl.generateRandomString(TraccarHandlerConstants.Types.TRACCAR_TOKEN); + + TraccarUser traccarUser = new TraccarUser(); + traccarUser.setToken(token); + + if (Objects.equals(result, TraccarHandlerConstants.Types.USER_NOT_FOUND)) { + //create user + log.info("Creating a user on Traccar client"); + traccarUser.setName(userName); + traccarUser.setLogin(userName); + traccarUser.setEmail(userName); + traccarUser.setPassword(DeviceAPIClientServiceImpl.generateRandomString(TraccarHandlerConstants.Types.DEFAULT_RANDOM)); + traccarUser.setDeviceLimit(-1); + //traccarUser.setUserLimit(-1); + traccarUser.setExpirationTime(tomorrow.toString()); + DeviceAPIClientServiceImpl.createUser(traccarUser); + } else { + //update user + log.info("Updating the user on Traccar client"); + JSONObject obj = new JSONObject(result); + + traccarUser.setId(obj.getInt("id")); + traccarUser.setName(obj.getString("name")); + if (!obj.isNull("login")) { + traccarUser.setLogin(obj.getString("login")); + } + traccarUser.setEmail(obj.getString("email")); + traccarUser.setDeviceLimit(obj.getInt("deviceLimit")); + traccarUser.setUserLimit(obj.getInt("userLimit")); + traccarUser.setAdministrator(obj.getBoolean("administrator")); + traccarUser.setDisabled(obj.getBoolean("disabled")); + traccarUser.setReadonly(obj.getBoolean("readonly")); + if (!obj.getBoolean("administrator")) { + traccarUser.setExpirationTime(tomorrow.toString()); + } else if (!obj.isNull("expirationTime")) { + traccarUser.setExpirationTime(obj.getString("expirationTime")); + } + DeviceAPIClientServiceImpl.updateUser(traccarUser, obj.getInt("id")); + } + result = DeviceAPIClientServiceImpl.fetchUserInfo(userName); + return result; + } catch (InterruptedException | ExecutionException e) { + JSONObject obj = new JSONObject(); + String msg = "Error occurred while executing enrollment status of the device."; + obj.put("error", msg); + obj.put("e", e); + log.error(msg, e); + return obj.toString(); + } + } + + public String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException { + String method = TraccarHandlerConstants.Methods.POST; + String url = defaultPort + "/api/users"; + JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser); + + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + return res.get(); + } + + 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); + + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + return res.get(); + } + + public void setPermission(int userId, int deviceId) + throws ExecutionException, InterruptedException, TrackerManagementDAOException { + 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, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + String result = res.get(); + + if (("").equals(result)) { + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.addTrackerUserDevicePermission(userId, deviceId); + TrackerManagementDAOFactory.commitTransaction(); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + } else { + log.error("Couldn't add the permission record: " + result); + } + } + + public void removePermission(int userId, int deviceId, int removeType) + throws TrackerManagementDAOException, 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, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + + if (res.get() != null) { + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.removeTrackerUserDevicePermission(deviceId, userId, removeType); + TrackerManagementDAOFactory.commitTransaction(); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + } + } + + public List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) + throws TrackerManagementDAOException { + try { + TrackerManagementDAOFactory.openConnection(); + return trackerDAO.getUserIdofPermissionByUserIdNIdList(userId, NotInDeviceIdList); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + } + + public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { + try { + TrackerManagementDAOFactory.openConnection(); + return trackerDAO.getTrackerDevice(deviceId, tenantId); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (TrackerManagementDAOException e) { + String msg = "Could not add new device location"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + } + + public boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) + throws TrackerManagementDAOException { + Boolean result = false; + try { + TrackerManagementDAOFactory.openConnection(); + result = trackerDAO.getUserIdofPermissionByDeviceIdNUserId(deviceId, userId); + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + return result; + } + + /** + * Add Traccar Device operation. + * + * @param traccarDevice with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId + * Model, Contact, Category, fenceIds + * @throws TrackerManagementDAOException Failed while add Traccar Device the operation + */ + public void addDevice(TraccarDevice traccarDevice, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerDeviceInfo trackerDeviceInfo = null; + try { + TrackerManagementDAOFactory.openConnection(); + trackerDeviceInfo = trackerDAO.getTrackerDevice(traccarDevice.getId(), tenantId); + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + if (trackerDeviceInfo == null) { + //add the device + String url = defaultPort + "/api/devices"; + JSONObject payload = TraccarUtil.TraccarDevicePayload(traccarDevice); + + Future res = executor.submit(new OkHttpClientThreadPool(url, payload, TraccarHandlerConstants.Methods.POST, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + 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(); + log.info("TraccarDeviceId - " + traccarDeviceId); + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); + trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); + if (trackerDeviceInfo != null && 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 TrackerManagementDAOException(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + JSONObject returnUserInfo = new JSONObject(returnUser(username)); + setPermission(returnUserInfo.getInt("id"), traccarDeviceId); + } + } + } else { + String msg = "The device already exist"; + log.error(msg); + throw new TrackerAlreadyExistException(msg); + } + } + + /** + * 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 + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerDeviceInfo trackerDeviceInfo = null; + try { + TrackerManagementDAOFactory.openConnection(); + trackerDeviceInfo = trackerDAO.getTrackerDevice(device.getId(), tenantId); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (TrackerManagementDAOException e) { + String msg = "Could not add new device location"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + //check if the device is already exist before updating the location + if (trackerDeviceInfo == null) { + //add device if not exist + addDevice(device, tenantId); + } else { + //Update Location + if (log.isDebugEnabled()) { + log.info("Updating Location of the device: " + device.getId()); + } + String url = locationUpdatePort + "/?id=" + deviceInfo.getDeviceIdentifier() + + "×tamp=" + deviceInfo.getTimestamp() + "&lat=" + deviceInfo.getLat() + + "&lon=" + deviceInfo.getLon() + "&bearing=" + deviceInfo.getBearing() + + "&speed=" + deviceInfo.getSpeed() + "&ignition=true"; + + executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.GET, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + "http://localhost:")); + } + } + + /** + * Dis-enroll a Device operation. + * + * @param deviceId identified via deviceIdentifier + * @throws TrackerManagementDAOException Failed while dis-enroll a Traccar Device operation + */ + public void disEnrollDevice(int deviceId, int tenantId) throws TrackerManagementDAOException, ExecutionException, InterruptedException { + TrackerDeviceInfo trackerDeviceInfo = null; + List trackerPermissionInfo = null; + try { + TrackerManagementDAOFactory.beginTransaction(); + trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); + log.info("deviceId - " + deviceId); + if (trackerDeviceInfo != null) { + trackerDAO.removeTrackerDevice(deviceId, tenantId); + TrackerManagementDAOFactory.commitTransaction(); + trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDeviceInfo.getTraccarDeviceId()); + } + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId"; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + log.info("--------Disenrolling Device with device id " + deviceId + " from traccar client--------"); + //Delete from traccar + if (trackerDeviceInfo != null) { + String method = TraccarHandlerConstants.Methods.DELETE; + String url = defaultPort + "/api/devices/" + trackerPermissionInfo.get(0).getTraccarDeviceId(); + + executor.submit(new OkHttpClientThreadPool(url, null, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + + //remove permissions + try { + removePermission( + trackerPermissionInfo.get(0).getTraccarUserId(), + trackerPermissionInfo.get(0).getTraccarDeviceId(), + TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE); + } catch (ExecutionException e) { + log.error("ExecutionException : " + e); + throw new ExecutionException(e); + } + } + } + + /** + * Add Traccar Device operation. + * + * @param groupInfo with groupName + * @throws TrackerManagementDAOException Failed while add Traccar Device the operation + */ + public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TrackerGroupInfo trackerGroupInfo = null; + try { + TrackerManagementDAOFactory.openConnection(); + 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 groupId."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection."; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + 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, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + String result = res.get(); + + 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) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId. "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (TransactionManagementException e) { + String msg = "Error occurred establishing the DB connection. "; + log.error(msg, e); + TrackerManagementDAOFactory.rollbackTransaction(); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + } else { + // TODO: Assumed the error message change if wrong + log.error("Response does not contains the key id: " + result); + } + } else { + // TODO: Assumed the error message change if wrong + log.error("Response does not contains a JSON object " + result); + } + } + + /** + * update Traccar Group operation. + * + * @param groupInfo with groupName + * @throws TrackerManagementDAOException Failed while add Traccar Device the operation + */ + public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + 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); + throw new TrackerManagementDAOException(msg, e); + } catch (TrackerManagementDAOException e) { + String msg = "Could not find traccar group details. "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + if ((res == null) || (res.getTraccarGroupId() == 0)) { + //add a new traccar group + 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 TrackerManagementDAOException(msg, e); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection. "; + log.error(msg, e); + throw new TrackerManagementDAOException(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 method = TraccarHandlerConstants.Methods.PUT; + String url = defaultPort + "/api/groups/" + obj.getInt("traccarGroupId"); + + executor.submit(new OkHttpClientThreadPool(url, payload, method, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + } + } + + /** + * Add Traccar Device operation. + * + * @param groupId + * @throws TrackerManagementDAOException Failed while add Traccar Device the operation + */ + public void deleteGroup(int groupId, int tenantId) throws TrackerManagementDAOException, ExecutionException, InterruptedException { + 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(); + + String url = defaultPort + "/api/groups/" + obj.getInt("traccarGroupId"); + + executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.DELETE, + authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), + serverUrl(HttpReportingUtil.trackerServer()))); + } + } + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection. "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with groupId. "; + log.error(msg, e); + throw new TrackerManagementDAOException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + } + + public String generateRandomString(int len) { + String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + Random rnd = new Random(); + StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) + sb.append(chars.charAt(rnd.nextInt(chars.length()))); + return sb.toString(); + } + + private TraccarGateway getTraccarGateway() { + return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway( + TraccarHandlerConstants.TraccarConfig.GATEWAY_NAME); + } + + public String authorizedKey(String trackerUser, String trackerPassword) { + String newAuthorizationKey = authorizationKey; + if (trackerUser != null && trackerPassword != null) { + newAuthorizationKey = trackerUser + ':' + trackerPassword; + + byte[] result = newAuthorizationKey.getBytes(); + byte[] res = Base64.encodeBase64(result); + newAuthorizationKey = "Basic " + new String(res); + } + return newAuthorizationKey; + } + + public String serverUrl(String serverUrl) { + String newServerUri = endpoint; + if (serverUrl != null) { + newServerUri = serverUrl; + } + return newServerUri; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java new file mode 100644 index 00000000000..f1f71cb99a8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/DeviceAPIClientServiceImpl.java @@ -0,0 +1,179 @@ +/* + * Copyright (C) 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.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; +import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; +import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; +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.traccar.api.service.DeviceAPIClientService; +import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TraccarClientImpl; +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 java.util.Date; +import java.util.List; +import java.util.concurrent.ExecutionException; + +public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { + + private static final Log log = LogFactory.getLog(DeviceAPIClientServiceImpl.class); + + public void addDevice(Device device, int tenantId) throws ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + String lastUpdatedTime = String.valueOf((new Date().getTime())); + TraccarDevice traccarDevice = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(), + "online", "false", lastUpdatedTime, "", "", "", "", + "", ""); + try { + client.addDevice(traccarDevice, tenantId); + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId"; + log.error(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The device already exist"; + log.error(msg, e); + } + } + + public void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId) throws ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + TraccarPosition traccarPosition = new TraccarPosition(device.getDeviceIdentifier(), + deviceLocation.getUpdatedTime().getTime(), + deviceLocation.getLatitude(), deviceLocation.getLongitude(), + deviceLocation.getBearing(), deviceLocation.getSpeed()); + + String lastUpdatedTime = String.valueOf((new Date().getTime())); + TraccarDevice traccarDevice = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(), + "online", "false", lastUpdatedTime, "", "", "", "", + "", ""); + try { + client.updateLocation(traccarDevice, traccarPosition, tenantId); + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId"; + log.error(msg, e); + }catch (TrackerAlreadyExistException e) { + String msg = "The device already exist"; + log.error(msg, e); + } + } + + public void disEnrollDevice(int deviceId, int tenantId) throws ExecutionException, InterruptedException{ + TraccarClientImpl client = new TraccarClientImpl(); + try { + client.disEnrollDevice(deviceId, tenantId); + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while dis-enrolling the device"; + log.error(msg, e); + } + } + + public void addGroup(DeviceGroup group, int groupId, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + TraccarGroups traccarGroups = new TraccarGroups(group.getName()); + client.addGroup(traccarGroups, groupId, tenantId); + } + + public void updateGroup(DeviceGroup group, int groupId, int tenantId) throws + TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + TraccarGroups traccarGroups = new TraccarGroups(group.getName()); + client.updateGroup(traccarGroups, groupId, tenantId); + } + + public void deleteGroup(int groupId, int tenantId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + client.deleteGroup(groupId, tenantId); + } + + public static String fetchUserInfo(String userName) throws ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + return client.fetchUserInfo(userName); + } + + public static TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws + TrackerManagementDAOException { + TraccarClientImpl client = new TraccarClientImpl(); + return client.getTrackerDevice(deviceId, tenantId); + } + + public static boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws + TrackerManagementDAOException { + TraccarClientImpl client = new TraccarClientImpl(); + return client.getUserIdofPermissionByDeviceIdNUserId(deviceId, userId); + } + + public static String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + return client.createUser(traccarUser); + } + + public static String updateUser(TraccarUser traccarUser, int userId) throws + ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + return client.updateUser(traccarUser, userId); + } + + public static String returnUser(String userName) { + TraccarClientImpl client = new TraccarClientImpl(); + try { + return client.returnUser(userName); + } catch (TrackerManagementDAOException e) { + JSONObject obj = new JSONObject(); + String msg = "Error occurred while creating a user: "+ e; + obj.put("error", msg); + return obj.toString(); + } + } + + public static void addTrackerUserDevicePermission(int userId, int deviceId) throws + TrackerManagementDAOException, ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + client.setPermission(userId, deviceId); + } + + public static void removeTrackerUserDevicePermission(int userId, int deviceId, int removeType) throws + TrackerManagementDAOException, ExecutionException, InterruptedException { + TraccarClientImpl client = new TraccarClientImpl(); + client.removePermission(userId, deviceId, removeType); + } + + public static List getUserIdofPermissionByUserIdNIdList(int userId, List NotInDeviceIdList) throws + TrackerManagementDAOException { + TraccarClientImpl client = new TraccarClientImpl(); + return client.getUserIdofPermissionByUserIdNIdList(userId, NotInDeviceIdList); + } + + public static String generateRandomString(int len) { + TraccarClientImpl client = new TraccarClientImpl(); + return client.generateRandomString(len); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java new file mode 100644 index 00000000000..e99832e9398 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarHandlerConstants.java @@ -0,0 +1,56 @@ +/* + * 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.common; + +public class TraccarHandlerConstants { + + public static class TraccarConfig { + public static final String TRACCAR_CONFIG_XML_NAME = "traccar-config.xml"; + public static final String GATEWAY_NAME = "sample"; + public static final String ENDPOINT = "api-endpoint"; + public static final String AUTHORIZATION = "authorization"; + public static final String AUTHORIZATION_KEY = "authorization-key"; + public static final String DEFAULT_PORT = "default-port"; + public static final String LOCATION_UPDATE_PORT = "location-update-port"; + } + + // TODO: Get these from http client + public static class Methods { + public static final String POST = "POST"; + public static final String GET = "GET"; + public static final String PUT = "PUT"; + public static final String DELETE = "DELETE"; + } + + public static class Types { + public static final String DEVICE = "DEVICE"; + public static final String GROUP = "GROUP"; + public static final String USER = "USER"; + public static final String PERMISSION = "PERMISSION"; + + public static final String USER_NOT_FOUND = "USER_NOT_FOUND"; + + public static final int DEFAULT_RANDOM = 10; + public static final int TRACCAR_TOKEN = 32; + public static final int REMOVE_TYPE_MULTIPLE = -1; + public static final int REMOVE_TYPE_SINGLE = 1; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java new file mode 100644 index 00000000000..163ae4f3a5d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarDevice.java @@ -0,0 +1,112 @@ +/* + * 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.common.beans; + +public class TraccarDevice { + private int id; + private String deviceIdentifier; + private String deviceName; + private String uniqueId; + private String status; + private String disabled; + private String lastUpdate; + private String positionId; + private String groupId; + private String phone; + private String model; + private String contact; + private String category; + + public TraccarDevice(String deviceIdentifier){ + this.deviceIdentifier =deviceIdentifier; + } + + public TraccarDevice(int id, String deviceName, String uniqueId, String status, String disabled, String lastUpdate, + String positionId, String groupId, String phone, String model, String contact, + String category){ + this.id =id; + this.deviceName =deviceName; + this.uniqueId=uniqueId; + this.status=status; + this.disabled =disabled; + this.lastUpdate =lastUpdate; + this.positionId =positionId; + this.groupId =groupId; + this.phone =phone; + this.model =model; + this.contact =contact; + this.category =category; + } + + public TraccarDevice(){ } + + public int getId() { return id; } + + public void setId(int id) { this.id = id; } + + public String getDeviceIdentifier() {return deviceIdentifier;} + + public void setDeviceIdentifier(String deviceIdentifier) {this.deviceIdentifier = deviceIdentifier;} + + public String getDeviceName() {return deviceName;} + + public void setDeviceName(String deviceName) {this.deviceName = deviceName;} + + public String getUniqueId() {return uniqueId;} + + public void setUniqueId(String uniqueId) {this.uniqueId = uniqueId;} + + public String getStatus() {return status;} + + public void setStatus(String status) {this.status = status;} + + public String getDisabled() {return disabled;} + + public void setDisabled(String disabled) {this.disabled = disabled;} + + public String getLastUpdate() {return lastUpdate;} + + public void setLastUpdate(String lastUpdate) {this.lastUpdate = lastUpdate;} + + public String getPhone() {return phone;} + + public void setPhone(String phone) {this.phone = phone;} + + public String getModel() {return model;} + + public void setModel(String model) {this.model = model;} + + public String getContact() {return contact;} + + public void setContact(String contact) {this.contact = contact;} + + public String getCategory() {return category;} + + public void setCategory(String category) {this.category = category;} + + public String getPositionId() {return positionId;} + + public void setPositionId(String positionId) {this.positionId = positionId;} + + public String getGroupId() {return groupId;} + + public void setGroupId(String groupId) {this.groupId = groupId;} + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarGroups.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarGroups.java new file mode 100644 index 00000000000..5fdf1026d43 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarGroups.java @@ -0,0 +1,50 @@ +/* + * 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.common.beans; + +public class TraccarGroups { + private String name; + private int groupId; + + public TraccarGroups(String name){ + this.name =name; + } + + public TraccarGroups(String name, int groupId){ + this.name =name; + this.groupId =groupId; + } + + public TraccarGroups(){ } + + public String getName() { return name; } + + public void setName(String name) { + this.name = name; + } + + public int getGroupId() { + return groupId; + } + + public void setGroupId(int groupId) { + this.groupId = groupId; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarPosition.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarPosition.java new file mode 100644 index 00000000000..8ee07b7fdbf --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarPosition.java @@ -0,0 +1,109 @@ +/* + * 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.common.beans; + +public class TraccarPosition { + private int id; + private String deviceIdentifier; + private Long timestamp; + private Double lat; + private Double lon; + private Float bearing; + private Float speed; + + public TraccarPosition(int id, String deviceIdentifier, long timestamp, Double lat, Double lon, + float bearing, float speed){ + this.id =id; + this.deviceIdentifier =deviceIdentifier; + this.timestamp=timestamp; + this.lat=lat; + this.lon =lon; + this.bearing =bearing; + this.speed =speed; + } + + public TraccarPosition(String deviceIdentifier, long timestamp, Double lat, Double lon, + float bearing, float speed){ + this.deviceIdentifier =deviceIdentifier; + this.timestamp=timestamp; + this.lat=lat; + this.lon =lon; + this.bearing =bearing; + this.speed =speed; + } + + public TraccarPosition(){ } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public Long getTimestamp() { + return timestamp; + } + + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + public Double getLat() { + return lat; + } + + public void setLat(Double lat) { + this.lat = lat; + } + + public Double getLon() { + return lon; + } + + public void setLon(Double lon) { + this.lon = lon; + } + + public Float getBearing() { + return bearing; + } + + public void setBearing(Float bearing) { + this.bearing = bearing; + } + + public Float getSpeed() { + return speed; + } + + public void setSpeed(Float speed) { + this.speed = speed; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java new file mode 100644 index 00000000000..4531e1d122d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/beans/TraccarUser.java @@ -0,0 +1,176 @@ +/* + * 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.core.traccar.common.beans; + +import java.io.Serializable; + +public class TraccarUser implements Serializable { + + private static final long serialVersionUID = -1916365851689588289L; + + private int id; + private String name; + private String login; + private String email; + private String phone; + private Boolean readonly; + private Boolean administrator; + private Boolean disabled; + private String expirationTime; + private int deviceLimit; + private int userLimit; + private Boolean deviceReadonly; + private String token; + private String password; + + public TraccarUser() { + } + + public TraccarUser(String name, String login, String email, String phone, Boolean readonly, Boolean administrator, + Boolean disabled, String expirationTime, int deviceLimit, int userLimit, + Boolean deviceReadonly, String token, String password) { + this.name = name; + this.login = login; + this.email = email; + this.phone = phone; + this.readonly = readonly; + this.administrator = administrator; + this.disabled = disabled; + this.expirationTime = expirationTime; + this.deviceLimit = deviceLimit; + this.userLimit = userLimit; + this.deviceReadonly = deviceReadonly; + this.token = token; + this.password = password; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public Boolean getReadonly() { + return readonly; + } + + public void setReadonly(Boolean readonly) { + this.readonly = readonly; + } + + public Boolean getAdministrator() { + return administrator; + } + + public void setAdministrator(Boolean administrator) { + this.administrator = administrator; + } + + public Boolean getDisabled() { + return disabled; + } + + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } + + public String getExpirationTime() { + return expirationTime; + } + + public void setExpirationTime(String expirationTime) { + this.expirationTime = expirationTime; + } + + public int getDeviceLimit() { + return deviceLimit; + } + + public void setDeviceLimit(int deviceLimit) { + this.deviceLimit = deviceLimit; + } + + public int getUserLimit() { + return userLimit; + } + + public void setUserLimit(int userLimit) { + this.userLimit = userLimit; + } + + public Boolean getDeviceReadonly() { + return deviceReadonly; + } + + public void setDeviceReadonly(Boolean deviceReadonly) { + this.deviceReadonly = deviceReadonly; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/Property.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/Property.java new file mode 100644 index 00000000000..8aca8595ae3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/Property.java @@ -0,0 +1,49 @@ +/* + * 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.common.config; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlValue; + +@XmlRootElement(name = "Property") +public class Property { + + private String name; + private String value; + + @XmlAttribute(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlValue + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfiguration.java new file mode 100644 index 00000000000..ee355d31f02 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarConfiguration.java @@ -0,0 +1,68 @@ +/* + * 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.common.config; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "TraccarConfiguration") +public class TraccarConfiguration { + + private List traccarGateways; + + @XmlElementWrapper(name = "Gateways") + @XmlElement(name = "Gateway") + public List getTraccarGateways() { + return traccarGateways; + } + + public void setTraccarGateways(List traccarGateways) { + this.traccarGateways = traccarGateways; + } + + /** + * Retrieve the default Traccar Gateway as defined in the Traccar configuration. + * @return default {@link TraccarGateway} + */ + public TraccarGateway getDefaultTraccarGateway() { + for (TraccarGateway traccarGateway : traccarGateways) { + if (traccarGateway.isDefault()) { + return traccarGateway; + } + } + return null; + } + + /** + * Retrieve Traccar Gateway by the provided Gateway Name + * @param gatewayName has the name of the Gateway to be retrieved + * @return retrieved {@link TraccarGateway} + */ + public TraccarGateway getTraccarGateway(String gatewayName) { + for (TraccarGateway traccarGateway : traccarGateways) { + if (gatewayName.equals(traccarGateway.getName())) { + return traccarGateway; + } + } + return null; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarGateway.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarGateway.java new file mode 100644 index 00000000000..87f2a7fa025 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/config/TraccarGateway.java @@ -0,0 +1,87 @@ +/* + * 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.common.config; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "Gateway") +public class TraccarGateway { + + private String name; + private String extensionClass; + private boolean isDefault; + private List properties; + + @XmlAttribute(name = "name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlAttribute(name = "extensionClass") + public String getExtensionClass() { + return extensionClass; + } + + public void setExtensionClass(String extensionClass) { + this.extensionClass = extensionClass; + } + + @XmlAttribute(name = "isDefault") + public boolean isDefault() { + return isDefault; + } + + public void setDefault(boolean aDefault) { + isDefault = aDefault; + } + + @XmlElementWrapper(name = "Properties") + @XmlElement(name = "Property") + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + /** + * Retrives the Property based on the provided property name + * @param propertyName has the name of the Property to be retrieved + * @return retrieved {@link Property} + */ + public Property getPropertyByName(String propertyName) { + for (Property property : properties) { + if (propertyName.equals(property.getName())) { + return property; + } + } + return null; + } +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java new file mode 100644 index 00000000000..986b10624d8 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/util/TraccarUtil.java @@ -0,0 +1,69 @@ +/* + * 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.common.util; + +import org.json.JSONObject; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; +import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser; + +import java.util.ArrayList; +import java.util.List; + +public class TraccarUtil { + public static JSONObject TraccarUserPayload(TraccarUser traccarUser) { + JSONObject payload = new JSONObject(); + JSONObject attribute = new JSONObject(); + attribute.put("speedUnit", "kmh"); + 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()); + payload.put("attributes", attribute); + return payload; + } + + public static JSONObject TraccarDevicePayload(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; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java new file mode 100644 index 00000000000..b79ad078665 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/core/config/TraccarConfigurationManager.java @@ -0,0 +1,102 @@ +/* + * 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.core.config; + +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.core.traccar.common.TraccarHandlerConstants; +import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfiguration; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.File; + + +public class TraccarConfigurationManager { + private static final Log log = LogFactory.getLog(TraccarConfigurationManager.class); + private static TraccarConfigurationManager traccarConfigurationManager; + private TraccarConfiguration traccarConfiguration; + private static final String CarbonUtilsFile = CarbonUtils.getCarbonConfigDirPath() + File.separator; + private static final String TRACCAR_CONFIG_PATH = CarbonUtilsFile + TraccarHandlerConstants.TraccarConfig.TRACCAR_CONFIG_XML_NAME; + + /** + * Retrieve an instance of {@link TraccarConfigurationManager} + * @return an instance of {@link TraccarConfigurationManager} + */ + public static TraccarConfigurationManager getInstance() { + if (traccarConfigurationManager == null) { + synchronized (TraccarConfigurationManager.class) { + if (traccarConfigurationManager == null) { + traccarConfigurationManager = new TraccarConfigurationManager(); + } + } + } + return traccarConfigurationManager; + } + + /** + * Initialize the Traccar Configuration through the provided configuration location + * @param configLocation has the path of the Traccar configuration file + * @throws DeviceManagementException throws when there are any errors during the initialization of + * Traccar configuration + */ + public synchronized void initConfig(String configLocation) throws DeviceManagementException { + try { + File traccarConfig = new File(configLocation); + Document doc = DeviceManagerUtil.convertToDocument(traccarConfig); + + //Un-marshaling Traccar configuration + JAXBContext traccarContext = JAXBContext.newInstance(TraccarConfiguration.class); + Unmarshaller unmarshaller = traccarContext.createUnmarshaller(); + this.traccarConfiguration = (TraccarConfiguration) unmarshaller.unmarshal(doc); + } catch (JAXBException e) { + String msg = "Error occurred while initializing Traccar config '" + configLocation + "'"; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + } + + /** + * Initialize the Traccar Configuration through the traccar-config.xml file in the TRACCAR_CONFIG_PATH + * @throws DeviceManagementException throws when there are any errors during the initialization of + * Traccar configuration + */ + public void initConfig() throws DeviceManagementException { + this.initConfig(TRACCAR_CONFIG_PATH); + } + + /** + * Retrieves the initialized {@link TraccarConfiguration} + * @return the initialized {@link TraccarConfiguration} + */ + public TraccarConfiguration getTraccarConfig() { + try{ + initConfig(); + }catch (Exception e){ + log.error("TraccarConfiguration:", e); + } + return traccarConfiguration; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/HttpReportingUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/HttpReportingUtil.java index 54877fdaa13..139eb00430d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/HttpReportingUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/HttpReportingUtil.java @@ -34,6 +34,11 @@ public class HttpReportingUtil { private static final Log log = LogFactory.getLog(HttpReportingUtil.class); private static final String IS_EVENT_PUBLISHING_ENABLED = "isEventPublishingEnabled"; + private static final String IS_TRACKER_ENABLED = "isTrackerEnabled"; + private static final String IS_LOCATION_PUBLISHING_ENABLED = "isLocationPublishingEnabled"; + private static final String TRACKER_SERVER_URI = "trackerServer"; + private static final String TRACKER_PASSWORD = "trackerPassword"; + private static final String TRACKER_USER = "trackerUsername"; public static String getReportingHost() { return System.getProperty(DeviceManagementConstants.Report.REPORTING_EVENT_HOST); @@ -62,4 +67,44 @@ public class HttpReportingUtil { } return false; } + + public static boolean isLocationPublishing() { + Object configuration = DeviceManagerUtil.getConfiguration(IS_LOCATION_PUBLISHING_ENABLED); + if (configuration != null) { + return Boolean.valueOf(configuration.toString()); + } + return false; + } + + public static boolean isTrackerEnabled() { + Object configuration = DeviceManagerUtil.getConfiguration(IS_TRACKER_ENABLED); + if (configuration != null) { + return Boolean.valueOf(configuration.toString()); + } + return false; + } + + public static String trackerServer() { + Object configuration = DeviceManagerUtil.getConfiguration(TRACKER_SERVER_URI); + if (configuration != null) { + return configuration.toString(); + } + return null; + } + + public static String trackerPassword() { + Object configuration = DeviceManagerUtil.getConfiguration(TRACKER_PASSWORD); + if (configuration != null) { + return configuration.toString(); + } + return null; + } + + public static String trackerUser() { + Object configuration = DeviceManagerUtil.getConfiguration(TRACKER_USER); + if (configuration != null) { + return configuration.toString(); + } + return null; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml new file mode 100644 index 00000000000..3521695b04e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/config/operation/traccar-config.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + sample + http://localhost: + + 5055 + Authorization + Basic YWRtaW46YWRtaW4= + + + + 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 fb88cd39109..005db8fb7da 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/conf/traccar-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml new file mode 100644 index 00000000000..3521695b04e --- /dev/null +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/conf/traccar-config.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + sample + http://localhost: + + 5055 + Authorization + Basic YWRtaW46YWRtaW4= + + + + 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 c03341d4785..6fa6f7c4971 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 @@ -748,3 +748,32 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING ( ); -- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- + +-- 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/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql index d967f50e637..37d7cbb3b8e 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -812,3 +812,32 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING ( ) ENGINE=InnoDB; -- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- + +-- 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-- \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/p2.inf index 178b0961b03..6779ade766f 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.basics.feature/src/main/resources/p2.inf @@ -11,3 +11,4 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/resources/email-templates);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf/traccar-config.xml,target:${installFolder}/../../conf/traccar-config.xml,overwrite:true);\