Update group add/update/delete and device enroll/disenroll with traccar

feature/traccar-sync
Rushdi Mohamed 3 years ago
parent 9f6eaedbc3
commit c3dd560878

@ -0,0 +1,72 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.common;
import java.io.Serializable;
public class TrackerDeviceInfo implements Serializable {
private static final long serialVersionUID = 1998101712L;
private int id;
private int traccarDeviceId;
private int deviceId;
private int tenantId;
public TrackerDeviceInfo() {
}
public TrackerDeviceInfo(int traccarDeviceId, int deviceId, int tenantId) {
this.traccarDeviceId = traccarDeviceId;
this.deviceId = deviceId;
this.tenantId = tenantId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTraccarDeviceId() {
return traccarDeviceId;
}
public void setTraccarDeviceId(int traccarDeviceId) {
this.traccarDeviceId = traccarDeviceId;
}
public int getDeviceId() {
return deviceId;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
}

@ -0,0 +1,92 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(value = "TrackerGroupInfo", description = "This class carries all information related to a add groups.")
public class TrackerInfo implements Serializable {
private static final long serialVersionUID = 1998101712L;
@ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.",
required = true)
private int id;
private int traccarGroupId;
private int traccarDeviceId;
private int groupId;
private int tenantId;
public TrackerInfo() {
}
public TrackerInfo(int traccarGroupId, int groupId, int tenantId) {
this.traccarGroupId = traccarGroupId;
this.groupId = groupId;
this.tenantId = tenantId;
}
public TrackerInfo(int traccarDeviceId, int groupId) {
this.traccarDeviceId = traccarDeviceId;
this.groupId = groupId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTraccarGroupId() {
return traccarGroupId;
}
public void setTraccarGroupId(int traccarGroupId) {
this.traccarGroupId = traccarGroupId;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public int getTenantId() {
return tenantId;
}
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public int getTraccarDeviceId() {
return traccarDeviceId;
}
public void setTraccarDeviceId(int traccarDeviceId) {
this.traccarDeviceId = traccarDeviceId;
}
}

@ -130,6 +130,23 @@ public class DeviceManagementDAOFactory {
return new BillingDAOImpl(); return new BillingDAOImpl();
} }
public static TrackerDAO getTrackerDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL:
return new TrackerDAOImpl();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
}
throw new IllegalStateException("Database engine has not initialized properly.");
}
public static DeviceStatusDAO getDeviceStatusDAO() { public static DeviceStatusDAO getDeviceStatusDAO() {
return new DeviceStatusDAOImpl(); return new DeviceStatusDAOImpl();
} }

@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementExcepti
import org.wso2.carbon.device.mgt.common.exceptions.UnsupportedDatabaseEngineException; import org.wso2.carbon.device.mgt.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;
@ -72,6 +73,22 @@ 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,38 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerGroupInfo;
public interface TrackerDAO {
Boolean addTraccarDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException;
int removeTraccarDevice(int deviceId, int tenantId) throws TrackerManagementDAOException;
TrackerDeviceInfo getTraccarDevice(int groupId, int tenantId) throws TrackerManagementDAOException;
Boolean addTraccarGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException;
int removeTraccarGroup(int id) throws TrackerManagementDAOException;
TrackerGroupInfo getTraccarGroup(int groupId, int tenantId) throws TrackerManagementDAOException;
}

@ -0,0 +1,78 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.dao;
/**
* Custom exception class for data access related exceptions.
*/
public class TrackerManagementDAOException extends Exception {
private String message;
private static final long serialVersionUID = 2021891706072918864L;
/**
* Constructs a new exception with the specified detail message and nested exception.
*
* @param message error message
* @param nestedException exception
*/
public TrackerManagementDAOException(String message, Exception nestedException) {
super(message, nestedException);
setErrorMessage(message);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message the detail message.
* @param cause the cause of this exception.
*/
public TrackerManagementDAOException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
/**
* Constructs a new exception with the specified detail message
*
* @param message the detail message.
*/
public TrackerManagementDAOException(String message) {
super(message);
setErrorMessage(message);
}
/**
* Constructs a new exception with the specified and cause.
*
* @param cause the cause of this exception.
*/
public TrackerManagementDAOException(Throwable cause) {
super(cause);
}
public String getMessage() {
return message;
}
public void setErrorMessage(String errorMessage) {
this.message = errorMessage;
}
}

@ -0,0 +1,191 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.dao.impl;
import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerGroupInfo;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.TrackerDAO;
import org.wso2.carbon.device.mgt.core.dao.util.GroupManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TrackerDAOImpl implements TrackerDAO {
@Override
public Boolean addTraccarDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = DeviceManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_TRACCAR_DEVICE_MAPPING(TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID) VALUES(?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, traccarDeviceId);
stmt.setInt(2, deviceId);
stmt.setInt(3, tenantId);
stmt.execute();
return true;
} catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while adding traccar device mapping", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public int removeTraccarDevice(int deviceId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
int status = -1;
try {
Connection conn = DeviceManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_TRACCAR_DEVICE_MAPPING WHERE DEVICE_ID = ? AND TENANT_ID = ? ";
stmt = conn.prepareStatement(sql, new String[] {"id"});
stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
status = 1;
}
return status;
} catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while removing traccar device", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public TrackerDeviceInfo getTraccarDevice(int deviceId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
TrackerDeviceInfo trackerDeviceInfo = null;
try {
Connection conn = DeviceManagementDAOFactory.getConnection();
String sql = "SELECT ID, TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID FROM DM_TRACCAR_DEVICE_MAPPING WHERE " +
"DEVICE_ID = ? AND TENANT_ID = ? ORDER BY ID DESC LIMIT 1";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
trackerDeviceInfo = this.loadTrackerDevice(rs);
}
return trackerDeviceInfo;
} catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while retrieving the traccar device information ", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public Boolean addTraccarGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_TRACCAR_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID) VALUES(?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, traccarGroupId);
stmt.setInt(2, groupId);
stmt.setInt(3, tenantId);
stmt.execute();
return true;
} catch (SQLException e) {
String msg = "Error occurred while adding traccar group mapping";
throw new TrackerManagementDAOException(msg, e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public int removeTraccarGroup(int id) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
int status = -1;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_TRACCAR_GROUP_MAPPING WHERE ID = ? ";
stmt = conn.prepareStatement(sql, new String[] {"id"});
stmt.setInt(1, id);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
status = 1;
}
return status;
} catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while removing traccar group", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public TrackerGroupInfo getTraccarGroup(int groupId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
TrackerGroupInfo trackerGroupInfo = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID, TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID FROM DM_TRACCAR_GROUP_MAPPING WHERE " +
"GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
trackerGroupInfo = this.loadTrackerGroup(rs);
}
return trackerGroupInfo;
} catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, rs);
}
}
private TrackerGroupInfo loadTrackerGroup(ResultSet rs) throws SQLException {
TrackerGroupInfo trackerGroupInfo = new TrackerGroupInfo();
trackerGroupInfo.setId(rs.getInt("ID"));
trackerGroupInfo.setTraccarGroupId(rs.getInt("TRACCAR_GROUP_ID"));
trackerGroupInfo.setGroupId(rs.getInt("GROUP_ID"));
trackerGroupInfo.setTenantId(rs.getInt("TENANT_ID"));
return trackerGroupInfo;
}
private TrackerDeviceInfo loadTrackerDevice(ResultSet rs) throws SQLException {
TrackerDeviceInfo trackerDeviceInfo = new TrackerDeviceInfo();
trackerDeviceInfo.setId(rs.getInt("ID"));
trackerDeviceInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID"));
trackerDeviceInfo.setDeviceId(rs.getInt("DEVICE_ID"));
trackerDeviceInfo.setTenantId(rs.getInt("TENANT_ID"));
return trackerDeviceInfo;
}
}

@ -389,7 +389,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
//Traccar update GPS Location //Traccar update GPS Location
try { try {
if (HttpReportingUtil.isLocationPublishing()) { if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.updateLocation(device, deviceLocation); .updateLocation(device, deviceLocation);
} }

@ -47,10 +47,30 @@ 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;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.ActivityPaginationRequest;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceEnrollmentInfoNotification;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.DeviceNotification;
import org.wso2.carbon.device.mgt.common.DevicePropertyNotification;
import org.wso2.carbon.device.mgt.common.DeviceTransferRequest;
import org.wso2.carbon.device.mgt.common.DynamicTaskContext;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.StartupOperationConfig;
import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerGroupInfo;
import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.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;
@ -118,9 +138,9 @@ import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.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.api.service.DeviceAPIClientService;
import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; 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.email.sender.core.ContentProviderInfo; import org.wso2.carbon.email.sender.core.ContentProviderInfo;
import org.wso2.carbon.email.sender.core.EmailContext; import org.wso2.carbon.email.sender.core.EmailContext;
import org.wso2.carbon.email.sender.core.EmailSendingFailedException; import org.wso2.carbon.email.sender.core.EmailSendingFailedException;
@ -161,6 +181,7 @@ 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();
@ -171,6 +192,7 @@ 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 */
@ -396,9 +418,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
//enroll Traccar device //enroll Traccar device
try { try {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device); if (HttpReportingUtil.isTrackerEnabled()) {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId);
}
} catch (TraccarConfigurationException e) { } catch (TraccarConfigurationException e) {
log.error("Error while adding a device to traccar " + e); log.error("Error while adding a group to Traccar " + e);
} }
//enroll Traccar device //enroll Traccar device
@ -463,6 +487,19 @@ 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) {
@ -564,13 +601,20 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
this.removeDeviceFromCache(deviceId); this.removeDeviceFromCache(deviceId);
//disenroll Traccar device //disenroll Traccar device
if (HttpReportingUtil.isTrackerEnabled()) {
try { 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() DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.disDevice(device.getDeviceIdentifier()); .disEndrollDevice(obj.getInt("traccarDeviceId"), tenantId);
} catch (TraccarConfigurationException e) { } catch (TraccarConfigurationException e) {
log.error("Error while disenrolling a device from Traccar " + e); log.error("Error while disenrolling a device from Traccar " + e);
} }
//disenroll Traccar device }
//procees to dis-enroll a device from traccar ends*/
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();

@ -35,15 +35,16 @@
package org.wso2.carbon.device.mgt.core.service; package org.wso2.carbon.device.mgt.core.service;
import com.google.gson.Gson;
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;
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.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.TrackerGroupInfo;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest; import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
@ -61,12 +62,14 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupDAO; import org.wso2.carbon.device.mgt.core.dao.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.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;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.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.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
@ -86,6 +89,7 @@ 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.
@ -93,6 +97,7 @@ 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();
} }
/** /**
@ -136,21 +141,29 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
//add new group in traccar //add new group in traccar
try { try {
if (HttpReportingUtil.isTrackerEnabled()) {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.addGroup(deviceGroup); .addGroup(deviceGroup, updatedGroupID, tenantId);
}
} catch (TraccarConfigurationException e) { } catch (TraccarConfigurationException e) {
log.error("Error while disenrolling a device from Traccar " + e); log.error("Error while adding a group to Traccar " + e);
} }
//add new group in traccar //add new group in traccar
} else { } else {
//check if a group exist or not in traccar if not existing then add // add a group if not exist in traccar starts
/*try { existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId);
int groupId = existingGroup.getGroupId();
TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId);
if(res==null){
try {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService() DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.addGroup(deviceGroup); .addGroup(deviceGroup, groupId, tenantId);
} catch (TraccarConfigurationException e) { } catch (TraccarConfigurationException e) {
log.error("Error while disenrolling a device from Traccar " + e); log.error("Error while adding a existing group to Traccar " + e);
}*/ }
//check if a group exist or not in traccar }
// add a group if not exist in traccar starts
throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName()); throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName());
} }
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
@ -228,6 +241,20 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
if (deviceGroup.getGroupProperties() != null && deviceGroup.getGroupProperties().size() > 0) { if (deviceGroup.getGroupProperties() != null && deviceGroup.getGroupProperties().size() > 0) {
this.groupDAO.updateGroupProperties(deviceGroup, groupId, tenantId); this.groupDAO.updateGroupProperties(deviceGroup, groupId, tenantId);
} }
//procees to update a group in traccar starts
if (HttpReportingUtil.isTrackerEnabled()) {
TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId);
JSONObject obj = new JSONObject(res);
try {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.updateGroup(deviceGroup, obj.getInt("traccarGroupId"), groupId, tenantId);
} catch (TraccarConfigurationException e) {
log.error("Error while updating the group in Traccar " + e);
}
}
//procees to update a group in traccar starts
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} else { } else {
throw new GroupNotExistException("Group with ID - '" + groupId + "' doesn't exists!"); throw new GroupNotExistException("Group with ID - '" + groupId + "' doesn't exists!");
@ -286,6 +313,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
} }
} }
//procees to delete a group from traccar starts
if (HttpReportingUtil.isTrackerEnabled()) {
TrackerGroupInfo res = trackerDAO.getTraccarGroup(groupId, tenantId);
JSONObject obj = new JSONObject(res);
trackerDAO.removeTraccarGroup(obj.getInt("id"));
try {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.deleteGroup(obj.getInt("traccarGroupId"), tenantId);
} catch (TraccarConfigurationException e) {
log.error("Error while disenrolling a device from Traccar " + e);
}
}
//procees to delete a group from traccar ends
if (isDeleteChildren) { if (isDeleteChildren) {
groupIdsToDelete.add(groupId); groupIdsToDelete.add(groupId);
groupDAO.deleteGroupsMapping(groupIdsToDelete, tenantId); groupDAO.deleteGroupsMapping(groupIdsToDelete, tenantId);
@ -302,14 +344,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DeviceGroup " + deviceGroup.getName() + " removed."); log.debug("DeviceGroup " + deviceGroup.getName() + " removed.");
} }
//add new group in traccar
try {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.deleteGroup(deviceGroup);
} catch (TraccarConfigurationException e) {
log.error("Error while disenrolling a device from Traccar " + e);
}
//add new group in traccar
return true; return true;
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();

@ -46,15 +46,23 @@ 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) throws TraccarConfigurationException; void addDevice(Device device, int tenantId) throws TraccarConfigurationException;
/**
* Create device Traccar configuration records
*
* @param device to modify
* @throws TraccarConfigurationException errors thrown while creating a device traccar configuration
*/
void updateDevice(Device device, int tenantId) throws TraccarConfigurationException;
/** /**
* Delete a device Traccar configuration records * Delete a device Traccar configuration records
* *
* @param deviceIdentifier to be delete a device * @param deviceId to be delete a device
* @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration * @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration
*/ */
void disDevice(String deviceIdentifier) throws TraccarConfigurationException; void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException;
/** /**
* Delete a device Traccar configuration records * Delete a device Traccar configuration records
@ -62,7 +70,7 @@ 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) throws TraccarConfigurationException; void addGroup(DeviceGroup group, int groupID, int tenantId) throws TraccarConfigurationException;
/** /**
* Delete a device Traccar configuration records * Delete a device Traccar configuration records
@ -70,5 +78,14 @@ 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 deleteGroup(DeviceGroup group) throws TraccarConfigurationException; void updateGroup(DeviceGroup group, int traccarGroupId, int groupID, int tenantId) throws TraccarConfigurationException;
/**
* Delete a device Traccar configuration records
*
* @param traccarGroupId to delete a group
* @param tenantId to delete a group
* @throws TraccarConfigurationException errors thrown while adding a group traccar configuration
*/
void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException;
} }

@ -27,9 +27,13 @@ import okhttp3.RequestBody;
import okhttp3.Response; import okhttp3.Response;
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.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.TrackerDAO;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarClient; import org.wso2.carbon.device.mgt.core.traccar.common.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;
@ -42,17 +46,10 @@ import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationM
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.ENDPOINT;
import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION;
import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.AUTHORIZATION_KEY;
import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.DEFAULT_PORT;
import static org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants.LOCATION_UPDATE_PORT;
public class TrackerClient implements TraccarClient { public class TrackerClient implements TraccarClient {
private static final Log log = LogFactory.getLog(TrackerClient.class); private static final Log log = LogFactory.getLog(TrackerClient.class);
private static final int THREAD_POOL_SIZE = 50; private static final int THREAD_POOL_SIZE = 50;
@ -60,11 +57,14 @@ public class TrackerClient implements TraccarClient {
private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
final TraccarGateway traccarGateway = getTraccarGateway(); final TraccarGateway traccarGateway = getTraccarGateway();
final String endpoint = traccarGateway.getPropertyByName(ENDPOINT).getValue(); final String endpoint = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.ENDPOINT).getValue();
final String authorization = traccarGateway.getPropertyByName(AUTHORIZATION).getValue(); final String authorization = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.AUTHORIZATION).getValue();
final String authorizationKey = traccarGateway.getPropertyByName(AUTHORIZATION_KEY).getValue(); final String authorizationKey = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.AUTHORIZATION_KEY).getValue();
final String defaultPort = traccarGateway.getPropertyByName(DEFAULT_PORT).getValue(); final String defaultPort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.DEFAULT_PORT).getValue();
final String locationUpdatePort = traccarGateway.getPropertyByName(LOCATION_UPDATE_PORT).getValue(); final String locationUpdatePort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.LOCATION_UPDATE_PORT).getValue();
private final TrackerDAO trackerGroupDAO;
private final TrackerDAO trackerDeviceDAO;
public TrackerClient() { public TrackerClient() {
client = new OkHttpClient.Builder() client = new OkHttpClient.Builder()
@ -73,39 +73,90 @@ 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.trackerGroupDAO = DeviceManagementDAOFactory.getTrackerDAO();
} }
private class TrackerExecutor implements Runnable { private class TrackerExecutor implements Runnable {
final int id;
final int tenantId;
final JSONObject payload; final JSONObject payload;
final String context; final String context;
final String publisherUrl; final String publisherUrl;
private final String method; private final String method;
private final String type;
private TrackerExecutor(String publisherUrl, String context, JSONObject payload, String method) { private TrackerExecutor(int id, int tenantId, String publisherUrl, String context, JSONObject payload,
String method, String type) {
this.id = id;
this.tenantId = tenantId;
this.payload = payload; this.payload = payload;
this.context = context; this.context = context;
this.publisherUrl = publisherUrl; this.publisherUrl = publisherUrl;
this.method = method; this.method = method;
this.type = type;
} }
public void run() { public void run() {
RequestBody requestBody; RequestBody requestBody;
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
Request request; Request request;
Response response;
if(method=="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);
}else if(method=="delete"){ }if(method==TraccarHandlerConstants.Methods.PUT){
requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8"));
builder = builder.put(requestBody);
}else if(method==TraccarHandlerConstants.Methods.DELETE){
builder = builder.delete(); builder = builder.delete();
} }
request = builder.url(publisherUrl + context) request = builder.url(publisherUrl + context).addHeader(authorization, authorizationKey).build();
.addHeader(authorization, authorizationKey)
.build(); 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){
try {
DeviceManagementDAOFactory.beginTransaction();
trackerDeviceDAO.addTraccarDevice(traccarId, id, tenantId);
DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
} catch (TrackerManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping traccarDeviceId with deviceId .";
log.error(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}else if(type==TraccarHandlerConstants.Types.GROUP){
try { try {
client.newCall(request).execute(); GroupManagementDAOFactory.beginTransaction();
trackerGroupDAO.addTraccarGroup(traccarId, id, tenantId);
GroupManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
GroupManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
} catch (TrackerManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping traccarGroupId with groupId .";
log.error(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
}
}
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Successfully the request is proceed and communicated with Traccar"); log.debug("Successfully the request is proceed and communicated with Traccar");
} }
@ -122,8 +173,42 @@ 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) throws TraccarConfigurationException { public void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException {
try{ 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);
}
}
/**
* Add Traccar Device operation.
* @param deviceInfo with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId
* Model, Contact, Category, fenceIds
* @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/
public void updateDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException {
try{
JSONObject payload = payload(deviceInfo);
String context = defaultPort+"/api/devices";
Runnable trackerExecutor = new TrackerExecutor(deviceInfo.getId(), tenantId, endpoint, context, payload,
TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.DEVICE);
executor.execute(trackerExecutor);
}catch (Exception e){
String msg="Could not enroll traccar device";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
}
}
private JSONObject payload(TraccarDevice deviceInfo){
JSONObject payload = new JSONObject(); JSONObject payload = new JSONObject();
payload.put("name", deviceInfo.getDeviceName()); payload.put("name", deviceInfo.getDeviceName());
payload.put("uniqueId", deviceInfo.getUniqueId()); payload.put("uniqueId", deviceInfo.getUniqueId());
@ -139,15 +224,7 @@ public class TrackerClient implements TraccarClient {
List<String> geoFenceIds = new ArrayList<>(); List<String> geoFenceIds = new ArrayList<>();
payload.put("geofenceIds", geoFenceIds); payload.put("geofenceIds", geoFenceIds);
payload.put("attributes", new JSONObject()); payload.put("attributes", new JSONObject());
String context = defaultPort+"/api/devices"; return payload;
Runnable trackerExecutor = new TrackerExecutor(endpoint, context, payload, "post");
executor.execute(trackerExecutor);
log.info("Device successfully enorolled on traccar");
}catch (Exception e){
String msg="Could not enroll traccar device";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
}
} }
/** /**
@ -159,7 +236,8 @@ public class TrackerClient implements TraccarClient {
String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"&timestamp="+deviceInfo.getTimestamp()+ String context = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+"&timestamp="+deviceInfo.getTimestamp()+
"&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+ "&lat="+deviceInfo.getLat()+"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+
"&speed="+deviceInfo.getSpeed()+"&ignition=true"; "&speed="+deviceInfo.getSpeed()+"&ignition=true";
Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); Runnable trackerExecutor = new TrackerExecutor(0, 0, endpoint, context, null,
TraccarHandlerConstants.Methods.GET, TraccarHandlerConstants.Types.DEVICE);
executor.execute(trackerExecutor); executor.execute(trackerExecutor);
log.info("Device GPS location added on traccar"); log.info("Device GPS location added on traccar");
}catch (Exception e){ }catch (Exception e){
@ -169,59 +247,22 @@ public class TrackerClient implements TraccarClient {
} }
} }
/**
* Add Device GPS Location operation.
* @param deviceId
* @return device info
* @throws TraccarConfigurationException Failed while add Traccar Device location operation
*/
@Override
public String getDeviceByDeviceIdentifier(String deviceId) throws TraccarConfigurationException {
try {
String context = defaultPort+"/api/devices?uniqueId="+ deviceId;
Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get");
executor.execute(trackerExecutor);
Request request = new Request.Builder()
.url(endpoint+context)
.addHeader(authorization, authorizationKey)
.build();
Response response = client.newCall(request).execute();
String result = response.body().string();
log.info("Device info found");
return result;
} catch (IOException e) {
String msg="Could not find device information";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
}
}
/** /**
* Dis-enroll a Device operation. * Dis-enroll a Device operation.
* @param deviceInfo identified via deviceIdentifier * @param traccarDeviceId identified via deviceIdentifier
* @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation * @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation
*/ */
public void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException { public void disEndrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException {
try{ try{
String result = getDeviceByDeviceIdentifier(deviceInfo.getDeviceIdentifier()); String context = defaultPort+"/api/devices/"+traccarDeviceId;
String jsonData ="{"+ "\"geodata\": "+ result+ "}"; Runnable trackerExecutor = new TrackerExecutor(traccarDeviceId, tenantId, endpoint, context, null,
TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.DEVICE);
JSONObject obj = new JSONObject(jsonData);
JSONArray geodata = obj.getJSONArray("geodata");
JSONObject jsonResponse = geodata.getJSONObject(0);
String context = defaultPort+"/api/devices/"+jsonResponse.getInt("id");
Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "delete");
executor.execute(trackerExecutor); executor.execute(trackerExecutor);
log.info("Device successfully dis-enrolled"); log.info("Device successfully dis-enrolled");
}catch (JSONException e){ }catch (JSONException e){
String msg = "Could not find the device information to dis-enroll the device"; String msg = "Could not find the device information to dis-enroll the device";
log.error(msg, e); log.error(msg, e);
throw new TraccarConfigurationException(msg); throw new TraccarConfigurationException(msg);
}catch (TraccarConfigurationException ex){
String msg = "Could not find the device information to dis-enroll the device";
log.error(msg, ex);
throw new TraccarConfigurationException(msg, ex);
} }
} }
@ -230,14 +271,15 @@ public class TrackerClient implements TraccarClient {
* @param groupInfo with groupName * @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) throws TraccarConfigurationException { public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException {
try{ try{
JSONObject payload = new JSONObject(); JSONObject payload = new JSONObject();
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"; String context = defaultPort+"/api/groups";
Runnable trackerExecutor = new TrackerExecutor(endpoint, context, payload, "post"); Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload,
TraccarHandlerConstants.Methods.POST, TraccarHandlerConstants.Types.GROUP);
executor.execute(trackerExecutor); executor.execute(trackerExecutor);
log.info("Group successfully added on traccar"); log.info("Group successfully added on traccar");
}catch (Exception e){ }catch (Exception e){
@ -248,25 +290,24 @@ public class TrackerClient implements TraccarClient {
} }
/** /**
* Add Device GPS Location operation. * Add Traccar Device operation.
* @return all groups * @param groupInfo with groupName
* @throws TraccarConfigurationException Failed while add Traccar Device location operation * @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/ */
@Override public void updateGroup(TraccarGroups groupInfo, int traccarGroupId, int groupId, int tenantId) throws TraccarConfigurationException {
public String getAllGroups() throws TraccarConfigurationException { try{
try { JSONObject payload = new JSONObject();
String context = defaultPort+"/api/groups?all=true"; payload.put("id", traccarGroupId);
Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "get"); payload.put("name", groupInfo.getName());
payload.put("attributes", new JSONObject());
String context = defaultPort+"/api/groups/"+traccarGroupId;
Runnable trackerExecutor = new TrackerExecutor(groupId, tenantId, endpoint, context, payload,
TraccarHandlerConstants.Methods.PUT, TraccarHandlerConstants.Types.GROUP);
executor.execute(trackerExecutor); executor.execute(trackerExecutor);
Request request = new Request.Builder() log.info("Group successfully updated on traccar");
.url(endpoint+context) }catch (Exception e){
.addHeader(authorization, authorizationKey) String msg="Could not update the traccar group";
.build();
Response response = client.newCall(request).execute();
String result = response.body().string();
return result;
} catch (IOException e) {
String msg="Could not find device information";
log.error(msg, e); log.error(msg, e);
throw new TraccarConfigurationException(msg, e); throw new TraccarConfigurationException(msg, e);
} }
@ -274,37 +315,19 @@ public class TrackerClient implements TraccarClient {
/** /**
* Add Traccar Device operation. * Add Traccar Device operation.
* @param groupInfo with groupName * @param traccarGroupId
* @throws TraccarConfigurationException Failed while add Traccar Device the operation * @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/ */
public void deleteGroup(TraccarGroups groupInfo) throws TraccarConfigurationException { public void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException {
try{ try{
String result = getAllGroups(); String context = defaultPort+"/api/groups/"+traccarGroupId;
String jsonData ="{"+ "\"groupdata\": "+ result+ "}"; Runnable trackerExecutor = new TrackerExecutor(traccarGroupId, tenantId, endpoint, context,
null, TraccarHandlerConstants.Methods.DELETE, TraccarHandlerConstants.Types.GROUP);
JSONObject obj = new JSONObject(jsonData);
JSONArray geodata = obj.getJSONArray("groupdata");
for(int i=0; i<geodata.length();i++){
JSONObject jsonResponse = geodata.getJSONObject(i);
log.info(jsonResponse.getString("name"));
log.info(jsonResponse.getInt("id"));
if(Objects.equals(jsonResponse.getString("name"), groupInfo.getName())){
String context = defaultPort+"/api/groups/"+jsonResponse.getInt("id");
Runnable trackerExecutor = new TrackerExecutor(endpoint, context, null, "delete");
executor.execute(trackerExecutor); executor.execute(trackerExecutor);
log.info("Traccar group successfully deleted");
break;
}
}
}catch (JSONException e){ }catch (JSONException e){
String msg = "Could not find the device information to dis-enroll the device"; String msg = "Could not find the device information to dis-enroll the device";
log.error(msg, e); log.error(msg, e);
throw new TraccarConfigurationException(msg); throw new TraccarConfigurationException(msg);
}catch (TraccarConfigurationException ex){
String msg = "Could not find the device information to dis-enroll the device";
log.error(msg, ex);
throw new TraccarConfigurationException(msg, ex);
} }
} }

@ -33,13 +33,22 @@ import java.util.Date;
public class TraccarAPIClientServiceImpl implements DeviceAPIClientService { public class TraccarAPIClientServiceImpl implements DeviceAPIClientService {
public void addDevice(Device device) throws TraccarConfigurationException { public void addDevice(Device device, int tenantId) throws TraccarConfigurationException {
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.getName(), device.getDeviceIdentifier(), TraccarDevice traccarDeviceInfo = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(),
"online", "false", lastUpdatedTime, "", "", "", "", "online", "false", lastUpdatedTime, "", "", "", "",
"", ""); "", "");
client.addDevice(traccarDeviceInfo); client.addDevice(traccarDeviceInfo, tenantId);
}
public void updateDevice(Device device, int tenantId) throws TraccarConfigurationException {
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);
} }
public void updateLocation(Device device, DeviceLocation deviceLocation) throws TraccarConfigurationException { public void updateLocation(Device device, DeviceLocation deviceLocation) throws TraccarConfigurationException {
@ -51,22 +60,26 @@ public class TraccarAPIClientServiceImpl implements DeviceAPIClientService {
client.updateLocation(traccarPosition); client.updateLocation(traccarPosition);
} }
public void disDevice(String deviceIdentifier) throws TraccarConfigurationException { public void disEndrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException {
TrackerClient client = new TrackerClient(); TrackerClient client = new TrackerClient();
TraccarDevice traccarDeviceInfo = new TraccarDevice(deviceIdentifier); client.disEndrollDevice(deviceId, tenantId);
client.disDevice(traccarDeviceInfo);
} }
public void addGroup(DeviceGroup group) throws TraccarConfigurationException { public void addGroup(DeviceGroup group, int groupId, int tenantId) throws TraccarConfigurationException {
TrackerClient client = new TrackerClient(); TrackerClient client = new TrackerClient();
TraccarGroups traccarGroups = new TraccarGroups(group.getName()); TraccarGroups traccarGroups = new TraccarGroups(group.getName());
client.addGroup(traccarGroups); client.addGroup(traccarGroups, groupId, tenantId);
} }
public void deleteGroup(DeviceGroup group) throws TraccarConfigurationException { public void updateGroup(DeviceGroup group, int traccarGroupId, int groupId, int tenantId) throws TraccarConfigurationException {
TrackerClient client = new TrackerClient(); TrackerClient client = new TrackerClient();
TraccarGroups traccarGroups = new TraccarGroups(group.getName()); TraccarGroups traccarGroups = new TraccarGroups(group.getName());
client.deleteGroup(traccarGroups); client.updateGroup(traccarGroups, traccarGroupId, groupId, tenantId);
}
public void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException {
TrackerClient client = new TrackerClient();
client.deleteGroup(traccarGroupId, tenantId);
} }
} }

@ -26,17 +26,16 @@ import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfiguratio
public interface TraccarClient { public interface TraccarClient {
void addDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException; void addDevice(TraccarDevice deviceInfo, int tenantId) throws TraccarConfigurationException;
void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException; void updateLocation(TraccarPosition deviceInfo) throws TraccarConfigurationException;
String getDeviceByDeviceIdentifier(String deviceId) throws TraccarConfigurationException; void disEndrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException;
void disDevice(TraccarDevice deviceInfo) throws TraccarConfigurationException; void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws TraccarConfigurationException;
void addGroup(TraccarGroups groupInfo) throws TraccarConfigurationException; void updateGroup(TraccarGroups groupInfo, int traccarGroupId, int groupId, int tenantId) throws TraccarConfigurationException;
void deleteGroup(TraccarGroups groupInfo) throws TraccarConfigurationException; void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException;
String getAllGroups() throws TraccarConfigurationException;
} }

@ -27,4 +27,27 @@ public class TraccarHandlerConstants {
public static final String AUTHORIZATION_KEY = "authorization-key"; public static final String AUTHORIZATION_KEY = "authorization-key";
public static final String DEFAULT_PORT = "default-port"; public static final String DEFAULT_PORT = "default-port";
public static final String LOCATION_UPDATE_PORT = "location-update-port"; public static final String LOCATION_UPDATE_PORT = "location-update-port";
public static class Methods {
public static final String POST = "POST";
public static final String GET = "GET";
public static final String PUT = "PUT";
public static final String DELETE = "DELETE";
}
public static class Types {
public static final String DEVICE = "DEVICE";
public static final String GROUP = "GROUP";
}
public static 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";
}
} }

@ -22,6 +22,7 @@ package org.wso2.carbon.device.mgt.core.traccar.common.beans;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
public class TraccarDevice { public class TraccarDevice {
private int id;
private String deviceIdentifier; private String deviceIdentifier;
private String deviceName; private String deviceName;
private String uniqueId; private String uniqueId;
@ -39,9 +40,10 @@ public class TraccarDevice {
this.deviceIdentifier =deviceIdentifier; this.deviceIdentifier =deviceIdentifier;
} }
public TraccarDevice(String deviceName, String uniqueId, String status, String disabled, String lastUpdate, public TraccarDevice(int id, String deviceName, String uniqueId, String status, String disabled, String lastUpdate,
String positionId, String groupId, String phone, String model, String contact, String positionId, String groupId, String phone, String model, String contact,
String category){ String category){
this.id =id;
this.deviceName =deviceName; this.deviceName =deviceName;
this.uniqueId=uniqueId; this.uniqueId=uniqueId;
this.status=status; this.status=status;
@ -57,6 +59,10 @@ public class TraccarDevice {
public TraccarDevice(){ } public TraccarDevice(){ }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getDeviceIdentifier() {return deviceIdentifier;} public String getDeviceIdentifier() {return deviceIdentifier;}
public void setDeviceIdentifier(String deviceIdentifier) {this.deviceIdentifier = deviceIdentifier;} public void setDeviceIdentifier(String deviceIdentifier) {this.deviceIdentifier = deviceIdentifier;}

@ -21,19 +21,30 @@ package org.wso2.carbon.device.mgt.core.traccar.common.beans;
public class TraccarGroups { public class TraccarGroups {
private String name; private String name;
private int groupId;
public TraccarGroups(String name){ public TraccarGroups(String name){
this.name =name; this.name =name;
} }
public TraccarGroups(){ } public TraccarGroups(String name, int groupId){
this.name =name;
this.groupId =groupId;
}
public TraccarGroups(){ }
public String getName() { public String getName() { return name; }
return name;
}
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
} }

@ -20,6 +20,7 @@
package org.wso2.carbon.device.mgt.core.traccar.common.beans; package org.wso2.carbon.device.mgt.core.traccar.common.beans;
public class TraccarPosition { public class TraccarPosition {
private int id;
private String deviceIdentifier; private String deviceIdentifier;
private Long timestamp; private Long timestamp;
private Double lat; private Double lat;
@ -27,6 +28,17 @@ public class TraccarPosition {
private Float bearing; private Float bearing;
private Float speed; private Float speed;
public TraccarPosition(int id, String deviceIdentifier, long timestamp, Double lat, Double lon,
float bearing, float speed){
this.id =id;
this.deviceIdentifier =deviceIdentifier;
this.timestamp=timestamp;
this.lat=lat;
this.lon =lon;
this.bearing =bearing;
this.speed =speed;
}
public TraccarPosition(String deviceIdentifier, long timestamp, Double lat, Double lon, public TraccarPosition(String deviceIdentifier, long timestamp, Double lat, Double lon,
float bearing, float speed){ float bearing, float speed){
this.deviceIdentifier =deviceIdentifier; this.deviceIdentifier =deviceIdentifier;
@ -39,6 +51,14 @@ public class TraccarPosition {
public TraccarPosition(){ } public TraccarPosition(){ }
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDeviceIdentifier() { public String getDeviceIdentifier() {
return deviceIdentifier; return deviceIdentifier;
} }
@ -86,5 +106,4 @@ public class TraccarPosition {
public void setSpeed(Float speed) { public void setSpeed(Float speed) {
this.speed = speed; this.speed = speed;
} }
} }

@ -34,6 +34,7 @@ public class HttpReportingUtil {
private static final Log log = LogFactory.getLog(HttpReportingUtil.class); private static final Log log = LogFactory.getLog(HttpReportingUtil.class);
private static final String IS_EVENT_PUBLISHING_ENABLED = "isEventPublishingEnabled"; private static final String IS_EVENT_PUBLISHING_ENABLED = "isEventPublishingEnabled";
private static final String IS_TRACKER_ENABLED = "isTrackerEnabled";
private static final String IS_LOCATION_PUBLISHING_ENABLED = "isLocationPublishingEnabled"; private static final String IS_LOCATION_PUBLISHING_ENABLED = "isLocationPublishingEnabled";
public static String getReportingHost() { public static String getReportingHost() {
@ -71,4 +72,12 @@ public class HttpReportingUtil {
} }
return false; return false;
} }
public static boolean isTrackerEnabled() {
Object configuration = DeviceManagerUtil.getConfiguration(IS_TRACKER_ENABLED);
if (configuration != null) {
return Boolean.valueOf(configuration.toString());
}
return false;
}
} }

Loading…
Cancel
Save