master
shamalka 2 years ago
parent d61814329c
commit 83be953583

@ -588,8 +588,8 @@ public interface DeviceManagementService {
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Getting Details of Registered Devices Owned by an Authenticated User", value = "Getting Details of Registered Devices Owned by an Authenticated User to generate token for Traccar",
notes = "Provides details of devices enrolled by authenticated users.", notes = "Provides details of devices enrolled by authenticated users to generate token for Traccar.",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {

@ -511,17 +511,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
status.add("INACTIVE"); status.add("INACTIVE");
status.add("CREATED"); status.add("CREATED");
status.add("UNREACHABLE"); status.add("UNREACHABLE");
boolean isStatusEmpty = true;
for (String statusString : status) {
if (StringUtils.isNotBlank(statusString)) {
isStatusEmpty = false;
break;
}
}
if (!isStatusEmpty) {
RequestValidationUtil.validateStatus(status);
request.setStatusList(status); request.setStatusList(status);
}
// this is the user who initiates the request // this is the user who initiates the request
String authorizedUser = MultitenantUtils.getTenantAwareUsername(currentUser); String authorizedUser = MultitenantUtils.getTenantAwareUsername(currentUser);
// check whether the user is device-mgt admin // check whether the user is device-mgt admin
@ -539,9 +529,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} }
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
for (int i = 0; i < devices.getCount(); i++) { for (Device device : devices.getList()) {
TrackerDeviceInfo trackerDevice = DeviceAPIClientServiceImpl.getTrackerDevice( TrackerDeviceInfo trackerDevice = DeviceAPIClientServiceImpl
devices.getList().get(i).getId(), tenantId); .getTrackerDevice(device.getId(), tenantId);
int traccarDeviceId = trackerDevice.getTraccarDeviceId(); int traccarDeviceId = trackerDevice.getTraccarDeviceId();
boolean getPermission = DeviceAPIClientServiceImpl.getUserIdofPermissionByDeviceIdNUserId(traccarDeviceId, userId); boolean getPermission = DeviceAPIClientServiceImpl.getUserIdofPermissionByDeviceIdNUserId(traccarDeviceId, userId);
traccarValidIdList.add(traccarDeviceId); traccarValidIdList.add(traccarDeviceId);
@ -549,7 +539,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
DeviceAPIClientServiceImpl.addTrackerUserDevicePermission(userId, traccarDeviceId); DeviceAPIClientServiceImpl.addTrackerUserDevicePermission(userId, traccarDeviceId);
} }
} }
//Remove neecessary //Remove necessary
List<TrackerPermissionInfo> getAllUserDevices = List<TrackerPermissionInfo> getAllUserDevices =
DeviceAPIClientServiceImpl.getUserIdofPermissionByUserIdNIdList(userId, traccarValidIdList); DeviceAPIClientServiceImpl.getUserIdofPermissionByUserIdNIdList(userId, traccarValidIdList);
for (TrackerPermissionInfo getAllUserDevice : getAllUserDevices) { for (TrackerPermissionInfo getAllUserDevice : getAllUserDevices) {
@ -558,10 +548,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
getAllUserDevice.getTraccarDeviceId(), getAllUserDevice.getTraccarDeviceId(),
TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE); TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE);
} }
} catch (JSONException e) {
String msg = "not a JSONObject. ";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while fetching all enrolled devices. "; String msg = "Error occurred while fetching all enrolled devices. ";
log.error(msg, e); log.error(msg, e);
@ -575,11 +561,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ExecutionException e) { } catch (ExecutionException e) {
String msg = "ExecutionException occurred "; String msg = "Execution error occurred handling traccar device permissions";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (InterruptedException e) { } catch (InterruptedException e) {
String msg = "InterruptedException occurred "; String msg = "Interruption error occurred handling traccar device permissions";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }

@ -22,7 +22,7 @@ import java.io.Serializable;
public class TrackerDeviceInfo implements Serializable { public class TrackerDeviceInfo implements Serializable {
private static final long serialVersionUID = 1998101712L; private static final long serialVersionUID = 11545107900391993L;
private int id; private int id;
private int traccarDeviceId; private int traccarDeviceId;

@ -22,7 +22,7 @@ import java.io.Serializable;
public class TrackerGroupInfo implements Serializable { public class TrackerGroupInfo implements Serializable {
private static final long serialVersionUID = 1998101712L; private static final long serialVersionUID = 2156646949297006690L;
private int id; private int id;
private int traccarGroupId; private int traccarGroupId;

@ -22,7 +22,7 @@ import java.io.Serializable;
public class TrackerPermissionInfo implements Serializable { public class TrackerPermissionInfo implements Serializable {
private static final long serialVersionUID = 1998101712L; private static final long serialVersionUID = -8648202903090812913L;
private int traccarUserId; private int traccarUserId;
private int traccarDeviceId; private int traccarDeviceId;

@ -26,7 +26,7 @@ import java.io.Serializable;
@ApiModel(value = "User", description = "This class carries all information related to a managed Traccar User.") @ApiModel(value = "User", description = "This class carries all information related to a managed Traccar User.")
public class TrackerUserInfo implements Serializable { public class TrackerUserInfo implements Serializable {
private static final long serialVersionUID = 1998101712L; private static final long serialVersionUID = -6808358733610879805L;
@ApiModelProperty(name = "userName", value = "The user's name that can be set on the device by the device user.", @ApiModelProperty(name = "userName", value = "The user's name that can be set on the device by the device user.",
required = true) required = true)

@ -23,7 +23,7 @@ package org.wso2.carbon.device.mgt.common.exceptions;
*/ */
public class TrackerAlreadyExistException extends Exception { public class TrackerAlreadyExistException extends Exception {
private static final long serialVersionUID = -312678379574816874L; private static final long serialVersionUID = 5241722939654800965L;
private String errorMessage; private String errorMessage;
public TrackerAlreadyExistException(String msg, Exception nestedEx) { public TrackerAlreadyExistException(String msg, Exception nestedEx) {

@ -34,7 +34,7 @@ public interface TrackerDAO {
* @return boolean value. * @return boolean value.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException; void addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException;
/** /**
* get trackerDevice info. * get trackerDevice info.
@ -51,10 +51,9 @@ public interface TrackerDAO {
* @param deviceId of the device. * @param deviceId of the device.
* @param tenantId of the group. * @param tenantId of the group.
* @param status of the device. * @param status of the device.
* @return boolean value.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException; void updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException;
/** /**
* Remove a Device. * Remove a Device.
@ -63,17 +62,16 @@ public interface TrackerDAO {
* @return sql execution result. * @return sql execution result.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
int removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException; void removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException;
/** /**
* Add new Group. * Add new Group.
* @param traccarGroupId to be added. * @param traccarGroupId to be added.
* @param groupId of the group. * @param groupId of the group.
* @param tenantId of the group. * @param tenantId of the group.
* @return boolean value.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException; void addTrackerGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException;
/** /**
* Update status and traccarGroupId of a Group. * Update status and traccarGroupId of a Group.

@ -41,7 +41,7 @@ public class TrackerDAOImpl implements TrackerDAO {
private static final Log log = LogFactory.getLog(TrackerDAOImpl.class); private static final Log log = LogFactory.getLog(TrackerDAOImpl.class);
@Override @Override
public Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) public void addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId)
throws TrackerManagementDAOException { throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
@ -52,8 +52,6 @@ public class TrackerDAOImpl implements TrackerDAO {
stmt.setInt(2, deviceId); stmt.setInt(2, deviceId);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.execute(); stmt.execute();
return true;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while adding on trackerDevice mapping table"; String msg = "Error occurred while adding on trackerDevice mapping table";
log.error(msg, e); log.error(msg, e);
@ -64,7 +62,7 @@ public class TrackerDAOImpl implements TrackerDAO {
} }
@Override @Override
public Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) public void updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status)
throws TrackerManagementDAOException { throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
@ -76,8 +74,6 @@ public class TrackerDAOImpl implements TrackerDAO {
stmt.setInt(3, deviceId); stmt.setInt(3, deviceId);
stmt.setInt(4, tenantId); stmt.setInt(4, tenantId);
stmt.execute(); stmt.execute();
return true;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while updating status on trackerDevice mapping table"; String msg = "Error occurred while updating status on trackerDevice mapping table";
log.error(msg, e); log.error(msg, e);
@ -88,10 +84,8 @@ public class TrackerDAOImpl implements TrackerDAO {
} }
@Override @Override
public int removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { public void removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null;
int status = -1;
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_EXT_DEVICE_MAPPING WHERE DEVICE_ID = ? AND TENANT_ID = ? "; String sql = "DELETE FROM DM_EXT_DEVICE_MAPPING WHERE DEVICE_ID = ? AND TENANT_ID = ? ";
@ -99,11 +93,6 @@ public class TrackerDAOImpl implements TrackerDAO {
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
status = 1;
}
return status;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while removing on trackerDevice table"; String msg = "Error occurred while removing on trackerDevice table";
log.error(msg, e); log.error(msg, e);
@ -117,7 +106,6 @@ public class TrackerDAOImpl implements TrackerDAO {
public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException { public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
TrackerDeviceInfo trackerDeviceInfo = null;
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "SELECT ID, TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID, STATUS FROM DM_EXT_DEVICE_MAPPING WHERE " + String sql = "SELECT ID, TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID, STATUS FROM DM_EXT_DEVICE_MAPPING WHERE " +
@ -127,9 +115,9 @@ public class TrackerDAOImpl implements TrackerDAO {
stmt.setInt(2, tenantId); stmt.setInt(2, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (rs.next()) { if (rs.next()) {
trackerDeviceInfo = TrackerManagementDAOUtil.loadTrackerDevice(rs); return TrackerManagementDAOUtil.loadTrackerDevice(rs);
} }
return trackerDeviceInfo; return null;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while retrieving data from the trackerDevice table "; String msg = "Error occurred while retrieving data from the trackerDevice table ";
log.error(msg, e); log.error(msg, e);
@ -140,10 +128,9 @@ public class TrackerDAOImpl implements TrackerDAO {
} }
@Override @Override
public Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId) public void addTrackerGroup(int traccarGroupId, int groupId, int tenantId)
throws TrackerManagementDAOException { throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
int status = 1;
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_EXT_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID, STATUS) VALUES(?, ?, ?, ?)"; String sql = "INSERT INTO DM_EXT_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID, STATUS) VALUES(?, ?, ?, ?)";
@ -151,10 +138,8 @@ public class TrackerDAOImpl implements TrackerDAO {
stmt.setInt(1, traccarGroupId); stmt.setInt(1, traccarGroupId);
stmt.setInt(2, groupId); stmt.setInt(2, groupId);
stmt.setInt(3, tenantId); stmt.setInt(3, tenantId);
stmt.setInt(4, status); stmt.setInt(4, 1);
stmt.execute(); stmt.execute();
return true;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while adding on traccarGroup mapping table"; String msg = "Error occurred while adding on traccarGroup mapping table";
log.error(msg, e); log.error(msg, e);
@ -268,6 +253,7 @@ public class TrackerDAOImpl implements TrackerDAO {
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_DEVICE_ID = ?"; String sql = "DELETE FROM DM_EXT_PERMISSION_MAPPING WHERE TRACCAR_DEVICE_ID = ?";
// TODO: Recheck the usage of below if condition
if (removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE) { if (removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE) {
sql = sql + " AND TRACCAR_USER_ID = ? "; sql = sql + " AND TRACCAR_USER_ID = ? ";
} }

@ -1,20 +1,3 @@
/*
* 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) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved. /* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* Entgra (pvt) Ltd. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,

@ -395,12 +395,19 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
} catch (ExecutionException e) { } catch (ExecutionException e) {
log.error("ExecutionException : " + e); log.error("ExecutionException : " + e);
//throw new RuntimeException(e); //throw new RuntimeException(e);
//Exception was not thrown due to being conflicted with non-traccar features
} catch (InterruptedException e) { } catch (InterruptedException e) {
log.error("InterruptedException : " + e); log.error("InterruptedException : " + e);
//throw new RuntimeException(e); //throw new RuntimeException(e);
//Exception was not thrown due to being conflicted with non-traccar features
} }
} else { } else {
log.info("location publishing is disabled and traccan disabled"); if(!HttpReportingUtil.isLocationPublishing()) {
log.info("Location publishing is disabled");
}
if (!HttpReportingUtil.isTrackerEnabled()) {
log.info("Traccar is disabled");
}
} }
//Tracker update GPS Location //Tracker update GPS Location

@ -441,6 +441,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
//throw new RuntimeException(e); //throw new RuntimeException(e);
//Exception was not thrown due to being conflicted with non-traccar features //Exception was not thrown due to being conflicted with non-traccar features
} }
} else {
log.info("Traccar is disabled");
} }
//enroll Traccar device //enroll Traccar device

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. * Copyright (C) 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
* *
* Unauthorised copying/redistribution of this file, via any medium is strictly prohibited. * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
* *
@ -120,7 +120,7 @@ public class TraccarClientImpl implements TraccarClient {
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 (Objects.equals(method, TraccarHandlerConstants.Methods.DELETE)) { } else if (Objects.equals(method, TraccarHandlerConstants.Methods.DELETE)) {
if (publisherUrlWithContext.indexOf("permission") != -1) { if (publisherUrlWithContext.contains("permission")) {
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.delete(requestBody); builder = builder.delete(requestBody);
} else { } else {
@ -141,8 +141,7 @@ public class TraccarClientImpl implements TraccarClient {
Future<String> result = executor.submit(new OkHttpClientThreadPool(url, null, method, Future<String> result = executor.submit(new OkHttpClientThreadPool(url, null, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer()))); serverUrl(HttpReportingUtil.trackerServer())));
String res = result.get(); return result.get();
return res;
} }
public String fetchUserInfo(String userName) throws ExecutionException, InterruptedException { public String fetchUserInfo(String userName) throws ExecutionException, InterruptedException {
@ -177,7 +176,7 @@ public class TraccarClientImpl implements TraccarClient {
if (Objects.equals(result, TraccarHandlerConstants.Types.USER_NOT_FOUND)) { if (Objects.equals(result, TraccarHandlerConstants.Types.USER_NOT_FOUND)) {
//create user //create user
log.info("Creating a user"); log.info("Creating a user on Traccar client");
traccarUser.setName(userName); traccarUser.setName(userName);
traccarUser.setLogin(userName); traccarUser.setLogin(userName);
traccarUser.setEmail(userName); traccarUser.setEmail(userName);
@ -188,7 +187,7 @@ public class TraccarClientImpl implements TraccarClient {
DeviceAPIClientServiceImpl.createUser(traccarUser); DeviceAPIClientServiceImpl.createUser(traccarUser);
} else { } else {
//update user //update user
log.info("Updating the user"); log.info("Updating the user on Traccar client");
JSONObject obj = new JSONObject(result); JSONObject obj = new JSONObject(result);
traccarUser.setId(obj.getInt("id")); traccarUser.setId(obj.getInt("id"));
@ -229,8 +228,7 @@ public class TraccarClientImpl implements TraccarClient {
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method, Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer()))); serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get(); return res.get();
return result;
} }
public String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException { public String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException {
@ -241,8 +239,7 @@ public class TraccarClientImpl implements TraccarClient {
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method, Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer()))); serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get(); return res.get();
return result;
} }
public void setPermission(int userId, int deviceId) public void setPermission(int userId, int deviceId)
@ -259,7 +256,7 @@ public class TraccarClientImpl implements TraccarClient {
serverUrl(HttpReportingUtil.trackerServer()))); serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get(); String result = res.get();
if (result.equals("")) { if (("").equals(result)) {
try { try {
TrackerManagementDAOFactory.beginTransaction(); TrackerManagementDAOFactory.beginTransaction();
trackerDAO.addTrackerUserDevicePermission(userId, deviceId); trackerDAO.addTrackerUserDevicePermission(userId, deviceId);
@ -294,9 +291,8 @@ public class TraccarClientImpl implements TraccarClient {
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method, Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer()))); serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
if (result != null) { if (res.get() != null) {
try { try {
TrackerManagementDAOFactory.beginTransaction(); TrackerManagementDAOFactory.beginTransaction();
trackerDAO.removeTrackerUserDevicePermission(deviceId, userId, removeType); trackerDAO.removeTrackerUserDevicePermission(deviceId, userId, removeType);
@ -386,11 +382,6 @@ public class TraccarClientImpl implements TraccarClient {
try { try {
TrackerManagementDAOFactory.openConnection(); TrackerManagementDAOFactory.openConnection();
trackerDeviceInfo = trackerDAO.getTrackerDevice(traccarDevice.getId(), tenantId); trackerDeviceInfo = trackerDAO.getTrackerDevice(traccarDevice.getId(), tenantId);
if (trackerDeviceInfo != null) {
String msg = "The device already exist";
log.error(msg);
throw new TrackerAlreadyExistException(msg);
}
} catch (TrackerManagementDAOException e) { } catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with deviceId ."; String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e); log.error(msg, e);
@ -405,11 +396,10 @@ public class TraccarClientImpl implements TraccarClient {
if (trackerDeviceInfo == null) { if (trackerDeviceInfo == null) {
//add the device //add the device
String method = TraccarHandlerConstants.Methods.POST;
String url = defaultPort + "/api/devices"; String url = defaultPort + "/api/devices";
JSONObject payload = TraccarUtil.TraccarDevicePayload(traccarDevice); JSONObject payload = TraccarUtil.TraccarDevicePayload(traccarDevice);
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()), authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer()))); serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get(); String result = res.get();
@ -423,7 +413,7 @@ public class TraccarClientImpl implements TraccarClient {
TrackerManagementDAOFactory.beginTransaction(); TrackerManagementDAOFactory.beginTransaction();
trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId);
trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId);
if (trackerDeviceInfo.getStatus() == 0) { if (trackerDeviceInfo != null && trackerDeviceInfo.getStatus() == 0) {
trackerDAO.updateTrackerDeviceIdANDStatus(trackerDeviceInfo.getTraccarDeviceId(), deviceId, tenantId, 1); trackerDAO.updateTrackerDeviceIdANDStatus(trackerDeviceInfo.getTraccarDeviceId(), deviceId, tenantId, 1);
} }
TrackerManagementDAOFactory.commitTransaction(); TrackerManagementDAOFactory.commitTransaction();
@ -445,6 +435,10 @@ public class TraccarClientImpl implements TraccarClient {
setPermission(returnUserInfo.getInt("id"), traccarDeviceId); setPermission(returnUserInfo.getInt("id"), traccarDeviceId);
} }
} }
} else {
String msg = "The device already exist";
log.error(msg);
throw new TrackerAlreadyExistException(msg);
} }
} }
@ -477,14 +471,15 @@ public class TraccarClientImpl implements TraccarClient {
addDevice(device, tenantId); addDevice(device, tenantId);
} else { } else {
//Update Location //Update Location
log.info("Updating Location"); if (log.isDebugEnabled()) {
String method = TraccarHandlerConstants.Methods.GET; log.info("Updating Location of the device: " + device.getId());
}
String url = locationUpdatePort + "/?id=" + deviceInfo.getDeviceIdentifier() + String url = locationUpdatePort + "/?id=" + deviceInfo.getDeviceIdentifier() +
"&timestamp=" + deviceInfo.getTimestamp() + "&lat=" + deviceInfo.getLat() + "&timestamp=" + deviceInfo.getTimestamp() + "&lat=" + deviceInfo.getLat() +
"&lon=" + deviceInfo.getLon() + "&bearing=" + deviceInfo.getBearing() + "&lon=" + deviceInfo.getLon() + "&bearing=" + deviceInfo.getBearing() +
"&speed=" + deviceInfo.getSpeed() + "&ignition=true"; "&speed=" + deviceInfo.getSpeed() + "&ignition=true";
executor.submit(new OkHttpClientThreadPool(url, null, method, executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.GET,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
"http://localhost:")); "http://localhost:"));
} }
@ -502,13 +497,10 @@ public class TraccarClientImpl implements TraccarClient {
try { try {
TrackerManagementDAOFactory.beginTransaction(); TrackerManagementDAOFactory.beginTransaction();
trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId);
log.info("deviceId - " + deviceId); log.info("deviceId - " + deviceId);
if (trackerDeviceInfo != null) { if (trackerDeviceInfo != null) {
int status = trackerDAO.removeTrackerDevice(deviceId, tenantId); trackerDAO.removeTrackerDevice(deviceId, tenantId);
log.info("Status" + status);
TrackerManagementDAOFactory.commitTransaction(); TrackerManagementDAOFactory.commitTransaction();
trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDeviceInfo.getTraccarDeviceId()); trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDeviceInfo.getTraccarDeviceId());
} }
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
@ -524,7 +516,7 @@ public class TraccarClientImpl implements TraccarClient {
} finally { } finally {
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
log.info("--------Disenrolling Device--------"); log.info("--------Disenrolling Device with device id " + deviceId + " from traccar client--------");
//Delete from traccar //Delete from traccar
if (trackerDeviceInfo != null) { if (trackerDeviceInfo != null) {
String method = TraccarHandlerConstants.Methods.DELETE; String method = TraccarHandlerConstants.Methods.DELETE;
@ -601,9 +593,9 @@ public class TraccarClientImpl implements TraccarClient {
trackerDAO.updateTrackerGroupIdANDStatus(trackerGroupInfo.getTraccarGroupId(), groupId, tenantId, 1); trackerDAO.updateTrackerGroupIdANDStatus(trackerGroupInfo.getTraccarGroupId(), groupId, tenantId, 1);
} }
} catch (TrackerManagementDAOException e) { } catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId. "; String msg = "Error occurred while mapping with deviceId. ";
log.error(msg, e); log.error(msg, e);
TrackerManagementDAOFactory.rollbackTransaction();
throw new TrackerManagementDAOException(msg, e); throw new TrackerManagementDAOException(msg, e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
String msg = "Error occurred establishing the DB connection. "; String msg = "Error occurred establishing the DB connection. ";
@ -614,10 +606,12 @@ public class TraccarClientImpl implements TraccarClient {
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
} else { } else {
log.error("Something went wrong_1: " + result); // TODO: Assumed the error message change if wrong
log.error("Response does not contains the key id: " + result);
} }
} else { } else {
log.error("Something went wrong_2: " + result); // TODO: Assumed the error message change if wrong
log.error("Response does not contains a JSON object " + result);
} }
} }
@ -636,9 +630,11 @@ public class TraccarClientImpl implements TraccarClient {
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred establishing the DB connection. "; String msg = "Error occurred establishing the DB connection. ";
log.error(msg, e); log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} catch (TrackerManagementDAOException e) { } catch (TrackerManagementDAOException e) {
String msg = "Could not find traccar group details. "; String msg = "Could not find traccar group details. ";
log.error(msg, e); log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally { } finally {
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
@ -699,10 +695,9 @@ public class TraccarClientImpl implements TraccarClient {
trackerDAO.removeTrackerGroup(obj.getInt("id")); trackerDAO.removeTrackerGroup(obj.getInt("id"));
TrackerManagementDAOFactory.commitTransaction(); TrackerManagementDAOFactory.commitTransaction();
String method = TraccarHandlerConstants.Methods.DELETE;
String url = defaultPort + "/api/groups/" + obj.getInt("traccarGroupId"); String url = defaultPort + "/api/groups/" + obj.getInt("traccarGroupId");
executor.submit(new OkHttpClientThreadPool(url, null, method, executor.submit(new OkHttpClientThreadPool(url, null, TraccarHandlerConstants.Methods.DELETE,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()), authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer()))); serverUrl(HttpReportingUtil.trackerServer())));
} }

@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved. * Copyright (C) 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
* *
* Unauthorised copying/redistribution of this file, via any medium is strictly prohibited. * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
* *

@ -31,6 +31,7 @@ public class TraccarHandlerConstants {
public static final String LOCATION_UPDATE_PORT = "location-update-port"; public static final String LOCATION_UPDATE_PORT = "location-update-port";
} }
// TODO: Get these from http client
public static class Methods { public static class Methods {
public static final String POST = "POST"; public static final String POST = "POST";
public static final String GET = "GET"; public static final String GET = "GET";

@ -23,7 +23,7 @@ import java.io.Serializable;
public class TraccarUser implements Serializable { public class TraccarUser implements Serializable {
private static final long serialVersionUID = 1998101712L; private static final long serialVersionUID = -1916365851689588289L;
private int id; private int id;
private String name; private String name;

@ -27,7 +27,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class TraccarUtil { public class TraccarUtil {
public static JSONObject TraccarUserPayload(TraccarUser traccarUser){ public static JSONObject TraccarUserPayload(TraccarUser traccarUser) {
JSONObject payload = new JSONObject(); JSONObject payload = new JSONObject();
JSONObject attribute = new JSONObject(); JSONObject attribute = new JSONObject();
attribute.put("speedUnit", "kmh"); attribute.put("speedUnit", "kmh");
@ -48,7 +48,7 @@ public class TraccarUtil {
return payload; return payload;
} }
public static JSONObject TraccarDevicePayload(TraccarDevice deviceInfo){ public static JSONObject TraccarDevicePayload(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());

Loading…
Cancel
Save