update the threadpool apporoach/ add traccar devices/groups for existing UEM devices/groups

feature/traccar-sync
Rushdi Mohamed 3 years ago
parent 9d9ff9f391
commit d1f2bdb296

@ -18,38 +18,26 @@
*/ */
package org.wso2.carbon.device.mgt.common; package org.wso2.carbon.device.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable; import java.io.Serializable;
@ApiModel(value = "TrackerGroupInfo", description = "This class carries all information related to a add groups.") public class TrackerGroupInfo implements Serializable {
public class TrackerInfo implements Serializable {
private static final long serialVersionUID = 1998101712L; 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 id;
private int traccarGroupId; private int traccarGroupId;
private int traccarDeviceId;
private int groupId; private int groupId;
private int tenantId; 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.traccarGroupId = traccarGroupId;
this.groupId = groupId; this.groupId = groupId;
this.tenantId = tenantId; this.tenantId = tenantId;
} }
public TrackerInfo(int traccarDeviceId, int groupId) {
this.traccarDeviceId = traccarDeviceId;
this.groupId = groupId;
}
public int getId() { public int getId() {
return id; return id;
} }
@ -81,12 +69,4 @@ public class TrackerInfo implements Serializable {
public void setTenantId(int tenantId) { public void setTenantId(int tenantId) {
this.tenantId = tenantId; this.tenantId = tenantId;
} }
public int getTraccarDeviceId() {
return traccarDeviceId;
}
public void setTraccarDeviceId(int traccarDeviceId) {
this.traccarDeviceId = traccarDeviceId;
}
} }

@ -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;
}
}

@ -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.common.exceptions.UnsupportedDatabaseEngineException;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; 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.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.GenericGroupDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.group.OracleGroupDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.group.OracleGroupDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.group.PostgreSQLGroupDAOImpl; 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."); 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) { public static void init(DataSourceConfig config) {
dataSource = resolveDataSource(config); dataSource = resolveDataSource(config);
try { try {

@ -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.
* <p/>
* 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.
* <p/>
* Any transaction that commits data into the underlying data persistence mechanism MUST follow the sequence of
* operations mentioned below.
* <p/>
* <pre>
* {@code
* try {
* TrackerManagementDAOFactory.beginTransaction();
* .....
* TrackerManagementDAOFactory.commitTransaction();
* return success;
* } catch (Exception e) {
* TrackerManagementDAOFactory.rollbackTransaction();
* throw new DeviceManagementException("Error occurred while ...", e);
* } finally {
* TrackerManagementDAOFactory.closeConnection();
* }
* }
* </pre>
* <p/>
* Any transaction that retrieves data from the underlying data persistence mechanism MUST follow the sequence of
* operations mentioned below.
* <p/>
* <pre>
* {@code
* try {
* TrackerManagementDAOFactory.openConnection();
* .....
* } catch (Exception e) {
* throw new DeviceManagementException("Error occurred while ..., e);
* } finally {
* TrackerManagementDAOFactory.closeConnection();
* }
* }
* </pre>
*/
public class TrackerManagementDAOFactory {
private static DataSource dataSource;
private static String databaseEngine;
private static final Log log = LogFactory.getLog(TrackerManagementDAOFactory.class);
private static ThreadLocal<Connection> 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<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
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;
}
}

@ -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.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; 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.TrackerManagementDAOFactory;
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.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; 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.TrackerManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -38,8 +36,8 @@ public class TrackerDAOImpl implements TrackerDAO {
public Boolean addTraccarDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException { public Boolean addTraccarDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
Connection conn = DeviceManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_TRACCAR_DEVICE_MAPPING(TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID) VALUES(?, ?, ?)"; String sql = "INSERT INTO DM_EXT_DEVICE_MAPPING(TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID) VALUES(?, ?, ?)";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, traccarDeviceId); stmt.setInt(1, traccarDeviceId);
stmt.setInt(2, deviceId); stmt.setInt(2, deviceId);
@ -50,7 +48,7 @@ public class TrackerDAOImpl implements TrackerDAO {
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while adding traccar device mapping", e); throw new TrackerManagementDAOException("Error occurred while adding traccar device mapping", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@ -60,8 +58,8 @@ public class TrackerDAOImpl implements TrackerDAO {
ResultSet rs = null; ResultSet rs = null;
int status = -1; int status = -1;
try { try {
Connection conn = DeviceManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_TRACCAR_DEVICE_MAPPING WHERE DEVICE_ID = ? AND TENANT_ID = ? "; String sql = "DELETE FROM DM_EXT_DEVICE_MAPPING WHERE DEVICE_ID = ? AND TENANT_ID = ? ";
stmt = conn.prepareStatement(sql, new String[] {"id"}); stmt = conn.prepareStatement(sql, new String[] {"id"});
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
@ -74,7 +72,7 @@ public class TrackerDAOImpl implements TrackerDAO {
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while removing traccar device", e); throw new TrackerManagementDAOException("Error occurred while removing traccar device", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@ -84,8 +82,8 @@ public class TrackerDAOImpl implements TrackerDAO {
ResultSet rs = null; ResultSet rs = null;
TrackerDeviceInfo trackerDeviceInfo = null; TrackerDeviceInfo trackerDeviceInfo = null;
try { try {
Connection conn = DeviceManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "SELECT ID, TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID FROM DM_TRACCAR_DEVICE_MAPPING WHERE " + 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"; "DEVICE_ID = ? AND TENANT_ID = ? ORDER BY ID DESC LIMIT 1";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
@ -98,7 +96,7 @@ public class TrackerDAOImpl implements TrackerDAO {
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while retrieving the traccar device information ", e); throw new TrackerManagementDAOException("Error occurred while retrieving the traccar device information ", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); TrackerManagementDAOUtil.cleanupResources(stmt, rs);
} }
} }
@ -107,8 +105,8 @@ public class TrackerDAOImpl implements TrackerDAO {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_TRACCAR_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID) VALUES(?, ?, ?)"; String sql = "INSERT INTO DM_EXT_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID) VALUES(?, ?, ?)";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, traccarGroupId); stmt.setInt(1, traccarGroupId);
stmt.setInt(2, groupId); stmt.setInt(2, groupId);
@ -120,7 +118,7 @@ public class TrackerDAOImpl implements TrackerDAO {
String msg = "Error occurred while adding traccar group mapping"; String msg = "Error occurred while adding traccar group mapping";
throw new TrackerManagementDAOException(msg, e); throw new TrackerManagementDAOException(msg, e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@ -130,8 +128,8 @@ public class TrackerDAOImpl implements TrackerDAO {
ResultSet rs = null; ResultSet rs = null;
int status = -1; int status = -1;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_TRACCAR_GROUP_MAPPING WHERE ID = ? "; String sql = "DELETE FROM DM_EXT_GROUP_MAPPING WHERE ID = ? ";
stmt = conn.prepareStatement(sql, new String[] {"id"}); stmt = conn.prepareStatement(sql, new String[] {"id"});
stmt.setInt(1, id); stmt.setInt(1, id);
stmt.executeUpdate(); stmt.executeUpdate();
@ -143,7 +141,7 @@ public class TrackerDAOImpl implements TrackerDAO {
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while removing traccar group", e); throw new TrackerManagementDAOException("Error occurred while removing traccar group", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@ -153,8 +151,8 @@ public class TrackerDAOImpl implements TrackerDAO {
ResultSet rs = null; ResultSet rs = null;
TrackerGroupInfo trackerGroupInfo = null; TrackerGroupInfo trackerGroupInfo = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "SELECT ID, TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID FROM DM_TRACCAR_GROUP_MAPPING WHERE " + String sql = "SELECT ID, TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID FROM DM_EXT_GROUP_MAPPING WHERE " +
"GROUP_ID = ? AND TENANT_ID = ?"; "GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId); stmt.setInt(1, groupId);
@ -167,7 +165,7 @@ public class TrackerDAOImpl implements TrackerDAO {
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e);
} finally { } finally {
GroupManagementDAOUtil.cleanupResources(stmt, rs); TrackerManagementDAOUtil.cleanupResources(stmt, rs);
} }
} }

@ -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<Object, Object> 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);
}
}
}

@ -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.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.report.mgt.Constants; 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.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.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
@ -388,13 +387,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
} }
//Traccar update GPS Location //Traccar update GPS Location
try { if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) {
if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) { DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() .updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId());
.updateLocation(device, deviceLocation);
}
} catch (TraccarConfigurationException e) {
log.error("Error on Traccar while adding GEO Location" + e);
} }
//Traccar update GPS Location //Traccar update GPS Location

@ -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.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.EventManagementDAOFactory; 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.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.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl;
import org.wso2.carbon.device.mgt.core.event.config.EventConfigurationProviderServiceImpl; import org.wso2.carbon.device.mgt.core.event.config.EventConfigurationProviderServiceImpl;
@ -192,6 +193,7 @@ public class DeviceManagementServiceComponent {
DeviceManagementDAOFactory.init(dsConfig); DeviceManagementDAOFactory.init(dsConfig);
GroupManagementDAOFactory.init(dsConfig); GroupManagementDAOFactory.init(dsConfig);
TrackerManagementDAOFactory.init(dsConfig);
NotificationManagementDAOFactory.init(dsConfig); NotificationManagementDAOFactory.init(dsConfig);
OperationManagementDAOFactory.init(dsConfig); OperationManagementDAOFactory.init(dsConfig);
MetadataManagementDAOFactory.init(dsConfig); MetadataManagementDAOFactory.init(dsConfig);

@ -47,7 +47,6 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; 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.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.StartupOperationConfig; 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.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; import org.wso2.carbon.device.mgt.common.configuration.mgt.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.MetadataDAO;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; 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.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.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.email.sender.core.ContentProviderInfo; import org.wso2.carbon.email.sender.core.ContentProviderInfo;
@ -181,7 +177,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private MetadataDAO metadataDAO; private MetadataDAO metadataDAO;
private final BillingDAO billingDAO; private final BillingDAO billingDAO;
private final DeviceStatusDAO deviceStatusDAO; private final DeviceStatusDAO deviceStatusDAO;
private final TrackerDAO trackerDAO;
public DeviceManagementProviderServiceImpl() { public DeviceManagementProviderServiceImpl() {
this.pluginRepository = new DeviceManagementPluginRepository(); this.pluginRepository = new DeviceManagementPluginRepository();
@ -192,7 +187,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO(); this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO();
this.billingDAO = DeviceManagementDAOFactory.getBillingDAO(); this.billingDAO = DeviceManagementDAOFactory.getBillingDAO();
this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO(); this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO();
this.trackerDAO = DeviceManagementDAOFactory.getTrackerDAO();
/* Registering a listener to retrieve events when some device management service plugin is installed after /* Registering a listener to retrieve events when some device management service plugin is installed after
* the component is done getting initialized */ * the component is done getting initialized */
@ -417,12 +411,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
//enroll Traccar device //enroll Traccar device
try { if (HttpReportingUtil.isTrackerEnabled()) {
if (HttpReportingUtil.isTrackerEnabled()) { DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId);
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId);
}
} catch (TraccarConfigurationException e) {
log.error("Error while adding a group to Traccar " + e);
} }
//enroll Traccar device //enroll Traccar device
@ -488,18 +478,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceDAO.updateDevice(device, tenantId); deviceDAO.updateDevice(device, tenantId);
enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), 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(); DeviceManagementDAOFactory.commitTransaction();
this.removeDeviceFromCache(deviceIdentifier); this.removeDeviceFromCache(deviceIdentifier);
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
@ -600,21 +578,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
this.removeDeviceFromCache(deviceId); this.removeDeviceFromCache(deviceId);
//disenroll Traccar device //procees to dis-enroll a device from traccar starts
if (HttpReportingUtil.isTrackerEnabled()) { if (HttpReportingUtil.isTrackerEnabled()) {
try { DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
TrackerDeviceInfo res = trackerDAO.getTraccarDevice(device.getId(), tenantId); .disEndrollDevice(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);
}
} }
//procees to dis-enroll a device from traccar ends*/ //procees to dis-enroll a device from traccar ends
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();

@ -38,7 +38,6 @@ package org.wso2.carbon.device.mgt.core.service;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; 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.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException; 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.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.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.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.GroupManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; 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.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.event.config.GroupAssignmentEventOperationExecutor;
import org.wso2.carbon.device.mgt.core.geo.task.GeoFenceEventOperationManager; 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.internal.DeviceManagementDataHolder;
@ -89,7 +90,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
private final GroupDAO groupDAO; private final GroupDAO groupDAO;
private final DeviceDAO deviceDAO; private final DeviceDAO deviceDAO;
private final TrackerDAO trackerDAO;
/** /**
* Set groupDAO from GroupManagementDAOFactory when class instantiate. * Set groupDAO from GroupManagementDAOFactory when class instantiate.
@ -97,7 +97,6 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
public GroupManagementProviderServiceImpl() { public GroupManagementProviderServiceImpl() {
this.groupDAO = GroupManagementDAOFactory.getGroupDAO(); this.groupDAO = GroupManagementDAOFactory.getGroupDAO();
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.trackerDAO = DeviceManagementDAOFactory.getTrackerDAO();
} }
/** /**
@ -140,27 +139,18 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
//add new group in traccar //add new group in traccar
try { if (HttpReportingUtil.isTrackerEnabled()) {
if (HttpReportingUtil.isTrackerEnabled()) { DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() .addGroup(deviceGroup, updatedGroupID, tenantId);
.addGroup(deviceGroup, updatedGroupID, tenantId);
}
} catch (TraccarConfigurationException e) {
log.error("Error while adding a group to Traccar " + e);
} }
//add new group in traccar //add new group in traccar
} else { } else {
// add a group if not exist in traccar starts // add a group if not exist in traccar starts
existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId); if (HttpReportingUtil.isTrackerEnabled()){
int groupId = existingGroup.getGroupId(); existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId);
TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId); int groupId = existingGroup.getGroupId();
if(res==null){ DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
try { .addGroup(deviceGroup, groupId, tenantId);
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 // 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 //procees to update a group in traccar starts
if (HttpReportingUtil.isTrackerEnabled()) { if (HttpReportingUtil.isTrackerEnabled()) {
TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId); DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
JSONObject obj = new JSONObject(res); .updateGroup(deviceGroup, groupId, tenantId);
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 //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 //procees to delete a group from traccar starts
if (HttpReportingUtil.isTrackerEnabled()) { if (HttpReportingUtil.isTrackerEnabled()) {
TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId); DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
JSONObject obj = new JSONObject(res); .deleteGroup(groupId, tenantId);
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 //procees to delete a group from traccar ends

@ -20,15 +20,10 @@
package org.wso2.carbon.device.mgt.core.traccar.api.service; package org.wso2.carbon.device.mgt.core.traccar.api.service;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
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.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; 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 org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException;
import java.io.IOException;
public interface DeviceAPIClientService { public interface DeviceAPIClientService {
/** /**
@ -38,7 +33,7 @@ public interface DeviceAPIClientService {
* @param deviceLocation to be added to update location of the device * @param deviceLocation to be added to update location of the device
* @throws TraccarConfigurationException errors thrown while inserting location of a device traccar configuration * @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 * Create device Traccar configuration records
@ -46,7 +41,7 @@ public interface DeviceAPIClientService {
* @param device to be added * @param device to be added
* @throws TraccarConfigurationException errors thrown while creating a device traccar configuration * @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 * Create device Traccar configuration records
@ -54,7 +49,7 @@ public interface DeviceAPIClientService {
* @param device to modify * @param device to modify
* @throws TraccarConfigurationException errors thrown while creating a device traccar configuration * @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 * Delete a device Traccar configuration records
@ -62,7 +57,7 @@ public interface DeviceAPIClientService {
* @param deviceId to be delete a device * @param deviceId to be delete a device
* @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration * @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 * Delete a device Traccar configuration records
@ -70,22 +65,22 @@ public interface DeviceAPIClientService {
* @param group to be add a group * @param group to be add a group
* @throws TraccarConfigurationException errors thrown while adding a group traccar configuration * @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 * 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 * @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 * Delete a device Traccar configuration records
* *
* @param traccarGroupId to delete a group * @param groupId to delete a group
* @param tenantId to delete a group * @param tenantId to delete a group
* @throws TraccarConfigurationException errors thrown while adding a group traccar configuration * @throws TraccarConfigurationException errors thrown while adding a group traccar configuration
*/ */
void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException; void deleteGroup(int groupId, int tenantId);
} }

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.core.traccar.api.service.addons; package org.wso2.carbon.device.mgt.core.traccar.api.service.addons;
import com.google.gson.Gson;
import okhttp3.ConnectionPool; import okhttp3.ConnectionPool;
import okhttp3.MediaType; import okhttp3.MediaType;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
@ -29,11 +30,13 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; 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.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.common.group.mgt.TrackerAlreadyExistException;
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.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; 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.TraccarClient;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants; import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; import org.wso2.carbon.device.mgt.core.traccar.common.beans.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 org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationManager;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; 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 defaultPort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.DEFAULT_PORT).getValue();
final String locationUpdatePort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.LOCATION_UPDATE_PORT).getValue(); final String locationUpdatePort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.LOCATION_UPDATE_PORT).getValue();
private final TrackerDAO trackerGroupDAO; private final TrackerDAO trackerDAO;
private final TrackerDAO trackerDeviceDAO;
public TrackerClient() { public TrackerClient() {
client = new OkHttpClient.Builder() client = new OkHttpClient.Builder()
@ -73,12 +77,11 @@ public class TrackerClient implements TraccarClient {
.readTimeout(45, TimeUnit.SECONDS) .readTimeout(45, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS)) .connectionPool(new ConnectionPool(50,30,TimeUnit.SECONDS))
.build(); .build();
this.trackerDeviceDAO = GroupManagementDAOFactory.getTrackerDAO(); this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO();
this.trackerGroupDAO = DeviceManagementDAOFactory.getTrackerDAO();
} }
private class TrackerExecutor implements Runnable { private class TrackerExecutor implements Runnable {
final int id; final int deviceId;
final int tenantId; final int tenantId;
final JSONObject payload; final JSONObject payload;
final String context; final String context;
@ -86,9 +89,9 @@ public class TrackerClient implements TraccarClient {
private final String method; private final String method;
private final String type; 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) { String method, String type) {
this.id = id; this.deviceId = deviceId;
this.tenantId = tenantId; this.tenantId = tenantId;
this.payload = payload; this.payload = payload;
this.context = context; this.context = context;
@ -106,7 +109,7 @@ public class TrackerClient implements TraccarClient {
if(method==TraccarHandlerConstants.Methods.POST){ if(method==TraccarHandlerConstants.Methods.POST){
requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8")); requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8"));
builder = builder.post(requestBody); 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")); requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8"));
builder = builder.put(requestBody); builder = builder.put(requestBody);
}else if(method==TraccarHandlerConstants.Methods.DELETE){ }else if(method==TraccarHandlerConstants.Methods.DELETE){
@ -117,43 +120,33 @@ public class TrackerClient implements TraccarClient {
try { try {
response = client.newCall(request).execute(); response = client.newCall(request).execute();
if(method==TraccarHandlerConstants.Methods.POST){ if(method==TraccarHandlerConstants.Methods.POST){
String result = response.body().string(); JSONObject obj = new JSONObject(response.body().string());
JSONObject obj = new JSONObject(result); if (obj != null){
int traccarId = obj.getInt("id"); int traccarId = obj.getInt("id");
if(type==TraccarHandlerConstants.Types.DEVICE){
try { try {
DeviceManagementDAOFactory.beginTransaction(); TrackerManagementDAOFactory.beginTransaction();
trackerDeviceDAO.addTraccarDevice(traccarId, id, tenantId); if(type==TraccarHandlerConstants.Types.DEVICE){
DeviceManagementDAOFactory.commitTransaction(); trackerDAO.addTraccarDevice(traccarId, deviceId, tenantId);
}else if(type==TraccarHandlerConstants.Types.GROUP){
trackerDAO.addTraccarGroup(traccarId, deviceId, tenantId);
}
TrackerManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction(); TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection ."; String msg = "Error occurred establishing the DB connection .";
log.error(msg, e); log.error(msg, e);
} catch (TrackerManagementDAOException e) { } catch (TrackerManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping traccarDeviceId with deviceId ."; 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); log.error(msg, e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.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();
} }
} }
} }
@ -162,7 +155,6 @@ public class TrackerClient implements TraccarClient {
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred", e); log.error("Error occurred", e);
} }
} }
} }
@ -173,19 +165,31 @@ public class TrackerClient implements TraccarClient {
* Model, Contact, Category, fenceIds * Model, Contact, Category, fenceIds
* @throws TraccarConfigurationException Failed while add Traccar Device the operation * @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/ */
public void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException { public void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException {
try{ TrackerDeviceInfo res = null;
JSONObject payload = payload(deviceInfo); try {
String context = defaultPort+"/api/devices"; TrackerManagementDAOFactory.openConnection();
Runnable trackerExecutor = res = trackerDAO.getTraccarDevice(deviceInfo.getId(), tenantId);
new TrackerExecutor( deviceInfo.getId(),tenantId, endpoint, context, payload, if(res!=null){
TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.DEVICE); throw new TrackerAlreadyExistException("The device already exit");
executor.execute(trackerExecutor); }
}catch (Exception e){ } catch (TrackerManagementDAOException e) {
String msg="Could not enroll traccar device"; String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e); log.error(msg, e);
throw new TraccarConfigurationException(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 * Model, Contact, Category, fenceIds
* @throws TraccarConfigurationException Failed while add Traccar Device the operation * @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/ */
public void updateDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException { public void updateDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException {
try{ 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); JSONObject payload = payload(deviceInfo);
String context = defaultPort+"/api/devices"; String context = defaultPort+"/api/devices";
Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload, Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload,
TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.DEVICE); TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.DEVICE);
executor.execute(trackerExecutor); 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. * Add Device GPS Location operation.
* @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition * @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition
*/ */
public void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException { public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException {
try{ TrackerDeviceInfo res = null;
String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"&timestamp="+deviceInfo.getTimestamp()+ try {
"&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ TrackerManagementDAOFactory.openConnection();
"&speed="+deviceInfo.getSpeed()+"&ignition=true"; res = trackerDAO.getTraccarDevice(device.getId(), tenantId);
Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null, } catch (SQLException e) {
TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE); String msg = "Error occurred establishing the DB connection .";
executor.execute(trackerExecutor); log.error(msg, e);
log.info("Device GPS location added on traccar"); } catch (TrackerManagementDAOException e) {
}catch (Exception e){ String msg="Could not update the traccar group";
String msg="Could not add GPS location"; log.error(msg, e);
log.error(msg, e); } finally{
throw new TraccarConfigurationException(msg, e); 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()+"&timestamp="+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. * 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 * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation
*/ */
public void disEndrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException { public void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException {
try{ try {
String context = defaultPort+"/api/devices/"+traccarDeviceId; TrackerManagementDAOFactory.beginTransaction();
Runnable trackerExecutor = new TrackerExecutor(traccarDeviceId, tenantId, endpoint, context, null, 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); TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE);
executor.execute(trackerExecutor); executor.execute(trackerExecutor);
log.info("Device successfully dis-enrolled"); TrackerManagementDAOFactory.commitTransaction();
}catch (JSONException e){ } catch (TransactionManagementException e) {
String msg = "Could not find the device information to dis-enroll the device"; 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); log.error(msg, e);
throw new TraccarConfigurationException(msg); } finally {
TrackerManagementDAOFactory.closeConnection();
} }
} }
@ -271,22 +343,34 @@ public class TrackerClient implements TraccarClient {
* @param groupInfo with groupName * @param groupInfo with groupName
* @throws TraccarConfigurationException Failed while add Traccar Device the operation * @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/ */
public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException { public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException {
try{
JSONObject payload = new JSONObject();
payload.put("name", groupInfo.getName());
payload.put("attributes", new JSONObject());
String context = defaultPort+"/api/groups"; try {
Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload, TrackerManagementDAOFactory.openConnection();
TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP); TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId);
executor.execute(trackerExecutor); if(res!=null){
log.info("Group successfully added on traccar"); throw new TrackerAlreadyExistException("The group already exit");
}catch (Exception e){ }
String msg="Could not add a traccar group"; } 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); log.error(msg, e);
throw new TraccarConfigurationException(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 * @param groupInfo with groupName
* @throws TraccarConfigurationException Failed while add Traccar Device the operation * @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/ */
public void updateGroup(TraccarGroups groupInfo, int traccarGroupId, int groupId, int tenantId) throws TraccarConfigurationException { public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException {
try{ 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(); JSONObject payload = new JSONObject();
payload.put("id", traccarGroupId); payload.put("id", obj.getInt("traccarGroupId"));
payload.put("name", groupInfo.getName()); payload.put("name", groupInfo.getName());
payload.put("attributes", new JSONObject()); 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, Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload,
TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP); TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP);
executor.execute(trackerExecutor); 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. * Add Traccar Device operation.
* @param traccarGroupId * @param groupId
* @throws TraccarConfigurationException Failed while add Traccar Device the operation * @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/ */
public void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException { public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException {
try{ try {
String context = defaultPort+"/api/groups/"+traccarGroupId; TrackerManagementDAOFactory.beginTransaction();
Runnable trackerExecutor = new TrackerExecutor(traccarGroupId, tenantId, endpoint, context, 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); null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.GROUP);
executor.execute(trackerExecutor); executor.execute(trackerExecutor);
}catch (JSONException e){ TrackerManagementDAOFactory.commitTransaction();
String msg = "Could not find the device information to dis-enroll the device"; } 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); log.error(msg, e);
throw new TraccarConfigurationException(msg); } finally {
TrackerManagementDAOFactory.closeConnection();
} }
} }
private TraccarGateway getTraccarGateway(){ private TraccarGateway getTraccarGateway(){
return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway( return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway(
TraccarHandlerConstants.GATEWAY_NAME); TraccarHandlerConstants.TraccarConfig.GATEWAY_NAME);
} }
} }

@ -19,9 +19,12 @@
package org.wso2.carbon.device.mgt.core.traccar.api.service.impl; 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;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; 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.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.DeviceAPIClientService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TrackerClient; import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TrackerClient;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; 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 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(); TrackerClient client = new TrackerClient();
String lastUpdatedTime = String.valueOf((new Date().getTime())); 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, "", "", "", "", "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(); TrackerClient client = new TrackerClient();
String lastUpdatedTime = String.valueOf((new Date().getTime())); String lastUpdatedTime = String.valueOf((new Date().getTime()));
TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(), TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(),
"online", "false", lastUpdatedTime, "", "", "", "", "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(); TrackerClient client = new TrackerClient();
TraccarPosition traccarPosition = new TraccarPosition(device.getDeviceIdentifier(), TraccarPosition traccarPosition = new TraccarPosition(device.getDeviceIdentifier(),
deviceLocation.getUpdatedTime().getTime(), deviceLocation.getUpdatedTime().getTime(),
deviceLocation.getLatitude(), deviceLocation.getLongitude(), deviceLocation.getLatitude(), deviceLocation.getLongitude(),
deviceLocation.getBearing(), deviceLocation.getSpeed()); 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(); 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(); TrackerClient client = new TrackerClient();
TraccarGroups traccarGroups = new TraccarGroups(group.getName()); 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(); TrackerClient client = new TrackerClient();
TraccarGroups traccarGroups = new TraccarGroups(group.getName()); 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(); 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);
}
} }
} }

@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.core.traccar.common; 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.TraccarDevice;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarGroups; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarGroups;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition;
@ -26,16 +27,22 @@ import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfiguratio
public interface TraccarClient { 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 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; void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException;
} }

@ -20,13 +20,16 @@
package org.wso2.carbon.device.mgt.core.traccar.common; package org.wso2.carbon.device.mgt.core.traccar.common;
public class TraccarHandlerConstants { public class TraccarHandlerConstants {
public static final String TRACCAR_CONFIG_XML_NAME = "traccar-config.xml";
public static final String GATEWAY_NAME = "sample"; public static class TraccarConfig {
public static final String ENDPOINT = "api-endpoint"; public static final String TRACCAR_CONFIG_XML_NAME = "traccar-config.xml";
public static final String AUTHORIZATION = "authorization"; public static final String GATEWAY_NAME = "sample";
public static final String AUTHORIZATION_KEY = "authorization-key"; public static final String ENDPOINT = "api-endpoint";
public static final String DEFAULT_PORT = "default-port"; public static final String AUTHORIZATION = "authorization";
public static final String LOCATION_UPDATE_PORT = "location-update-port"; 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 class Methods {
public static final String POST = "POST"; public static final String POST = "POST";
@ -40,14 +43,4 @@ public class TraccarHandlerConstants {
public static final String GROUP = "GROUP"; 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";
}
} }

@ -19,8 +19,6 @@
package org.wso2.carbon.device.mgt.core.traccar.common.beans; package org.wso2.carbon.device.mgt.core.traccar.common.beans;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
public class TraccarDevice { public class TraccarDevice {
private int id; private int id;
private String deviceIdentifier; private String deviceIdentifier;

@ -39,7 +39,7 @@ public class TraccarConfigurationManager {
private static TraccarConfigurationManager traccarConfigurationManager; private static TraccarConfigurationManager traccarConfigurationManager;
private TraccarConfiguration traccarConfiguration; private TraccarConfiguration traccarConfiguration;
private static final String CarbonUtilsFile = CarbonUtils.getCarbonConfigDirPath() + File.separator; 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} * Retrieve an instance of {@link TraccarConfigurationManager}

@ -749,28 +749,22 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING (
-- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- -- END OF DM_GEOFENCE_GROUP_MAPPING TABLE--
-- DM_TRACCAR_GROUP_MAPPING TABLE-- -- DM_EXT_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_TRACCAR_GROUP_MAPPING ( CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,
TRACCAR_GROUP_ID INT NOT NULL, TRACCAR_GROUP_ID INT NOT NULL,
GROUP_ID INT NOT NULL, GROUP_ID INT NOT NULL,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
PRIMARY KEY (ID), 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)
); );
-- END OF DM_TRACCAR_GROUP_MAPPING TABLE-- -- END OF DM_EXT_GROUP_MAPPING TABLE--
-- END OF DM_TRACCAR_DEVICE_MAPPING TABLE-- -- END OF DM_EXT_DEVICE_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_TRACCAR_DEVICE_MAPPING ( CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING (
ID INT NOT NULL AUTO_INCREMENT, ID INT NOT NULL AUTO_INCREMENT,
TRACCAR_DEVICE_ID INT NOT NULL, TRACCAR_DEVICE_ID INT NOT NULL,
DEVICE_ID INT NOT NULL, DEVICE_ID INT NOT NULL,
TENANT_ID INT NOT NULL, TENANT_ID INT NOT NULL,
PRIMARY KEY (ID), 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)
); );
-- END OF DM_TRACCAR_DEVICE_MAPPING TABLE-- -- END OF DM_EXT_DEVICE_MAPPING TABLE--

Loading…
Cancel
Save