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 index f4d2045f12..6caea83c52 100644 --- 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 @@ -18,38 +18,26 @@ */ 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 { +public class TrackerGroupInfo 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 TrackerGroupInfo() { } - public TrackerInfo(int traccarGroupId, int groupId, int tenantId) { + public TrackerGroupInfo(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; } @@ -81,12 +69,4 @@ public class TrackerInfo implements Serializable { 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.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/TrackerAlreadyExistException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/TrackerAlreadyExistException.java new file mode 100644 index 0000000000..c120f78ea9 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/TrackerAlreadyExistException.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.common.group.mgt; + +/** + * This class represents a custom exception specified for group management + */ +public class TrackerAlreadyExistException extends Exception { + + private static final long serialVersionUID = -312678379574816874L; + 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; + } + +} \ No newline at end of file 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 a848f947bf..d4d3f53587 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,7 +26,6 @@ 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; @@ -73,22 +72,6 @@ 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/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 0000000000..912aca3ec5 --- /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) 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.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.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/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 index df317e282f..11f5284af8 100644 --- 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 @@ -20,12 +20,10 @@ 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.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.GroupManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.dao.util.TrackerManagementDAOUtil; import java.sql.Connection; import java.sql.PreparedStatement; @@ -38,8 +36,8 @@ public class TrackerDAOImpl implements TrackerDAO { 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(?, ?, ?)"; + 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); @@ -50,7 +48,7 @@ public class TrackerDAOImpl implements TrackerDAO { } catch (SQLException e) { throw new TrackerManagementDAOException("Error occurred while adding traccar device mapping", e); } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); + TrackerManagementDAOUtil.cleanupResources(stmt, null); } } @@ -60,8 +58,8 @@ public class TrackerDAOImpl implements TrackerDAO { 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 = ? "; + 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); @@ -74,7 +72,7 @@ public class TrackerDAOImpl implements TrackerDAO { } catch (SQLException e) { throw new TrackerManagementDAOException("Error occurred while removing traccar device", e); } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, null); + TrackerManagementDAOUtil.cleanupResources(stmt, null); } } @@ -84,8 +82,8 @@ public class TrackerDAOImpl implements TrackerDAO { 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 " + + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT ID, TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID 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); @@ -98,7 +96,7 @@ public class TrackerDAOImpl implements TrackerDAO { } catch (SQLException e) { throw new TrackerManagementDAOException("Error occurred while retrieving the traccar device information ", e); } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); + TrackerManagementDAOUtil.cleanupResources(stmt, rs); } } @@ -107,8 +105,8 @@ public class TrackerDAOImpl implements TrackerDAO { PreparedStatement stmt = null; try { - Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "INSERT INTO DM_TRACCAR_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID) VALUES(?, ?, ?)"; + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "INSERT INTO DM_EXT_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID) VALUES(?, ?, ?)"; stmt = conn.prepareStatement(sql); stmt.setInt(1, traccarGroupId); stmt.setInt(2, groupId); @@ -120,7 +118,7 @@ public class TrackerDAOImpl implements TrackerDAO { String msg = "Error occurred while adding traccar group mapping"; throw new TrackerManagementDAOException(msg, e); } finally { - GroupManagementDAOUtil.cleanupResources(stmt, null); + TrackerManagementDAOUtil.cleanupResources(stmt, null); } } @@ -130,8 +128,8 @@ public class TrackerDAOImpl implements TrackerDAO { ResultSet rs = null; int status = -1; try { - Connection conn = GroupManagementDAOFactory.getConnection(); - String sql = "DELETE FROM DM_TRACCAR_GROUP_MAPPING WHERE ID = ? "; + 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(); @@ -143,7 +141,7 @@ public class TrackerDAOImpl implements TrackerDAO { } catch (SQLException e) { throw new TrackerManagementDAOException("Error occurred while removing traccar group", e); } finally { - GroupManagementDAOUtil.cleanupResources(stmt, null); + TrackerManagementDAOUtil.cleanupResources(stmt, null); } } @@ -153,8 +151,8 @@ public class TrackerDAOImpl implements TrackerDAO { 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 " + + Connection conn = TrackerManagementDAOFactory.getConnection(); + String sql = "SELECT ID, TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID FROM DM_EXT_GROUP_MAPPING WHERE " + "GROUP_ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, groupId); @@ -167,7 +165,7 @@ public class TrackerDAOImpl implements TrackerDAO { } catch (SQLException e) { throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); } finally { - GroupManagementDAOUtil.cleanupResources(stmt, rs); + 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/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 0000000000..7aab01a40a --- /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,96 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + * Copyright (c) 2021, Entgra (pvt) Ltd. (https://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 javax.naming.InitialContext; +import javax.sql.DataSource; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Hashtable; + +/** + * 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) { + throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); + } + } +} 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 e699d223f2..50b665f441 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 @@ -43,7 +43,6 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDA import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.report.mgt.Constants; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; -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.UserStoreException; @@ -388,13 +387,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager { } //Traccar update GPS Location - try { - if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .updateLocation(device, deviceLocation); - } - } catch (TraccarConfigurationException e) { - log.error("Error on Traccar while adding GEO Location" + e); + if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId()); } //Traccar update GPS Location 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 fec7cbcbf3..fad8324919 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; @@ -192,6 +193,7 @@ public class DeviceManagementServiceComponent { DeviceManagementDAOFactory.init(dsConfig); GroupManagementDAOFactory.init(dsConfig); + TrackerManagementDAOFactory.init(dsConfig); NotificationManagementDAOFactory.init(dsConfig); OperationManagementDAOFactory.init(dsConfig); MetadataManagementDAOFactory.init(dsConfig); 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 022fec192a..7a62186377 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,7 +47,6 @@ 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; @@ -69,8 +68,6 @@ 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; @@ -138,7 +135,6 @@ 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.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; @@ -181,7 +177,6 @@ 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(); @@ -192,7 +187,6 @@ 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 */ @@ -417,12 +411,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } //enroll Traccar device - try { - if (HttpReportingUtil.isTrackerEnabled()) { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId); - } - } catch (TraccarConfigurationException e) { - log.error("Error while adding a group to Traccar " + e); + if (HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId); } //enroll Traccar device @@ -488,18 +478,6 @@ 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) { @@ -600,21 +578,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementDAOFactory.commitTransaction(); this.removeDeviceFromCache(deviceId); - //disenroll Traccar device + //procees to dis-enroll a device from traccar starts 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); - } + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .disEndrollDevice(device.getId(), tenantId); } - //procees to dis-enroll a device from traccar ends*/ + //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 098369800b..369b9d31f3 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 @@ -38,7 +38,6 @@ package org.wso2.carbon.device.mgt.core.service; 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; @@ -56,6 +55,7 @@ import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException; import org.wso2.carbon.device.mgt.common.group.mgt.RoleDoesNotExistException; +import org.wso2.carbon.device.mgt.common.group.mgt.TrackerAlreadyExistException; 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; @@ -63,6 +63,7 @@ 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.dao.TrackerManagementDAOException; 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; @@ -89,7 +90,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid private final GroupDAO groupDAO; private final DeviceDAO deviceDAO; - private final TrackerDAO trackerDAO; /** * Set groupDAO from GroupManagementDAOFactory when class instantiate. @@ -97,7 +97,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid public GroupManagementProviderServiceImpl() { this.groupDAO = GroupManagementDAOFactory.getGroupDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); - this.trackerDAO = DeviceManagementDAOFactory.getTrackerDAO(); } /** @@ -140,27 +139,18 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid GroupManagementDAOFactory.commitTransaction(); //add new group in traccar - try { - if (HttpReportingUtil.isTrackerEnabled()) { - DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() - .addGroup(deviceGroup, updatedGroupID, tenantId); - } - } catch (TraccarConfigurationException e) { - log.error("Error while adding a group to Traccar " + e); + if (HttpReportingUtil.isTrackerEnabled()) { + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .addGroup(deviceGroup, updatedGroupID, tenantId); } //add new group in traccar } else { // 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); - } + 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 @@ -244,14 +234,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid //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); - } + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .updateGroup(deviceGroup, groupId, tenantId); } //procees to update a group in traccar starts @@ -316,15 +300,8 @@ 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); - } + DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() + .deleteGroup(groupId, tenantId); } //procees to delete a group from traccar ends diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/DeviceAPIClientService.java index fbb4f320c1..99af81e5a9 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 @@ -20,15 +20,10 @@ 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.DeviceIdentifier; 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.core.traccar.common.beans.TraccarGroups; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; -import java.io.IOException; - - public interface DeviceAPIClientService { /** @@ -38,7 +33,7 @@ public interface DeviceAPIClientService { * @param deviceLocation to be added to update location of the device * @throws TraccarConfigurationException errors thrown while inserting location of a device traccar configuration */ - void updateLocation(Device device, DeviceLocation deviceLocation) throws TraccarConfigurationException; + void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId); /** * Create device Traccar configuration records @@ -46,7 +41,7 @@ public interface DeviceAPIClientService { * @param device to be added * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration */ - void addDevice(Device device, int tenantId) throws TraccarConfigurationException; + void addDevice(Device device, int tenantId); /** * Create device Traccar configuration records @@ -54,7 +49,7 @@ public interface DeviceAPIClientService { * @param device to modify * @throws TraccarConfigurationException errors thrown while creating a device traccar configuration */ - void updateDevice(Device device, int tenantId) throws TraccarConfigurationException; + void updateDevice(Device device, int tenantId); /** * Delete a device Traccar configuration records @@ -62,7 +57,7 @@ public interface DeviceAPIClientService { * @param deviceId to be delete a device * @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration */ - void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException; + void disEndrollDevice(int deviceId, int tenantId); /** * Delete a device Traccar configuration records @@ -70,22 +65,22 @@ public interface DeviceAPIClientService { * @param group to be add a group * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration */ - void addGroup(DeviceGroup group, int groupID, int tenantId) throws TraccarConfigurationException; + void addGroup(DeviceGroup group, int groupID, int tenantId); /** * Delete a device Traccar configuration records * - * @param group to be add a group + * @param group to be update the group * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration */ - void updateGroup(DeviceGroup group, int traccarGroupId, int groupID, int tenantId) throws TraccarConfigurationException; + void updateGroup(DeviceGroup group, int groupID, int tenantId); /** * Delete a device Traccar configuration records * - * @param traccarGroupId to delete a group + * @param groupId 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; + void deleteGroup(int groupId, int tenantId); } 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 db013bf634..414d1ebc57 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 @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.traccar.api.service.addons; +import com.google.gson.Gson; import okhttp3.ConnectionPool; import okhttp3.MediaType; import okhttp3.OkHttpClient; @@ -29,11 +30,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONException; import org.json.JSONObject; +import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; +import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; 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.common.group.mgt.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.common.TraccarClient; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; @@ -44,7 +47,9 @@ import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarGateway; import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationManager; import java.io.IOException; +import java.sql.SQLException; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -63,8 +68,7 @@ public class TrackerClient implements TraccarClient { 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; + private final TrackerDAO trackerDAO; public TrackerClient() { client = new OkHttpClient.Builder() @@ -73,12 +77,11 @@ 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(); + this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO(); } private class TrackerExecutor implements Runnable { - final int id; + final int deviceId; final int tenantId; final JSONObject payload; final String context; @@ -86,9 +89,9 @@ public class TrackerClient implements TraccarClient { private final String method; private final String type; - private TrackerExecutor(int id, int tenantId, String publisherUrl, String context, JSONObject payload, + private TrackerExecutor(int deviceId, int tenantId, String publisherUrl, String context, JSONObject payload, String method, String type) { - this.id = id; + this.deviceId = deviceId; this.tenantId = tenantId; this.payload = payload; this.context = context; @@ -106,7 +109,7 @@ public class TrackerClient implements TraccarClient { if(method==TraccarHandlerConstants.Methods.POST){ requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); builder = builder.post(requestBody); - }if(method==TraccarHandlerConstants.Methods.PUT){ + }else 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){ @@ -117,43 +120,33 @@ public class TrackerClient implements TraccarClient { try { 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){ + JSONObject obj = new JSONObject(response.body().string()); + if (obj != null){ + int traccarId = obj.getInt("id"); try { - DeviceManagementDAOFactory.beginTransaction(); - trackerDeviceDAO.addTraccarDevice(traccarId, id, tenantId); - DeviceManagementDAOFactory.commitTransaction(); + TrackerManagementDAOFactory.beginTransaction(); + if(type==TraccarHandlerConstants.Types.DEVICE){ + trackerDAO.addTraccarDevice(traccarId, deviceId, tenantId); + }else if(type==TraccarHandlerConstants.Types.GROUP){ + trackerDAO.addTraccarGroup(traccarId, deviceId, tenantId); + } + TrackerManagementDAOFactory.commitTransaction(); } catch (TransactionManagementException e) { - DeviceManagementDAOFactory.rollbackTransaction(); + TrackerManagementDAOFactory.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 ."; + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = null; + if(type==TraccarHandlerConstants.Types.DEVICE){ + msg = "Error occurred while mapping with deviceId ."; + }else if(type==TraccarHandlerConstants.Types.GROUP){ + msg = "Error occurred while mapping with groupId ."; + } 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(); + TrackerManagementDAOFactory.closeConnection(); } } } @@ -162,7 +155,6 @@ public class TrackerClient implements TraccarClient { } } catch (IOException e) { log.error("Error occurred", e); - } } } @@ -173,19 +165,31 @@ public class TrackerClient implements TraccarClient { * Model, Contact, Category, fenceIds * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void addDevice(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.POST, 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); + public void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { + TrackerDeviceInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTraccarDevice(deviceInfo.getId(), tenantId); + if(res!=null){ + throw new TrackerAlreadyExistException("The device already exit"); + } + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); } + + JSONObject payload = payload(deviceInfo); + String context = defaultPort+"/api/devices"; + Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.DEVICE); + executor.execute(trackerExecutor); } /** @@ -194,17 +198,45 @@ public class TrackerClient implements TraccarClient { * Model, Contact, Category, fenceIds * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void updateDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException { - try{ + public void updateDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { + TrackerDeviceInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTraccarDevice(deviceInfo.getId(), tenantId); + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); + } + + if(res==null){ + try { + TrackerClient trackerClient = new TrackerClient(); + TraccarDevice device = deviceInfo; + String lastUpdatedTime = String.valueOf((new Date().getTime())); + device.setLastUpdate(lastUpdatedTime); + trackerClient.addDevice(deviceInfo, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The group already exist"; + log.error(msg, e); + throw new TrackerAlreadyExistException(msg, e); + } + }else{ 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); } } @@ -231,38 +263,78 @@ public class TrackerClient implements TraccarClient { * Add Device GPS Location operation. * @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition */ - public void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException { - try{ - String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ - "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ - "&speed="+deviceInfo.getSpeed()+"&ignition=true"; - Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, - TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); - executor.execute(trackerExecutor); - log.info("Device GPS location added on traccar"); - }catch (Exception e){ - String msg="Could not add GPS location"; - log.error(msg, e); - throw new TraccarConfigurationException(msg, e); - } + public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { + TrackerDeviceInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTraccarDevice(device.getId(), tenantId); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + String msg="Could not update the traccar group"; + log.error(msg, e); + } finally{ + TrackerManagementDAOFactory.closeConnection(); + } + + if (res == null){ + try { + TrackerClient trackerClient = new TrackerClient(); + trackerClient.addDevice(device, tenantId); + log.info("===================================="); + log.info(device); + log.info(trackerClient); + log.info(tenantId); + log.info("===================================="); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The device already exist"; + log.error(msg, e); + throw new TrackerAlreadyExistException(msg, e); + } + }else{ + String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"×tamp="+deviceInfo.getTimestamp()+ + "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ + "&speed="+deviceInfo.getSpeed()+"&ignition=true"; + Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, + TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); + executor.execute(trackerExecutor); + log.info("Device GPS location added on traccar"); + } + } /** * Dis-enroll a Device operation. - * @param traccarDeviceId identified via deviceIdentifier + * @param deviceId identified via deviceIdentifier * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation */ - public void disEndrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException { - try{ - String context = defaultPort+"/api/devices/"+traccarDeviceId; - Runnable trackerExecutor = new TrackerExecutor(traccarDeviceId, tenantId, endpoint, context, null, + public void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { + try { + TrackerManagementDAOFactory.beginTransaction(); + TrackerDeviceInfo res = trackerDAO.getTraccarDevice(deviceId, tenantId); + JSONObject obj = new JSONObject(res); + trackerDAO.removeTraccarDevice(deviceId, tenantId); + + String context = defaultPort+"/api/devices/"+obj.getInt("traccarDeviceId"); + Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarDeviceId"), tenantId, endpoint, context, null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE); executor.execute(trackerExecutor); - log.info("Device successfully dis-enrolled"); - }catch (JSONException e){ - String msg = "Could not find the device information to dis-enroll the device"; + TrackerManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection"; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with deviceId"; log.error(msg, e); - throw new TraccarConfigurationException(msg); + } finally { + TrackerManagementDAOFactory.closeConnection(); } } @@ -271,22 +343,34 @@ public class TrackerClient implements TraccarClient { * @param groupInfo with groupName * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException { - try{ - JSONObject payload = new JSONObject(); - payload.put("name", groupInfo.getName()); - payload.put("attributes", new JSONObject()); + public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { - String context = defaultPort+"/api/groups"; - 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){ - String msg="Could not add a traccar group"; + try { + TrackerManagementDAOFactory.openConnection(); + TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId); + if(res!=null){ + throw new TrackerAlreadyExistException("The group already exit"); + } + } catch (TrackerManagementDAOException e) { + String msg = "Error occurred while mapping with deviceId ."; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; log.error(msg, e); throw new TraccarConfigurationException(msg, e); + } finally { + TrackerManagementDAOFactory.closeConnection(); } + + JSONObject payload = new JSONObject(); + payload.put("name", groupInfo.getName()); + payload.put("attributes", new JSONObject()); + + String context = defaultPort+"/api/groups"; + Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, + TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP); + executor.execute(trackerExecutor); } /** @@ -294,45 +378,80 @@ public class TrackerClient implements TraccarClient { * @param groupInfo with groupName * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void updateGroup(TraccarGroups groupInfo, int traccarGroupId, int groupId, int tenantId) throws TraccarConfigurationException { - try{ + public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException { + TrackerGroupInfo res = null; + try { + TrackerManagementDAOFactory.openConnection(); + res = trackerDAO.getTraccarGroup(groupId, tenantId); + } catch (SQLException e) { + String msg = "Error occurred establishing the DB connection ."; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + String msg="Could not update the traccar group"; + log.error(msg, e); + } finally{ + TrackerManagementDAOFactory.closeConnection(); + } + + if (res == null){ + try { + TrackerClient trackerClient = new TrackerClient(); + trackerClient.addGroup(groupInfo, groupId, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + throw new TraccarConfigurationException(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The group already exist"; + log.error(msg, e); + throw new TrackerAlreadyExistException(msg, e); + } + }else{ + JSONObject obj = new JSONObject(res); JSONObject payload = new JSONObject(); - payload.put("id", traccarGroupId); + payload.put("id", obj.getInt("traccarGroupId")); payload.put("name", groupInfo.getName()); payload.put("attributes", new JSONObject()); - String context = defaultPort+"/api/groups/"+traccarGroupId; + String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP); executor.execute(trackerExecutor); - 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); } } /** * Add Traccar Device operation. - * @param traccarGroupId + * @param groupId * @throws TraccarConfigurationException Failed while add Traccar Device the operation */ - public void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException { - try{ - String context = defaultPort+"/api/groups/"+traccarGroupId; - Runnable trackerExecutor = new TrackerExecutor(traccarGroupId, tenantId, endpoint, context, + public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException { + try { + TrackerManagementDAOFactory.beginTransaction(); + TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId); + JSONObject obj = new JSONObject(res); + trackerDAO.removeTraccarGroup(obj.getInt("id")); + + String context = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId"); + Runnable trackerExecutor = new TrackerExecutor(obj.getInt("traccarGroupId"), tenantId, endpoint, context, null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.GROUP); executor.execute(trackerExecutor); - }catch (JSONException e){ - String msg = "Could not find the device information to dis-enroll the device"; + TrackerManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred establishing the DB connection"; + log.error(msg, e); + } catch (TrackerManagementDAOException e) { + TrackerManagementDAOFactory.rollbackTransaction(); + String msg = "Error occurred while mapping with groupId"; log.error(msg, e); - throw new TraccarConfigurationException(msg); + } finally { + TrackerManagementDAOFactory.closeConnection(); } } private TraccarGateway getTraccarGateway(){ return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway( - TraccarHandlerConstants.GATEWAY_NAME); + TraccarHandlerConstants.TraccarConfig.GATEWAY_NAME); } } 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/TraccarAPIClientServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java index e5a59467e8..08b9b85eed 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/api/service/impl/TraccarAPIClientServiceImpl.java @@ -19,9 +19,12 @@ 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.wso2.carbon.device.mgt.common.Device; 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.group.mgt.TrackerAlreadyExistException; import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TrackerClient; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; @@ -33,53 +36,110 @@ import java.util.Date; public class TraccarAPIClientServiceImpl implements DeviceAPIClientService { - public void addDevice(Device device, int tenantId) throws TraccarConfigurationException { + private static final Log log = LogFactory.getLog(TraccarAPIClientServiceImpl.class); + + public void addDevice(Device device, int tenantId) { TrackerClient client = new TrackerClient(); String lastUpdatedTime = String.valueOf((new Date().getTime())); - TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(), + TraccarDevice traccarDevice = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(), "online", "false", lastUpdatedTime, "", "", "", "", "", ""); - client.addDevice(traccarDeviceInfo, tenantId); + try { + client.addDevice(traccarDevice, tenantId); + } catch (TraccarConfigurationException 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 updateDevice(Device device, int tenantId) throws TraccarConfigurationException { + public void updateDevice(Device device, int tenantId) { TrackerClient client = new TrackerClient(); String lastUpdatedTime = String.valueOf((new Date().getTime())); TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(), "online", "false", lastUpdatedTime, "", "", "", "", "", ""); - client.updateDevice(traccarDeviceInfo, tenantId); + try { + client.updateDevice(traccarDeviceInfo, tenantId); + } catch (TraccarConfigurationException 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) throws TraccarConfigurationException { + public void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId) { TrackerClient client = new TrackerClient(); TraccarPosition traccarPosition = new TraccarPosition(device.getDeviceIdentifier(), deviceLocation.getUpdatedTime().getTime(), deviceLocation.getLatitude(), deviceLocation.getLongitude(), deviceLocation.getBearing(), deviceLocation.getSpeed()); - client.updateLocation(traccarPosition); + + 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 (TraccarConfigurationException 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 disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { + public void disEndrollDevice(int deviceId, int tenantId) { TrackerClient client = new TrackerClient(); - client.disEndrollDevice(deviceId, tenantId); + try { + client.disEndrollDevice(deviceId, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with deviceId"; + log.error(msg, e); + } } - public void addGroup(DeviceGroup group, int groupId, int tenantId) throws TraccarConfigurationException { + public void addGroup(DeviceGroup group, int groupId, int tenantId) { TrackerClient client = new TrackerClient(); TraccarGroups traccarGroups = new TraccarGroups(group.getName()); - client.addGroup(traccarGroups, groupId, tenantId); + try { + client.addGroup(traccarGroups, groupId, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The group already exist"; + log.error(msg, e); + } } - public void updateGroup(DeviceGroup group, int traccarGroupId, int groupId, int tenantId) throws TraccarConfigurationException { + public void updateGroup(DeviceGroup group, int groupId, int tenantId) { TrackerClient client = new TrackerClient(); TraccarGroups traccarGroups = new TraccarGroups(group.getName()); - client.updateGroup(traccarGroups, traccarGroupId, groupId, tenantId); + try { + client.updateGroup(traccarGroups, groupId, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + } catch (TrackerAlreadyExistException e) { + String msg = "The group already exist"; + log.error(msg, e); + } } - public void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException { + public void deleteGroup(int groupId, int tenantId) { TrackerClient client = new TrackerClient(); - client.deleteGroup(traccarGroupId, tenantId); + try { + client.deleteGroup(groupId, tenantId); + } catch (TraccarConfigurationException e) { + String msg = "Error occurred while mapping with groupId"; + log.error(msg, e); + } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java index e1ae84351b..cd6cff23c5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/traccar/common/TraccarClient.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.traccar.common; +import org.wso2.carbon.device.mgt.common.group.mgt.TrackerAlreadyExistException; 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; @@ -26,16 +27,22 @@ import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfiguratio public interface TraccarClient { - void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException; + void addDevice(TraccarDevice deviceInfo, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException; - void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException; + void updateDevice(TraccarDevice deviceInfo, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException; + + void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException; void disEndrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException; - void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException; + void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws + TraccarConfigurationException, TrackerAlreadyExistException; - void updateGroup(TraccarGroups groupInfo, int traccarGroupId, int groupId, int tenantId) throws TraccarConfigurationException; + void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) + throws TraccarConfigurationException, TrackerAlreadyExistException; 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/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 index 0aab658d47..d11024936e 100644 --- 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 @@ -20,13 +20,16 @@ package org.wso2.carbon.device.mgt.core.traccar.common; public class TraccarHandlerConstants { - 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"; + + 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"; + } public static class Methods { public static final String POST = "POST"; @@ -40,14 +43,4 @@ public class TraccarHandlerConstants { public static final String GROUP = "GROUP"; } - - 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"; - } } 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 index cafc848373..163ae4f3a5 100644 --- 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 @@ -19,8 +19,6 @@ package org.wso2.carbon.device.mgt.core.traccar.common.beans; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; - public class TraccarDevice { private int id; private String deviceIdentifier; 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 index d1164bdb35..b79ad07866 100644 --- 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 @@ -39,7 +39,7 @@ public class TraccarConfigurationManager { 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.TRACCAR_CONFIG_XML_NAME; + private static final String TRACCAR_CONFIG_PATH = CarbonUtilsFile + TraccarHandlerConstants.TraccarConfig.TRACCAR_CONFIG_XML_NAME; /** * Retrieve an instance of {@link TraccarConfigurationManager} 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 24fab102c2..a9525c4081 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 @@ -749,28 +749,22 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING ( -- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- --- DM_TRACCAR_GROUP_MAPPING TABLE-- -CREATE TABLE IF NOT EXISTS DM_TRACCAR_GROUP_MAPPING ( +-- DM_EXT_GROUP_MAPPING TABLE-- +CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING ( ID INT NOT NULL AUTO_INCREMENT, TRACCAR_GROUP_ID INT NOT NULL, GROUP_ID INT NOT NULL, TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_group_traccar_group_mapping FOREIGN KEY (GROUP_ID) REFERENCES - DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT uk_traccar_group UNIQUE (TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID) + PRIMARY KEY (ID) ); --- END OF DM_TRACCAR_GROUP_MAPPING TABLE-- +-- END OF DM_EXT_GROUP_MAPPING TABLE-- --- END OF DM_TRACCAR_DEVICE_MAPPING TABLE-- -CREATE TABLE IF NOT EXISTS DM_TRACCAR_DEVICE_MAPPING ( +-- 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 NOT NULL, DEVICE_ID INT NOT NULL, TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_traccar_device_mapping FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT uk_traccar_device UNIQUE (TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID) + PRIMARY KEY (ID) ); --- END OF DM_TRACCAR_DEVICE_MAPPING TABLE-- +-- END OF DM_EXT_DEVICE_MAPPING TABLE--