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..d3da95fa5b9 --- /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,72 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.common; + +import java.io.Serializable; + +public class TrackerDeviceInfo implements Serializable { + + private static final long serialVersionUID = 1998101712L; + + private int id; + private int traccarDeviceId; + private int deviceId; + private int tenantId; + + 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; + } +} 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..f4d2045f129 --- /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,92 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.wso2.carbon.device.mgt.common; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; + +@ApiModel(value = "TrackerGroupInfo", description = "This class carries all information related to a add groups.") +public class TrackerInfo implements Serializable { + + private static final long serialVersionUID = 1998101712L; + + @ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.", + required = true) + private int id; + private int traccarGroupId; + private int traccarDeviceId; + private int groupId; + private int tenantId; + + public TrackerInfo() { + } + + public TrackerInfo(int traccarGroupId, int groupId, int tenantId) { + this.traccarGroupId = traccarGroupId; + this.groupId = groupId; + this.tenantId = tenantId; + } + + public TrackerInfo(int traccarDeviceId, int groupId) { + this.traccarDeviceId = traccarDeviceId; + this.groupId = groupId; + } + + 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 getTraccarDeviceId() { + return traccarDeviceId; + } + + public void setTraccarDeviceId(int traccarDeviceId) { + this.traccarDeviceId = traccarDeviceId; + } +} 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..05c58604be3 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 @@ -130,6 +130,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/GroupManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GroupManagementDAOFactory.java index d4d3f535879..a848f947bf4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GroupManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/GroupManagementDAOFactory.java @@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementExcepti 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.TrackerDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.group.GenericGroupDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.group.OracleGroupDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.group.PostgreSQLGroupDAOImpl; @@ -72,6 +73,22 @@ public class GroupManagementDAOFactory { throw new IllegalStateException("Database engine has not initialized properly."); } + 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 void init(DataSourceConfig config) { dataSource = resolveDataSource(config); try { 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..1c9bbf3e93f --- /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,38 @@ +/* + * 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.dao; + +import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; + +public interface TrackerDAO { + + Boolean addTraccarDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException; + + int removeTraccarDevice(int deviceId, int tenantId) throws TrackerManagementDAOException; + + TrackerDeviceInfo getTraccarDevice(int groupId, int tenantId) throws TrackerManagementDAOException; + + Boolean addTraccarGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException; + + int removeTraccarGroup(int id) throws TrackerManagementDAOException; + + TrackerGroupInfo getTraccarGroup(int groupId, int tenantId) 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..96d81dedbf3 --- /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) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.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/impl/TrackerDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/TrackerDAOImpl.java new file mode 100644 index 00000000000..df317e282f9 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/TrackerDAOImpl.java @@ -0,0 +1,191 @@ +/* + * 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.dao.impl; + +import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +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.GroupManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class TrackerDAOImpl implements TrackerDAO { + + @Override + public Boolean addTraccarDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DM_TRACCAR_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(); + + return true; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while adding traccar device mapping", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public int removeTraccarDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + int status = -1; + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_TRACCAR_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(); + rs = stmt.getGeneratedKeys(); + if (rs.next()) { + status = 1; + } + return status; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while removing traccar device", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public TrackerDeviceInfo getTraccarDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + TrackerDeviceInfo trackerDeviceInfo = null; + try { + Connection conn = DeviceManagementDAOFactory.getConnection(); + String sql = "SELECT ID, TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID FROM DM_TRACCAR_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()) { + trackerDeviceInfo = this.loadTrackerDevice(rs); + } + return trackerDeviceInfo; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while retrieving the traccar device information ", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public Boolean addTraccarGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DM_TRACCAR_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID) VALUES(?, ?, ?)"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, traccarGroupId); + stmt.setInt(2, groupId); + stmt.setInt(3, tenantId); + stmt.execute(); + + return true; + } catch (SQLException e) { + String msg = "Error occurred while adding traccar group mapping"; + throw new TrackerManagementDAOException(msg, e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public int removeTraccarGroup(int id) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + int status = -1; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "DELETE FROM DM_TRACCAR_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) { + throw new TrackerManagementDAOException("Error occurred while removing traccar group", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public TrackerGroupInfo getTraccarGroup(int groupId, int tenantId) throws TrackerManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + TrackerGroupInfo trackerGroupInfo = null; + try { + Connection conn = GroupManagementDAOFactory.getConnection(); + String sql = "SELECT ID, TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID FROM DM_TRACCAR_GROUP_MAPPING WHERE " + + "GROUP_ID = ? AND TENANT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, groupId); + stmt.setInt(2, tenantId); + rs = stmt.executeQuery(); + if (rs.next()) { + trackerGroupInfo = this.loadTrackerGroup(rs); + } + return trackerGroupInfo; + } catch (SQLException e) { + throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); + } finally { + GroupManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + private 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")); + return trackerGroupInfo; + } + + private 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")); + return trackerDeviceInfo; + } +} 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 cde5bb1ff1a..e699d223f2f 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 @@ -389,7 +389,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { //Traccar update GPS Location try { - if (HttpReportingUtil.isLocationPublishing()) { + if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() .updateLocation(device, deviceLocation); } 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 bd7e2ebb509..022fec192aa 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 @@ -47,10 +47,30 @@ import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.HTTP; +import org.json.JSONObject; 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.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.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; 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; @@ -118,9 +138,9 @@ import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; 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.traccar.api.service.DeviceAPIClientService; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; 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; @@ -161,6 +181,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv private MetadataDAO metadataDAO; private final BillingDAO billingDAO; private final DeviceStatusDAO deviceStatusDAO; + private final TrackerDAO trackerDAO; public DeviceManagementProviderServiceImpl() { this.pluginRepository = new DeviceManagementPluginRepository(); @@ -171,6 +192,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO(); this.billingDAO = DeviceManagementDAOFactory.getBillingDAO(); this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO(); + this.trackerDAO = DeviceManagementDAOFactory.getTrackerDAO(); /* Registering a listener to retrieve events when some device management service plugin is installed after * the component is done getting initialized */ @@ -396,9 +418,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv //enroll Traccar device try { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device); + if (HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId); + } } catch (TraccarConfigurationException e) { - log.error("Error while adding a device to traccar " + e); + log.error("Error while adding a group to Traccar " + e); } //enroll Traccar device @@ -463,6 +487,19 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } deviceDAO.updateDevice(device, tenantId); enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), tenantId); + + //modify Traccar device + if (HttpReportingUtil.isTrackerEnabled()) { + try { + //trackerDAO.removeTraccarDevice(device.getId(), tenantId); + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .updateDevice(device, tenantId); + } catch (TraccarConfigurationException e) { + log.error("Error while disenrolling a device from Traccar " + e); + } + } + //modify Traccar device + DeviceManagementDAOFactory.commitTransaction(); this.removeDeviceFromCache(deviceIdentifier); } catch (DeviceManagementDAOException e) { @@ -564,13 +601,20 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv this.removeDeviceFromCache(deviceId); //disenroll Traccar device - try { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .disDevice(device.getDeviceIdentifier()); - } catch (TraccarConfigurationException e) { - log.error("Error while disenrolling a device from Traccar " + e); + if (HttpReportingUtil.isTrackerEnabled()) { + try { + TrackerDeviceInfo res = trackerDAO.getTraccarDevice(device.getId(), tenantId); + JSONObject obj = new JSONObject(res); + //Need to verify this removal + //trackerDAO.removeTraccarDevice(device.getId(), tenantId); + //Need to verify this removal + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .disEndrollDevice(obj.getInt("traccarDeviceId"), tenantId); + } catch (TraccarConfigurationException e) { + log.error("Error while disenrolling a device from Traccar " + e); + } } - //disenroll Traccar device + //procees to dis-enroll a device from traccar ends*/ } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); 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 66167f837f1..098369800b8 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 @@ -35,15 +35,16 @@ package org.wso2.carbon.device.mgt.core.service; -import com.google.gson.Gson; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; @@ -61,12 +62,14 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.GroupDAO; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; import org.wso2.carbon.device.mgt.core.event.config.GroupAssignmentEventOperationExecutor; 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.traccar.common.config.TraccarConfigurationException; 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; @@ -86,6 +89,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid private final GroupDAO groupDAO; private final DeviceDAO deviceDAO; + private final TrackerDAO trackerDAO; /** * Set groupDAO from GroupManagementDAOFactory when class instantiate. @@ -93,6 +97,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid public GroupManagementProviderServiceImpl() { this.groupDAO = GroupManagementDAOFactory.getGroupDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); + this.trackerDAO = DeviceManagementDAOFactory.getTrackerDAO(); } /** @@ -136,21 +141,29 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid //add new group in traccar try { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .addGroup(deviceGroup); + if (HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .addGroup(deviceGroup, updatedGroupID, tenantId); + } } catch (TraccarConfigurationException e) { - log.error("Error while disenrolling a device from Traccar " + e); + log.error("Error while adding a group to Traccar " + e); } //add new group in traccar } else { - //check if a group exist or not in traccar if not existing then add - /*try { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .addGroup(deviceGroup); - } catch (TraccarConfigurationException e) { - log.error("Error while disenrolling a device from Traccar " + e); - }*/ - //check if a group exist or not in traccar + // add a group if not exist in traccar starts + existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId); + int groupId = existingGroup.getGroupId(); + TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId); + if(res==null){ + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .addGroup(deviceGroup, groupId, tenantId); + } catch (TraccarConfigurationException e) { + log.error("Error while adding a existing group to Traccar " + e); + } + } + // add a group if not exist in traccar starts + throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName()); } } catch (GroupManagementDAOException e) { @@ -228,6 +241,20 @@ 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()) { + TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId); + JSONObject obj = new JSONObject(res); + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .updateGroup(deviceGroup, obj.getInt("traccarGroupId"), groupId, tenantId); + } catch (TraccarConfigurationException e) { + log.error("Error while updating the group in Traccar " + e); + } + } + //procees to update a group in traccar starts + GroupManagementDAOFactory.commitTransaction(); } else { throw new GroupNotExistException("Group with ID - '" + groupId + "' doesn't exists!"); @@ -286,6 +313,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid } } } + + //procees to delete a group from traccar starts + if (HttpReportingUtil.isTrackerEnabled()) { + TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId); + JSONObject obj = new JSONObject(res); + trackerDAO.removeTraccarGroup(obj.getInt("id")); + try { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .deleteGroup(obj.getInt("traccarGroupId"), tenantId); + } catch (TraccarConfigurationException e) { + log.error("Error while disenrolling a device from Traccar " + e); + } + } + //procees to delete a group from traccar ends + if (isDeleteChildren) { groupIdsToDelete.add(groupId); groupDAO.deleteGroupsMapping(groupIdsToDelete, tenantId); @@ -302,14 +344,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid if (log.isDebugEnabled()) { log.debug("DeviceGroup " + deviceGroup.getName() + " removed."); } - //add new group in traccar - try { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .deleteGroup(deviceGroup); - } catch (TraccarConfigurationException e) { - log.error("Error while disenrolling a device from Traccar " + e); - } - //add new group in traccar + 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 index e187ddf7df8..fbb4f320c11 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java @@ -46,15 +46,23 @@ public interface DeviceAPIClientService { * @param device to be added * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration */ - void addDevice(Device device) throws TraccarConfigurationException; + void addDevice(Device device, int tenantId) throws TraccarConfigurationException; + + /** + * Create device Traccar configuration records + * + * @param device to modify + * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration + */ + void updateDevice(Device device, int tenantId) throws TraccarConfigurationException; /** * Delete a device Traccar configuration records * - * @param deviceIdentifier to be delete a device + * @param deviceId to be delete a device * @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration */ - void disDevice(String deviceIdentifier) throws TraccarConfigurationException; + void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException; /** * Delete a device Traccar configuration records @@ -62,7 +70,7 @@ public interface DeviceAPIClientService { * @param group to be add a group * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration */ - void addGroup(DeviceGroup group) throws TraccarConfigurationException; + void addGroup(DeviceGroup group, int groupID, int tenantId) throws TraccarConfigurationException; /** * Delete a device Traccar configuration records @@ -70,5 +78,14 @@ public interface DeviceAPIClientService { * @param group to be add a group * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration */ - void deleteGroup(DeviceGroup group) throws TraccarConfigurationException; + void updateGroup(DeviceGroup group, int traccarGroupId, int groupID, int tenantId) throws TraccarConfigurationException; + + /** + * Delete a device Traccar configuration records + * + * @param traccarGroupId to delete a group + * @param tenantId to delete a group + * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration + */ + void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java index 548e585a0bb..db013bf6348 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/addons/TrackerClient.java @@ -27,9 +27,13 @@ import okhttp3.RequestBody; import okhttp3.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarClient; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; @@ -42,17 +46,10 @@ import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationM import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.ENDPOINT; -import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION; -import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION_KEY; -import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.DEFAULT_PORT; -import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.LOCATION_UPDATE_PORT; - public class TrackerClient implements TraccarClient { private static final Log log = LogFactory.getLog(TrackerClient.class); private static final int THREAD_POOL_SIZE = 50; @@ -60,11 +57,14 @@ public class TrackerClient implements TraccarClient { private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); final TraccarGateway traccarGateway = getTraccarGateway(); - final String endpoint = traccarGateway.getPropertyByName(ENDPOINT).getValue(); - final String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); - final String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); - final String defaultPort = traccarGateway.getPropertyByName(DEFAULT_PORT).getValue(); - final String locationUpdatePort = traccarGateway.getPropertyByName(LOCATION_UPDATE_PORT).getValue(); + 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(); + + private final TrackerDAO trackerGroupDAO; + private final TrackerDAO trackerDeviceDAO; public TrackerClient() { client = new OkHttpClient.Builder() @@ -73,39 +73,90 @@ public class TrackerClient implements TraccarClient { .readTimeout(45, TimeUnit.SECONDS) .connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS)) .build(); + this.trackerDeviceDAO = GroupManagementDAOFactory.getTrackerDAO(); + this.trackerGroupDAO = DeviceManagementDAOFactory.getTrackerDAO(); } private class TrackerExecutor implements Runnable { + final int id; + final int tenantId; final JSONObject payload; final String context; final String publisherUrl; private final String method; + private final String type; - private TrackerExecutor(String publisherUrl, String context, JSONObject payload, String method) { + private TrackerExecutor(int id, int tenantId, String publisherUrl, String context, JSONObject payload, + String method, String type) { + this.id = id; + this.tenantId = tenantId; this.payload = payload; this.context = context; this.publisherUrl = publisherUrl; this.method = method; + this.type = type; } public void run() { RequestBody requestBody; Request.Builder builder = new Request.Builder(); Request request; + Response response; - if(method=="post"){ + if(method==TraccarHandlerConstants.Methods.POST){ requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.post(requestBody); - }else if(method=="delete"){ + }if(method==TraccarHandlerConstants.Methods.PUT){ + requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); + builder = builder.put(requestBody); + }else if(method==TraccarHandlerConstants.Methods.DELETE){ builder = builder.delete(); } - request = builder.url(publisherUrl + context) - .addHeader(authorization, authorizationKey) - .build(); + request = builder.url(publisherUrl + context).addHeader(authorization, authorizationKey).build(); try { - client.newCall(request).execute(); + response = client.newCall(request).execute(); + + if(method==TraccarHandlerConstants.Methods.POST){ + String result = response.body().string(); + JSONObject obj = new JSONObject(result); + int traccarId = obj.getInt("id"); + + if(type==TraccarHandlerConstants.Types.DEVICE){ + try { + DeviceManagementDAOFactory.beginTransaction(); + trackerDeviceDAO.addTraccarDevice(traccarId, id, tenantId); + DeviceManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + DeviceManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping traccarDeviceId with deviceId ."; + log.error(msg, e); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + }else if(type==TraccarHandlerConstants.Types.GROUP){ + try { + GroupManagementDAOFactory.beginTransaction(); + trackerGroupDAO.addTraccarGroup(traccarId, id, tenantId); + GroupManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + GroupManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + GroupManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping traccarGroupId with groupId ."; + log.error(msg, e); + } finally { + GroupManagementDAOFactory.closeConnection(); + } + } + } if (log.isDebugEnabled()) { log.debug("Successfully the request is proceed and communicated with Traccar"); } @@ -122,32 +173,58 @@ public class TrackerClient implements TraccarClient { * Model, Contact, Category, fenceIds * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void addDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { + public void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException { try{ - 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()); + JSONObject payload = payload(deviceInfo); String context = defaultPort+"/api/devices"; - Runnable trackerExecutor = new TrackerExecutor(endpoint, context, payload, "post"); + Runnable trackerExecutor = + new TrackerExecutor( deviceInfo.getId(),tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.DEVICE); executor.execute(trackerExecutor); - log.info("Device successfully enorolled on traccar"); - }catch (Exception e){ + }catch (Exception e){ String msg="Could not enroll traccar device"; log.error(msg, e); throw new TraccarConfigurationException(msg, e); - } + } + } + + /** + * Add Traccar Device operation. + * @param deviceInfo with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId + * Model, Contact, Category, fenceIds + * @throws TraccarConfigurationException Failed while add Traccar Device the operation + */ + public void updateDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException { + try{ + JSONObject payload = payload(deviceInfo); + String context = defaultPort+"/api/devices"; + Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.DEVICE); + executor.execute(trackerExecutor); + }catch (Exception e){ + String msg="Could not enroll traccar device"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } + } + + private JSONObject payload(TraccarDevice deviceInfo){ + JSONObject payload = new JSONObject(); + payload.put("name", deviceInfo.getDeviceName()); + payload.put("uniqueId", deviceInfo.getUniqueId()); + payload.put("status", deviceInfo.getStatus()); + payload.put("disabled", deviceInfo.getDisabled()); + payload.put("lastUpdate", deviceInfo.getLastUpdate()); + payload.put("positionId", deviceInfo.getPositionId()); + payload.put("groupId", deviceInfo.getGroupId()); + payload.put("phone", deviceInfo.getPhone()); + payload.put("model", deviceInfo.getModel()); + payload.put("contact", deviceInfo.getContact()); + payload.put("category", deviceInfo.getCategory()); + List geoFenceIds = new ArrayList<>(); + payload.put("geofenceIds", geoFenceIds); + payload.put("attributes", new JSONObject()); + return payload; } /** @@ -159,7 +236,8 @@ public class TrackerClient implements TraccarClient { String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ "&speed="+deviceInfo.getSpeed()+"&ignition=true"; - Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); + Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, + TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); executor.execute(trackerExecutor); log.info("Device GPS location added on traccar"); }catch (Exception e){ @@ -169,59 +247,22 @@ public class TrackerClient implements TraccarClient { } } - /** - * Add Device GPS Location operation. - * @param deviceId - * @return device info - * @throws TraccarConfigurationException Failed while add Traccar Device location operation - */ - @Override - public String getDeviceByDeviceIdentifier(String deviceId) throws TraccarConfigurationException { - try { - String context = defaultPort+"/api/devices?uniqueId="+ deviceId; - Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); - executor.execute(trackerExecutor); - Request request = new Request.Builder() - .url(endpoint+context) - .addHeader(authorization, authorizationKey) - .build(); - Response response = client.newCall(request).execute(); - String result = response.body().string(); - log.info("Device info found"); - return result; - } catch (IOException e) { - String msg="Could not find device information"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } - } - /** * Dis-enroll a Device operation. - * @param deviceInfo identified via deviceIdentifier + * @param traccarDeviceId identified via deviceIdentifier * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation */ - public void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { + public void disEndrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException { try{ - String result = getDeviceByDeviceIdentifier(deviceInfo.getDeviceIdentifier()); - String jsonData ="{"+ "\"geodata\": "+ result+ "}"; - - JSONObject obj = new JSONObject(jsonData); - JSONArray geodata = obj.getJSONArray("geodata"); - JSONObject jsonResponse = geodata.getJSONObject(0); - - String context = defaultPort+"/api/devices/"+jsonResponse.getInt("id"); - Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "delete"); + String context = defaultPort+"/api/devices/"+traccarDeviceId; + Runnable trackerExecutor = new TrackerExecutor(traccarDeviceId, tenantId, endpoint, context, null, + TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE); executor.execute(trackerExecutor); log.info("Device successfully dis-enrolled"); }catch (JSONException e){ String msg = "Could not find the device information to dis-enroll the device"; log.error(msg, e); throw new TraccarConfigurationException(msg); - }catch (TraccarConfigurationException ex){ - String msg = "Could not find the device information to dis-enroll the device"; - log.error(msg, ex); - throw new TraccarConfigurationException(msg, ex); } } @@ -230,14 +271,15 @@ public class TrackerClient implements TraccarClient { * @param groupInfo with groupName * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void addGroup(TraccarGroups groupInfo) throws TraccarConfigurationException { + public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException { try{ JSONObject payload = new JSONObject(); payload.put("name", groupInfo.getName()); payload.put("attributes", new JSONObject()); String context = defaultPort+"/api/groups"; - Runnable trackerExecutor = new TrackerExecutor(endpoint, context, payload, "post"); + Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP); executor.execute(trackerExecutor); log.info("Group successfully added on traccar"); }catch (Exception e){ @@ -248,25 +290,24 @@ public class TrackerClient implements TraccarClient { } /** - * Add Device GPS Location operation. - * @return all groups - * @throws TraccarConfigurationException Failed while add Traccar Device location operation + * Add Traccar Device operation. + * @param groupInfo with groupName + * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - @Override - public String getAllGroups() throws TraccarConfigurationException { - try { - String context = defaultPort+"/api/groups?all=true"; - Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); + public void updateGroup(TraccarGroups groupInfo, int traccarGroupId, int groupId, int tenantId) throws TraccarConfigurationException { + try{ + JSONObject payload = new JSONObject(); + payload.put("id", traccarGroupId); + payload.put("name", groupInfo.getName()); + payload.put("attributes", new JSONObject()); + + String context = defaultPort+"/api/groups/"+traccarGroupId; + Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP); executor.execute(trackerExecutor); - Request request = new Request.Builder() - .url(endpoint+context) - .addHeader(authorization, authorizationKey) - .build(); - Response response = client.newCall(request).execute(); - String result = response.body().string(); - return result; - } catch (IOException e) { - String msg="Could not find device information"; + log.info("Group successfully updated on traccar"); + }catch (Exception e){ + String msg="Could not update the traccar group"; log.error(msg, e); throw new TraccarConfigurationException(msg, e); } @@ -274,37 +315,19 @@ public class TrackerClient implements TraccarClient { /** * Add Traccar Device operation. - * @param groupInfo with groupName + * @param traccarGroupId * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void deleteGroup(TraccarGroups groupInfo) throws TraccarConfigurationException { + public void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException { try{ - String result = getAllGroups(); - String jsonData ="{"+ "\"groupdata\": "+ result+ "}"; - - JSONObject obj = new JSONObject(jsonData); - JSONArray geodata = obj.getJSONArray("groupdata"); - - for(int i=0; i