pull/5/head
shamalka 2 years ago
parent 90793b7130
commit f840ee97a8

@ -105,7 +105,7 @@ public interface DeviceDetailsDAO {
* @param deviceId - id of the device.
* @param enrollmentId - enrolment id of the device.
* @return - if device location exist
* @throws DeviceDetailsMgtDAOException
* @throws DeviceDetailsMgtDAOException if SQL error occurred while processing the query.
*/
boolean hasLocations(int deviceId, int enrollmentId) throws DeviceDetailsMgtDAOException;

@ -25,6 +25,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
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.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO;
@ -381,31 +382,23 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
@Override
public boolean hasLocations(int deviceId, int enrollmentId) throws
DeviceDetailsMgtDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
boolean hasLocation = false;
try {
conn = this.getConnection();
Connection conn = this.getConnection();
String sql = "SELECT DEVICE_ID FROM DM_DEVICE_LOCATION WHERE DEVICE_ID = ? AND ENROLMENT_ID = ? " +
"LIMIT 1";
stmt = conn.prepareStatement(sql);
ResultSet rs;
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, deviceId);
stmt.setInt(2, enrollmentId);
rs = stmt.executeQuery();
if (rs.next()) {
hasLocation = true;
return rs.next();
}
return hasLocation;
} catch (SQLException e) {
throw new DeviceDetailsMgtDAOException("Error occurred while fetching the location of the registered devices.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
String msg = "Error occurred while fetching the location of the registered devices.";
log.error(msg, e);
throw new DeviceDetailsMgtDAOException(msg, e);
}
}
}
@Override
public void deleteDeviceLocation(int deviceId, int enrollmentId) throws DeviceDetailsMgtDAOException {

@ -367,7 +367,6 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
if (previousLocation == null) {
deviceDetailsDAO.addDeviceLocation(deviceLocation, device.getEnrolmentInfo().getId());
} else {
log.info("Update location on IOTS");
deviceDetailsDAO.updateDeviceLocation(deviceLocation, device.getEnrolmentInfo().getId());
}
deviceDetailsDAO.addDeviceLocationInfo(device, deviceLocation,
@ -404,12 +403,16 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
}
} else {
if(!HttpReportingUtil.isLocationPublishing()) {
log.info("Location publishing is disabled");
if (log.isDebugEnabled()) {
log.debug("Location publishing is disabled");
}
}
if (!HttpReportingUtil.isTrackerEnabled()) {
if (log.isDebugEnabled()) {
log.info("Traccar is disabled");
}
}
}
//Tracker update GPS Location
DeviceManagementDAOFactory.commitTransaction();
@ -456,21 +459,25 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
} catch (ExecutionException e) {
log.error("ExecutionException : " + e);
//throw new RuntimeException(e);
//Exception was not thrown due to being conflicted with non-traccar features
// NOTE: Exception was not thrown due to being conflicted with non-traccar features
} catch (InterruptedException e) {
log.error("InterruptedException : " + e);
//throw new RuntimeException(e);
//Exception was not thrown due to being conflicted with non-traccar features
// NOTE: Exception was not thrown due to being conflicted with non-traccar features
}
} else {
if(!HttpReportingUtil.isLocationPublishing()) {
log.info("Location publishing is disabled");
if (log.isDebugEnabled()) {
log.debug("Location publishing is disabled");
}
}
if (!HttpReportingUtil.isTrackerEnabled()) {
if (log.isDebugEnabled()) {
log.info("Traccar is disabled");
}
}
}
}
DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {

@ -3980,13 +3980,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceLocation.setSpeed(Float.parseFloat(speed));
deviceLocation.setBearing(Float.parseFloat(bearing));
// deviceInformationManager.addDeviceLocation(device, deviceLocation);
log.info("--- Location Pushing to Traccar starts ---");
deviceInformationManager.addDeviceLocation(device, deviceLocation);
log.info("--- Location Pushing to Traccar end ---");
} catch (DeviceDetailsMgtException e) {
//We are not failing the execution since this is not critical for the functionality. But logging as
// a warning for reference.
//Exception was not thrown due to being conflicted with non-traccar features
/***
* NOTE:
* We are not failing the execution since this is not critical for the functionality. But logging as
* a warning for reference.
* Exception was not thrown due to being conflicted with non-traccar features
*/
log.warn("Error occurred while trying to add '" + device.getType() + "' device '" +
device.getDeviceIdentifier() + "' (id:'" + device.getId() + "') location (lat:" + latitude +
", lon:" + longitude + ", altitude: " + altitude +

@ -64,6 +64,8 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TraccarClientFactory {
@ -82,6 +84,9 @@ public class TraccarClientFactory {
final String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
private final TrackerDAO trackerDAO;
/**
* This is the private constructor method as this class is a singleton
*/
private TraccarClientFactory() {
client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
@ -92,6 +97,11 @@ public class TraccarClientFactory {
this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO();
}
/**
* This method is used to initiate a singleton instance of this class.
*
* @return TraccarClientFactory instance
*/
public static TraccarClientFactory getInstance() {
if(INSTANCE == null) {
INSTANCE = new TraccarClientFactory();
@ -144,10 +154,9 @@ public class TraccarClientFactory {
}
public String fetchAllUsers() throws ExecutionException, InterruptedException {
String method = TraccarHandlerConstants.Methods.GET;
String url = defaultPort + "/api/users";
Future<String> result = executor.submit(new OkHttpClientThreadPool(url, null, method,
Future<String> result = executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.GET,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
return result.get();
@ -191,7 +200,6 @@ public class TraccarClientFactory {
traccarUser.setEmail(userName);
traccarUser.setPassword(DeviceAPIClientServiceImpl.generateRandomString(TraccarHandlerConstants.Types.DEFAULT_RANDOM));
traccarUser.setDeviceLimit(-1);
//traccarUser.setUserLimit(-1);
traccarUser.setExpirationTime(tomorrow.toString());
DeviceAPIClientServiceImpl.createUser(traccarUser);
} else {
@ -217,7 +225,6 @@ public class TraccarClientFactory {
}
DeviceAPIClientServiceImpl.updateUser(traccarUser, obj.getInt("id"));
}
result = DeviceAPIClientServiceImpl.fetchUserInfo(userName);
return result;
} catch (InterruptedException | ExecutionException e) {
JSONObject obj = new JSONObject();
@ -230,22 +237,20 @@ public class TraccarClientFactory {
}
public String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException {
String method = TraccarHandlerConstants.Methods.POST;
String url = defaultPort + "/api/users";
JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser);
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, TraccarHandlerConstants.Methods.POST,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
return res.get();
}
public String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException {
String method = TraccarHandlerConstants.Methods.PUT;
String url = defaultPort + "/api/users/" + userId;
JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser);
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, TraccarHandlerConstants.Methods.PUT,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
return res.get();
@ -257,10 +262,9 @@ public class TraccarClientFactory {
payload.put("userId", userId);
payload.put("deviceId", deviceId);
String method = TraccarHandlerConstants.Methods.POST;
String url = defaultPort + "/api/permissions";
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, TraccarHandlerConstants.Methods.POST,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
@ -284,7 +288,9 @@ public class TraccarClientFactory {
TrackerManagementDAOFactory.closeConnection();
}
} else {
log.error("Couldn't add the permission record: " + result);
String msg = "Couldn't add the permission record: " + result;
log.error(msg);
throw new TrackerManagementDAOException(msg);
}
}
@ -294,10 +300,9 @@ public class TraccarClientFactory {
payload.put("userId", userId);
payload.put("deviceId", deviceId);
String method = TraccarHandlerConstants.Methods.DELETE;
String url = defaultPort + "/api/permissions";
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, TraccarHandlerConstants.Methods.DELETE,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
@ -319,6 +324,10 @@ public class TraccarClientFactory {
} finally {
TrackerManagementDAOFactory.closeConnection();
}
} else {
String msg = "Error occured while removing permission.";
log.error(msg);
throw new TrackerManagementDAOException(msg);
}
}
@ -328,7 +337,6 @@ public class TraccarClientFactory {
TrackerManagementDAOFactory.openConnection();
return trackerDAO.getUserIdofPermissionByUserIdNIdList(userId, NotInDeviceIdList);
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
@ -412,7 +420,7 @@ public class TraccarClientFactory {
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
log.info("---------result--------");
log.info("Device " + traccarDevice.getDeviceIdentifier() + " has been added to Traccar.");
if (res.isDone() && result.charAt(0) == '{') {
JSONObject obj = new JSONObject(result);
if (obj.has("id")) {
@ -508,36 +516,50 @@ public class TraccarClientFactory {
List<TrackerPermissionInfo> trackerPermissionInfo = null;
try {
TrackerManagementDAOFactory.beginTransaction();
try {
TrackerManagementDAOFactory.openConnection();
trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId);
log.info("deviceId - " + deviceId);
if (trackerDeviceInfo != null) {
trackerDAO.removeTrackerDevice(deviceId, tenantId);
TrackerManagementDAOFactory.commitTransaction();
trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDeviceInfo.getTraccarDeviceId());
} else {
String msg = "Tracker device for device id " + deviceId + " not found";
log.error(msg);
throw new TrackerManagementDAOException(msg);
}
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection";
} catch (SQLException e) {
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId";
String msg = "Could not add new device location";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
log.info("--------Disenrolling Device with device id " + deviceId + " from traccar client--------");
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
}
log.info("Disenrolling Device with device id " + deviceId + " from traccar client");
//Delete from traccar
if (trackerDeviceInfo != null) {
String method = TraccarHandlerConstants.Methods.DELETE;
if (trackerPermissionInfo.size() > 0) {
String url = defaultPort + "/api/devices/" + trackerPermissionInfo.get(0).getTraccarDeviceId();
executor.submit(new OkHttpClientThreadPool(url, null, method,
executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.DELETE,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
} else {
String msg = "Tracker permission mapping info not found";
log.error(msg);
throw new TrackerManagementDAOException(msg);
}
//remove permissions
try {
removePermission(
@ -545,9 +567,14 @@ public class TraccarClientFactory {
trackerPermissionInfo.get(0).getTraccarDeviceId(),
TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE);
} catch (ExecutionException e) {
log.error("ExecutionException : " + e);
throw new ExecutionException(e);
String msg = "Error occured while removing tacker permissions ";
log.error(msg);
throw new ExecutionException(msg, e);
}
} else {
String msg = "Tracker device not found";
log.error(msg);
throw new TrackerManagementDAOException(msg);
}
}
@ -584,36 +611,35 @@ public class TraccarClientFactory {
payload.put("name", groupInfo.getName());
payload.put("attributes", new JSONObject());
String method = TraccarHandlerConstants.Methods.POST;
String url = defaultPort + "/api/groups";
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, TraccarHandlerConstants.Methods.POST,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
log.info("---------result--------");
log.info("Group " + trackerGroupInfo.getGroupId() + " has been added to Traccar.");
if (res.isDone() && result.charAt(0) == '{') {
JSONObject obj = new JSONObject(result);
if (obj.has("id")) {
int traccarGroupId = obj.getInt("id");
try {
TrackerManagementDAOFactory.beginTransaction();
trackerDAO.addTrackerGroup(traccarGroupId, groupId, tenantId);
trackerGroupInfo = trackerDAO.getTrackerGroup(groupId, tenantId);
if (trackerGroupInfo.getStatus() == 0) {
trackerDAO.updateTrackerGroupIdANDStatus(trackerGroupInfo.getTraccarGroupId(), groupId, tenantId, 1);
TrackerManagementDAOFactory.commitTransaction();
}
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId. ";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred establishing the DB connection. ";
log.error(msg, e);
TrackerManagementDAOFactory.rollbackTransaction();
throw new TrackerManagementDAOException(msg, e);
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId. ";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
@ -680,10 +706,9 @@ public class TraccarClientFactory {
payload.put("name", groupInfo.getName());
payload.put("attributes", new JSONObject());
String method = TraccarHandlerConstants.Methods.PUT;
String url = defaultPort + "/api/groups/" + obj.getInt("traccarGroupId");
executor.submit(new OkHttpClientThreadPool(url, payload, method,
executor.submit(new OkHttpClientThreadPool(url, payload, TraccarHandlerConstants.Methods.PUT,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
}
@ -705,14 +730,20 @@ public class TraccarClientFactory {
obj = new JSONObject(res);
if (obj != null) {
trackerDAO.removeTrackerGroup(obj.getInt("id"));
TrackerManagementDAOFactory.commitTransaction();
String url = defaultPort + "/api/groups/" + obj.getInt("traccarGroupId");
executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.DELETE,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
TrackerManagementDAOFactory.commitTransaction();
} else {
String msg = "Tracker group JSON object is null";
log.error(msg);
throw new TrackerManagementDAOException(msg);
}
} else {
String msg = "Tracker group not found";
log.error(msg);
throw new TrackerManagementDAOException(msg);
}
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
@ -732,10 +763,7 @@ public class TraccarClientFactory {
public String generateRandomString(int len) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(chars.charAt(rnd.nextInt(chars.length())));
return sb.toString();
return IntStream.range(0, len).mapToObj(i -> String.valueOf(chars.charAt(rnd.nextInt(chars.length())))).collect(Collectors.joining());
}
private TraccarGateway getTraccarGateway() {
@ -756,10 +784,10 @@ public class TraccarClientFactory {
}
public String serverUrl(String serverUrl) {
String newServerUri = endpoint;
if (serverUrl != null) {
newServerUri = serverUrl;
return serverUrl;
} else {
return endpoint;
}
return newServerUri;
}
}

@ -403,7 +403,7 @@ public class TraccarClientImpl implements TraccarClient {
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
log.info("---------result--------");
log.info("Device " + traccarDevice.getDeviceIdentifier() + " has been added to Traccar.");
if (result.charAt(0) == '{') {
JSONObject obj = new JSONObject(result);
if (obj.has("id")) {
@ -582,7 +582,7 @@ public class TraccarClientImpl implements TraccarClient {
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
log.info("---------result--------");
log.info("Group " + trackerGroupInfo.getGroupId() + " has been added to Traccar.");
if (res.isDone() && result.charAt(0) == '{') {
JSONObject obj = new JSONObject(result);
if (obj.has("id")) {

Loading…
Cancel
Save