fix removing permission and organizing the code

feature/traccar-sync
Rushdi Mohamed 3 years ago
parent 83651efcb5
commit f4d0050270

@ -42,6 +42,7 @@ import org.apache.commons.httpclient.HttpStatus;
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.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
@ -61,6 +62,8 @@ 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.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo;
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.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
@ -88,6 +91,7 @@ import org.wso2.carbon.device.mgt.common.search.PropertyMap;
import org.wso2.carbon.device.mgt.common.search.SearchContext; import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus; import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
@ -99,6 +103,7 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl; import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
@ -133,6 +138,11 @@ import java.sql.Timestamp;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
@Path("/devices") @Path("/devices")
public class DeviceManagementServiceImpl implements DeviceManagementService { public class DeviceManagementServiceImpl implements DeviceManagementService {
@ -475,12 +485,98 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser)); JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser));
log.info("=================");
log.info(obj.toString());
log.info("==================");
if(obj.has("error")){ if(obj.has("error")){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build();
}else{ }else{
int userId = obj.getInt("id");
List<Integer> traccarValidIdList = new ArrayList<>();
/*Get Device Id List*/
try {
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
DeviceMgtAPIUtils.getDeviceAccessAuthorizationService();
PaginationRequest request = new PaginationRequest(0, 0);
PaginationResult result;
DeviceList devices = new DeviceList();
List<String> status = new ArrayList<>();
status.add("ACTIVE");
status.add("INACTIVE");
status.add("CREATED");
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);
}
// this is the user who initiates the request
String authorizedUser = MultitenantUtils.getTenantAwareUsername(currentUser);
// check whether the user is device-mgt admin
if (!deviceAccessAuthorizationService.isDeviceAdminUser()) {
request.setOwner(authorizedUser);
}
result = dms.getAllDevicesIds(request);
if (result == null || result.getData() == null || result.getData().isEmpty()) {
devices.setList(new ArrayList<Device>());
devices.setCount(0);
}else{
devices.setList((List<Device>) result.getData());
devices.setCount(result.getRecordsTotal());
}
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
for(int i=0; i<devices.getCount(); i++){
TrackerDeviceInfo trackerDevice = DeviceAPIClientServiceImpl.getTrackerDevice(
devices.getList().get(i).getId(), tenantId);
int traccarDeviceId = trackerDevice.getTraccarDeviceId();
boolean getPermission = DeviceAPIClientServiceImpl.getUserIdofPermissionByDeviceIdNUserId(traccarDeviceId, userId);
log.info("--------------------");
log.info(getPermission);
log.info(traccarDeviceId);
log.info(userId);
log.info("--------------------");
traccarValidIdList.add(traccarDeviceId);
if(!getPermission){
DeviceAPIClientServiceImpl.addTrackerUserDevicePermission(userId, traccarDeviceId);
}
}
//Remove neecessary
List<TrackerPermissionInfo> getAllUserDevices =
DeviceAPIClientServiceImpl.getUserIdofPermissionByUserIdNIdList(userId, traccarValidIdList);
for (TrackerPermissionInfo getAllUserDevice : getAllUserDevices) {
DeviceAPIClientServiceImpl.removeTrackerUserDevicePermission(
getAllUserDevice.getTraccarUserId(),
getAllUserDevice.getTraccarDeviceId(),
TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE);
}
} catch (JSONException e){
String msg = "not a JSONObject, ";
log.error(msg);
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching all enrolled devices";
log.error(msg, e);
} catch (DeviceAccessAuthorizationException e) {
String msg = "Error occurred while checking device access authorization";
log.error(msg, e);
} catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
} catch (ExecutionException e) {
log.error("ExecutionException : " + e);
} catch (InterruptedException e) {
log.error("InterruptedException : " + e);
}
/*Get Device Id List*/
return Response.status(Response.Status.OK).entity(obj.getString("token")).build(); return Response.status(Response.Status.OK).entity(obj.getString("token")).build();
} }
}else{ }else{

@ -129,6 +129,10 @@ public class Device implements Serializable {
this.deviceStatusInfo = deviceStatusInfo; this.deviceStatusInfo = deviceStatusInfo;
} }
public Device(String deviceId) {
this.deviceIdentifier = deviceId;
}
public int getId() { public int getId() {
return id; return id;
} }

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@ -14,8 +14,8 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*
*/ */
package org.wso2.carbon.device.mgt.common; package org.wso2.carbon.device.mgt.common;
import java.io.Serializable; import java.io.Serializable;

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@ -14,8 +14,8 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*
*/ */
package org.wso2.carbon.device.mgt.common; package org.wso2.carbon.device.mgt.common;
import java.io.Serializable; import java.io.Serializable;

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@ -14,8 +14,8 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*
*/ */
package org.wso2.carbon.device.mgt.common; package org.wso2.carbon.device.mgt.common;
import java.io.Serializable; import java.io.Serializable;

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@ -14,8 +14,8 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*
*/ */
package org.wso2.carbon.device.mgt.common; package org.wso2.carbon.device.mgt.common;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
/* /*
* Copyright (c) 2020, 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,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -301,6 +301,16 @@ public interface DeviceDAO {
*/ */
List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException; List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException;
/**
* This method is used to retrieve the devices of a given tenant as a paginated result.
*
* @param request PaginationRequest object holding the data for pagination
* @param tenantId tenant id.
* @return returns paginated list of devices.
* @throws DeviceManagementDAOException
*/
List<Device> getDevicesIds(PaginationRequest request, int tenantId) throws DeviceManagementDAOException;
/** /**
* This method is used to retrieve the devices of a given tenant as a paginated result, along the lines of * This method is used to retrieve the devices of a given tenant as a paginated result, along the lines of
* activeServerCount and serverIndex * activeServerCount and serverIndex

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@ -14,14 +14,16 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*
*/ */
package org.wso2.carbon.device.mgt.core.dao; package org.wso2.carbon.device.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerGroupInfo; import org.wso2.carbon.device.mgt.common.TrackerGroupInfo;
import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo; import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo;
import java.util.List;
public interface TrackerDAO { public interface TrackerDAO {
/** /**
@ -36,12 +38,12 @@ public interface TrackerDAO {
/** /**
* get trackerDevice info. * get trackerDevice info.
* @param groupId of the device. * @param deviceId of the device.
* @param tenantId of the group. * @param tenantId of the group.
* @return Tracker Device Info. * @return Tracker Device Info.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
TrackerDeviceInfo getTrackerDevice(int groupId, int tenantId) throws TrackerManagementDAOException; TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException;
/** /**
* update trackerDevice status and traccarDeviceId. * update trackerDevice status and traccarDeviceId.
@ -49,7 +51,7 @@ 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 Tracker Device Info. * @return boolean value.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException; Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException;
@ -86,35 +88,61 @@ public interface TrackerDAO {
/** /**
* Remove a Group. * Remove a Group.
* @param id mapping table. * @param id of groups.
* @return boolean value.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
int removeTrackerGroup(int id) throws TrackerManagementDAOException; int removeTrackerGroup(int id) throws TrackerManagementDAOException;
/**
* get trackerGroup info.
* @param groupId of the device.
* @param tenantId of the group.
* @return Tracker Device Info.
* @throws TrackerManagementDAOException
*/
TrackerGroupInfo getTrackerGroup(int groupId, int tenantId) throws TrackerManagementDAOException;
/** /**
* give permission to a user to view traccar device. * give permission to a user to view traccar device.
* @param traccarUserId mapping table. * @param traccarUserId mapping table.
* @param deviceId mapping table. * @param deviceId mapping table.
* @return boolean value.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException; Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException;
/** /**
* Remove a permission on viewing a device. * Remove a permission on viewing a device.
* @param deviceId mapping table. * @param deviceId of permissions.
* @return boolean value.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
Boolean removeTrackerUserDevicePermission(int deviceId) throws TrackerManagementDAOException; Boolean removeTrackerUserDevicePermission(int deviceId, int userId, int removeType) throws TrackerManagementDAOException;
TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException; /**
* get list of userDevicePermissions by.
* @param deviceId of permissions.
* @return Tracker Permission Info.
* @throws TrackerManagementDAOException
*/
List<TrackerPermissionInfo> getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException;
/**
* get list of userDevicePermissions by.
* @param userId of permissions.
* @param NotInDeviceIdList list of permissions.
* @return Tracker Permission Info.
* @throws TrackerManagementDAOException
*/
List<TrackerPermissionInfo> getUserIdofPermissionByUserIdNIdList(int userId, List<Integer> NotInDeviceIdList) throws TrackerManagementDAOException;
/** /**
* get trackerGroup info. * get list of userDevicePermissions by.
* @param groupId of the device. * @param deviceId of permissions.
* @param tenantId of the group. * @param userId of permissions.
* @return Tracker Device Info. * @return Tracker Permission Info.
* @throws TrackerManagementDAOException * @throws TrackerManagementDAOException
*/ */
TrackerGroupInfo getTrackerGroup(int groupId, int tenantId) throws TrackerManagementDAOException; Boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException;
} }

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@ -10,8 +10,8 @@
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */

@ -188,6 +188,7 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
//Return only not removed id list
@Override @Override
public List<Device> getDeviceListWithoutPagination(int tenantId) public List<Device> getDeviceListWithoutPagination(int tenantId)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
@ -217,7 +218,82 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
@Override @Override
public List<Device> getAllocatedDevices(PaginationRequest request, int tenantId, int activeServerCount, int serverIndex) public List<Device> getDevicesIds(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
List<Device> devices = null;
String owner = request.getOwner();
boolean isOwnerProvided = false;
String ownership = request.getOwnership();
boolean isOwnershipProvided = false;
List<String> statusList = request.getStatusList();
boolean isStatusProvided = false;
try {
conn = getConnection();
String sql = "SELECT " +
"d1.ID AS DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.STATUS, " +
"e.OWNER, " +
"e.IS_TRANSFERRED, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT d.ID, " +
"d.DEVICE_IDENTIFICATION " +
"FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " +
"WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? ";
//Add the query for ownership
if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
//Add the query for owner
if (owner != null && !owner.isEmpty()) {
sql = sql + " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
}
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership);
}
if (isOwnerProvided) {
stmt.setString(paramIdx++, owner);
}
if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
}
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDeviceIds(rs);
devices.add(device);
}
return devices;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override
public List<Device> getAllocatedDevices(PaginationRequest request, int tenantId,
int activeServerCount, int serverIndex)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
List<Device> devices; List<Device> devices;
String deviceType = request.getDeviceType(); String deviceType = request.getDeviceType();

@ -188,6 +188,81 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
//Return only not removed id list
@Override
public List<Device> getDevicesIds(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
List<Device> devices = null;
String owner = request.getOwner();
boolean isOwnerProvided = false;
String ownership = request.getOwnership();
boolean isOwnershipProvided = false;
List<String> statusList = request.getStatusList();
boolean isStatusProvided = false;
try {
conn = getConnection();
String sql = "SELECT " +
"d1.ID AS DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.STATUS, " +
"e.OWNER, " +
"e.IS_TRANSFERRED, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT d.ID, " +
"d.DEVICE_IDENTIFICATION " +
"FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " +
"WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? ";
//Add the query for ownership
if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
//Add the query for owner
if (owner != null && !owner.isEmpty()) {
sql = sql + " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
}
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership);
}
if (isOwnerProvided) {
stmt.setString(paramIdx++, owner);
}
if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
}
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDeviceIds(rs);
devices.add(device);
}
return devices;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override @Override
public List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { public List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException {
return null; return null;

@ -179,6 +179,81 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
//Return only not removed id list
@Override
public List<Device> getDevicesIds(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
List<Device> devices = null;
String owner = request.getOwner();
boolean isOwnerProvided = false;
String ownership = request.getOwnership();
boolean isOwnershipProvided = false;
List<String> statusList = request.getStatusList();
boolean isStatusProvided = false;
try {
conn = getConnection();
String sql = "SELECT " +
"d1.ID AS DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.STATUS, " +
"e.OWNER, " +
"e.IS_TRANSFERRED, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT d.ID, " +
"d.DEVICE_IDENTIFICATION " +
"FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " +
"WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? ";
//Add the query for ownership
if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
//Add the query for owner
if (owner != null && !owner.isEmpty()) {
sql = sql + " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
}
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership);
}
if (isOwnerProvided) {
stmt.setString(paramIdx++, owner);
}
if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
}
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDeviceIds(rs);
devices.add(device);
}
return devices;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override @Override
public List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { public List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException {
return null; return null;

@ -189,6 +189,81 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
//Return only not removed id list
@Override
public List<Device> getDevicesIds(PaginationRequest request, int tenantId)
throws DeviceManagementDAOException {
Connection conn;
List<Device> devices = null;
String owner = request.getOwner();
boolean isOwnerProvided = false;
String ownership = request.getOwnership();
boolean isOwnershipProvided = false;
List<String> statusList = request.getStatusList();
boolean isStatusProvided = false;
try {
conn = getConnection();
String sql = "SELECT " +
"d1.ID AS DEVICE_ID, " +
"d1.DEVICE_IDENTIFICATION, " +
"e.STATUS, " +
"e.OWNER, " +
"e.IS_TRANSFERRED, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT d.ID, " +
"d.DEVICE_IDENTIFICATION " +
"FROM DM_DEVICE d WHERE d.TENANT_ID = ?) d1 " +
"WHERE d1.ID = e.DEVICE_ID AND e.TENANT_ID = ? ";
//Add the query for ownership
if (ownership != null && !ownership.isEmpty()) {
sql = sql + " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
//Add the query for owner
if (owner != null && !owner.isEmpty()) {
sql = sql + " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (statusList != null && !statusList.isEmpty()) {
sql += buildStatusQuery(statusList);
isStatusProvided = true;
}
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1;
stmt.setInt(paramIdx++, tenantId);
stmt.setInt(paramIdx++, tenantId);
if (isOwnershipProvided) {
stmt.setString(paramIdx++, ownership);
}
if (isOwnerProvided) {
stmt.setString(paramIdx++, owner);
}
if (isStatusProvided) {
for (String status : statusList) {
stmt.setString(paramIdx++, status);
}
}
try (ResultSet rs = stmt.executeQuery()) {
devices = new ArrayList<>();
while (rs.next()) {
Device device = DeviceManagementDAOUtil.loadDeviceIds(rs);
devices.add(device);
}
return devices;
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving information of all " +
"registered devices";
log.error(msg, e);
throw new DeviceManagementDAOException(msg, e);
}
}
@Override @Override
public List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException { public List<Device> getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException {
return null; return null;

@ -1,7 +1,7 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@ -14,8 +14,8 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*
*/ */
package org.wso2.carbon.device.mgt.core.dao.impl.tracker; package org.wso2.carbon.device.mgt.core.dao.impl.tracker;
import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo; import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
@ -25,16 +25,20 @@ import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.TrackerDAO; import org.wso2.carbon.device.mgt.core.dao.TrackerDAO;
import org.wso2.carbon.device.mgt.core.dao.util.TrackerManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.TrackerManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class TrackerDAOImpl implements TrackerDAO { public class TrackerDAOImpl implements TrackerDAO {
@Override @Override
public Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException { public Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId)
throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
@ -47,14 +51,15 @@ public class TrackerDAOImpl implements TrackerDAO {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while adding traccar device mapping", e); throw new TrackerManagementDAOException("Error occurred while adding on trackerDevice mapping table", e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@Override @Override
public Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException { public Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status)
throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
@ -68,7 +73,7 @@ public class TrackerDAOImpl implements TrackerDAO {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while updating trackerDevice mapping table"; String msg = "Error occurred while updating status on trackerDevice mapping table";
throw new TrackerManagementDAOException(msg, e); throw new TrackerManagementDAOException(msg, e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
@ -93,7 +98,7 @@ public class TrackerDAOImpl implements TrackerDAO {
} }
return status; return status;
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while removing trackerDevice", e); throw new TrackerManagementDAOException("Error occurred while removing on trackerDevice table", e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -113,18 +118,19 @@ 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 = this.loadTrackerDevice(rs); trackerDeviceInfo = TrackerManagementDAOUtil.loadTrackerDevice(rs);
} }
return trackerDeviceInfo; return trackerDeviceInfo;
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while retrieving the trackerDevice information ", e); throw new TrackerManagementDAOException("Error occurred while retrieving data from the trackerDevice table ", e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, rs); TrackerManagementDAOUtil.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException { public Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId)
throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
int status = 1 ; int status = 1 ;
try { try {
@ -139,7 +145,7 @@ public class TrackerDAOImpl implements TrackerDAO {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while adding traccar group mapping"; String msg = "Error occurred while adding on traccarGroup mapping table";
throw new TrackerManagementDAOException(msg, e); throw new TrackerManagementDAOException(msg, e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
@ -147,7 +153,8 @@ public class TrackerDAOImpl implements TrackerDAO {
} }
@Override @Override
public Boolean updateTrackerGroupIdANDStatus(int traccarGroupId, int groupId, int tenantId, int status) throws TrackerManagementDAOException { public Boolean updateTrackerGroupIdANDStatus(int traccarGroupId, int groupId, int tenantId, int status)
throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
@ -161,7 +168,7 @@ public class TrackerDAOImpl implements TrackerDAO {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
String msg = "Error occurred while updating traccar group mapping table"; String msg = "Error occurred while updating status on traccarGroup mapping table";
throw new TrackerManagementDAOException(msg, e); throw new TrackerManagementDAOException(msg, e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
@ -185,7 +192,7 @@ public class TrackerDAOImpl implements TrackerDAO {
} }
return status; return status;
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while removing traccar group", e); throw new TrackerManagementDAOException("Error occurred while removing from traccarGroup mapping table", e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
@ -205,18 +212,19 @@ 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()) {
trackerGroupInfo = this.loadTrackerGroup(rs); trackerGroupInfo = TrackerManagementDAOUtil.loadTrackerGroup(rs);
} }
return trackerGroupInfo; return trackerGroupInfo;
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); throw new TrackerManagementDAOException("Error occurred while retrieving data from the traccarGroup mapping table ", e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, rs); TrackerManagementDAOUtil.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException { public Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId)
throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
@ -228,78 +236,121 @@ public class TrackerDAOImpl implements TrackerDAO {
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while adding traccar user device mapping", e); throw new TrackerManagementDAOException("Error occurred while adding permission on permissions mapping table", e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@Override @Override
public Boolean removeTrackerUserDevicePermission(int deviceId) throws TrackerManagementDAOException { public Boolean removeTrackerUserDevicePermission(int deviceId, int userId, int removeType)
throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
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 = ?";
if(removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE){
sql = sql + " AND TRACCAR_USER_ID = ? ";
}
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
if(removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE){
stmt.setInt(2, userId);
}
stmt.execute(); stmt.execute();
return true; return true;
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while removing traccar user device permission mapping", e); throw new TrackerManagementDAOException("Error occurred while removing permission from permissions mapping table", e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null); TrackerManagementDAOUtil.cleanupResources(stmt, null);
} }
} }
@Override @Override
public TrackerPermissionInfo getUserIdofPermissionByDeviceId(int deviceId) throws TrackerManagementDAOException { public List<TrackerPermissionInfo> getUserIdofPermissionByDeviceId(int deviceId)
throws TrackerManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
TrackerPermissionInfo trackerPermissionInfo = null; List<TrackerPermissionInfo> trackerPermissionInfo = null;
try { try {
Connection conn = TrackerManagementDAOFactory.getConnection(); Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " + String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " +
"TRACCAR_DEVICE_ID = ? ORDER BY TRACCAR_DEVICE_ID DESC LIMIT 1"; "TRACCAR_DEVICE_ID = ? ORDER BY TRACCAR_DEVICE_ID ASC";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId); stmt.setInt(1, deviceId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (rs.next()) { trackerPermissionInfo = new ArrayList<>();
trackerPermissionInfo = this.loadPermission(rs); while (rs.next()) {
TrackerPermissionInfo loadPermission = TrackerManagementDAOUtil.loadPermission(rs);
trackerPermissionInfo.add(loadPermission);
} }
return trackerPermissionInfo; return trackerPermissionInfo;
} catch (SQLException e) { } catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while retrieving the traccar group information ", e); throw new TrackerManagementDAOException("Error occurred while retrieving permissions data from permissions mapping table ", e);
} finally { } finally {
TrackerManagementDAOUtil.cleanupResources(stmt, rs); TrackerManagementDAOUtil.cleanupResources(stmt, rs);
} }
} }
@Override
private TrackerGroupInfo loadTrackerGroup(ResultSet rs) throws SQLException { public List<TrackerPermissionInfo> getUserIdofPermissionByUserIdNIdList(int userId, List<Integer> NotInDeviceIdList)
TrackerGroupInfo trackerGroupInfo = new TrackerGroupInfo(); throws TrackerManagementDAOException {
trackerGroupInfo.setId(rs.getInt("ID")); PreparedStatement stmt = null;
trackerGroupInfo.setTraccarGroupId(rs.getInt("TRACCAR_GROUP_ID")); ResultSet rs = null;
trackerGroupInfo.setGroupId(rs.getInt("GROUP_ID")); List<TrackerPermissionInfo> trackerPermissionInfo = null;
trackerGroupInfo.setTenantId(rs.getInt("TENANT_ID")); try {
trackerGroupInfo.setStatus(rs.getInt("STATUS")); Connection conn = TrackerManagementDAOFactory.getConnection();
return trackerGroupInfo; String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " +
"TRACCAR_USER_ID = ? ";
if(NotInDeviceIdList!=null && (!NotInDeviceIdList.isEmpty())){
sql += TrackerManagementDAOUtil.buildDeviceIdNotInQuery(NotInDeviceIdList);
} }
sql += " ORDER BY TRACCAR_USER_ID ASC";
private TrackerDeviceInfo loadTrackerDevice(ResultSet rs) throws SQLException { stmt = conn.prepareStatement(sql);
TrackerDeviceInfo trackerDeviceInfo = new TrackerDeviceInfo(); int paramIdx = 1;
trackerDeviceInfo.setId(rs.getInt("ID")); stmt.setInt(paramIdx++, userId);
trackerDeviceInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID")); if(NotInDeviceIdList!=null && (!NotInDeviceIdList.isEmpty())){
trackerDeviceInfo.setDeviceId(rs.getInt("DEVICE_ID")); for (int id : NotInDeviceIdList) {
trackerDeviceInfo.setTenantId(rs.getInt("TENANT_ID")); stmt.setInt(paramIdx++, id);
trackerDeviceInfo.setStatus(rs.getInt("STATUS")); }
return trackerDeviceInfo; }
rs = stmt.executeQuery();
trackerPermissionInfo = new ArrayList<>();
while (rs.next()) {
TrackerPermissionInfo loadPermission = TrackerManagementDAOUtil.loadPermission(rs);
trackerPermissionInfo.add(loadPermission);
} }
private TrackerPermissionInfo loadPermission(ResultSet rs) throws SQLException {
TrackerPermissionInfo trackerPermissionInfo = new TrackerPermissionInfo();
trackerPermissionInfo.setTraccarUserId(rs.getInt("TRACCAR_USER_ID"));
trackerPermissionInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID"));
return trackerPermissionInfo; return trackerPermissionInfo;
} catch (SQLException e) {
String msg = "Error occurred while retrieving data from the permissions mapping table ";
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, rs);
}
} }
@Override
public Boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
TrackerPermissionInfo trackerPermissionInfo = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "SELECT TRACCAR_DEVICE_ID, TRACCAR_USER_ID FROM DM_EXT_PERMISSION_MAPPING WHERE " +
"TRACCAR_DEVICE_ID = ? AND TRACCAR_USER_ID = ? ORDER BY TRACCAR_DEVICE_ID DESC";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, userId);
rs = stmt.executeQuery();
return rs.next();
} catch (SQLException e) {
throw new TrackerManagementDAOException("Error occurred while retrieving permissions data from permissions mapping table ", e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, rs);
}
}
} }

@ -173,6 +173,14 @@ public final class DeviceManagementDAOUtil {
return enrolmentInfo; return enrolmentInfo;
} }
public static EnrolmentInfo loadEnrolmentStatus(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setId(rs.getInt("ENROLMENT_ID"));
enrolmentInfo.setTransferred(rs.getBoolean("IS_TRANSFERRED"));
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
return enrolmentInfo;
}
public static EnrolmentInfo loadMatchingEnrolment(ResultSet rs) throws SQLException { public static EnrolmentInfo loadMatchingEnrolment(ResultSet rs) throws SQLException {
Map<EnrolmentInfo.Status, EnrolmentInfo> enrolmentInfos = new HashMap<>(); Map<EnrolmentInfo.Status, EnrolmentInfo> enrolmentInfos = new HashMap<>();
EnrolmentInfo enrolmentInfo = loadEnrolment(rs); EnrolmentInfo enrolmentInfo = loadEnrolment(rs);
@ -218,6 +226,14 @@ public final class DeviceManagementDAOUtil {
return device; return device;
} }
public static Device loadDeviceIds(ResultSet rs) throws SQLException {
Device device = new Device();
device.setId(rs.getInt("DEVICE_ID"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
device.setEnrolmentInfo(loadEnrolmentStatus(rs));
return device;
}
public static DeviceBilling loadDeviceBilling(ResultSet rs) throws SQLException { public static DeviceBilling loadDeviceBilling(ResultSet rs) throws SQLException {
DeviceBilling device = new DeviceBilling(); DeviceBilling device = new DeviceBilling();
device.setId(rs.getInt("ID")); device.setId(rs.getInt("ID"));

@ -14,10 +14,10 @@
* KIND, either express or implied. See the License for the * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/
/* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
* *
* Copyright (c) 2021, Entgra (pvt) Ltd. (https://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,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. * in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@ -36,6 +36,10 @@ package org.wso2.carbon.device.mgt.core.dao.util;
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.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerGroupInfo;
import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import javax.naming.InitialContext; import javax.naming.InitialContext;
import javax.sql.DataSource; import javax.sql.DataSource;
@ -43,6 +47,8 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List;
import java.util.StringJoiner;
/** /**
* This class represents utilities required to work with group management data * This class represents utilities required to work with group management data
@ -81,8 +87,7 @@ public final class TrackerManagementDAOUtil {
* @param jndiProperties Hash table of JNDI Properties * @param jndiProperties Hash table of JNDI Properties
* @return datasource looked * @return datasource looked
*/ */
public static DataSource lookupDataSource(String dataSourceName, public static DataSource lookupDataSource(String dataSourceName, final Hashtable<Object, Object> jndiProperties) {
final Hashtable<Object, Object> jndiProperties) {
try { try {
if (jndiProperties == null || jndiProperties.isEmpty()) { if (jndiProperties == null || jndiProperties.isEmpty()) {
return (DataSource) InitialContext.doLookup(dataSourceName); return (DataSource) InitialContext.doLookup(dataSourceName);
@ -93,4 +98,42 @@ public final class TrackerManagementDAOUtil {
throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e);
} }
} }
public static 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"));
trackerGroupInfo.setStatus(rs.getInt("STATUS"));
return trackerGroupInfo;
}
public static 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"));
trackerDeviceInfo.setStatus(rs.getInt("STATUS"));
return trackerDeviceInfo;
}
public static TrackerPermissionInfo loadPermission(ResultSet rs) throws SQLException {
TrackerPermissionInfo trackerPermissionInfo = new TrackerPermissionInfo();
trackerPermissionInfo.setTraccarUserId(rs.getInt("TRACCAR_USER_ID"));
trackerPermissionInfo.setTraccarDeviceId(rs.getInt("TRACCAR_DEVICE_ID"));
return trackerPermissionInfo;
}
public static String buildDeviceIdNotInQuery(List<Integer> DeviceIdList) throws TrackerManagementDAOException {
if (DeviceIdList == null || DeviceIdList.isEmpty()) {
String msg = "SQL query build for Device Id list failed. Device Id list cannot be empty or null";
throw new TrackerManagementDAOException(msg);
}
StringJoiner joiner = new StringJoiner(",", " AND TRACCAR_DEVICE_ID NOT IN(", ")");
DeviceIdList.stream().map(status -> "?").forEach(joiner::add);
return joiner.toString();
}
} }

@ -399,6 +399,8 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
log.error("InterruptedException : " + e); log.error("InterruptedException : " + e);
//throw new RuntimeException(e); //throw new RuntimeException(e);
} }
}else{
log.info("location publishing is disabled and traccan disabled");
} }
//Tracker update GPS Location //Tracker update GPS Location

@ -67,7 +67,6 @@ import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion;
import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster;
import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Collection; import java.util.Collection;
@ -187,6 +186,16 @@ public interface DeviceManagementProviderService {
*/ */
PaginationResult getAllDevices(PaginationRequest request) throws DeviceManagementException; PaginationResult getAllDevices(PaginationRequest request) throws DeviceManagementException;
/**
* Method to retrieve all the devices with pagination support.
*
* @param request PaginationRequest object holding the data for pagination
* @return PaginationResult - Result including the required parameters necessary to do pagination.
* @throws DeviceManagementException If some unusual behaviour is observed while fetching the
* devices.
*/
PaginationResult getAllDevicesIds(PaginationRequest request) throws DeviceManagementException;
/** /**
* Method to retrieve all the devices with pagination support. * Method to retrieve all the devices with pagination support.
* *
@ -220,6 +229,16 @@ public interface DeviceManagementProviderService {
/**
* Method to retrieve all the devices with pagination support.
*
* @param request PaginationRequest object holding the data for pagination
* @return PaginationResult - Result including the required parameters necessary to do pagination.
* @throws DeviceManagementException If some unusual behaviour is observed while fetching the
* devices.
*/
PaginationResult getAllDevicesIdList(PaginationRequest request) throws DeviceManagementException;
/** /**
* Returns the device of specified id. * Returns the device of specified id.
* *

@ -32,6 +32,7 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.core.service; package org.wso2.carbon.device.mgt.core.service;
import com.google.common.reflect.TypeToken; import com.google.common.reflect.TypeToken;
@ -173,7 +174,6 @@ import java.util.Properties;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService,
PluginInitializationListener { PluginInitializationListener {
@ -1226,6 +1226,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return paginationResult; return paginationResult;
} }
@Override
public PaginationResult getAllDevicesIds(PaginationRequest request) throws DeviceManagementException {
return this.getAllDevicesIdList(request);
}
@Override @Override
public PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException { public PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException {
if (request == null) { if (request == null) {
@ -1286,6 +1291,48 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return paginationResult; return paginationResult;
} }
@Override
public PaginationResult getAllDevicesIdList(PaginationRequest request) throws DeviceManagementException {
if (request == null) {
String msg = "Received incomplete pagination request for method getAllDevicesIdList";
log.error(msg);
throw new DeviceManagementException(msg);
}
if (log.isDebugEnabled()) {
log.debug("Get devices with pagination " + request.toString());
}
PaginationResult paginationResult = new PaginationResult();
List<Device> allDevices;
int count = 0;
int tenantId = this.getTenantId();
DeviceManagerUtil.validateDeviceListPageSize(request);
try {
DeviceManagementDAOFactory.openConnection();
allDevices = deviceDAO.getDevicesIds(request, tenantId);
count = deviceDAO.getDeviceCount(request, tenantId);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred while retrieving device list pertaining to the current tenant";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred while opening a connection to the data source";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} catch (Exception e) {
String msg = "Error occurred in getAllDevices";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
paginationResult.setData(allDevices);
paginationResult.setRecordsFiltered(count);
paginationResult.setRecordsTotal(count);
return paginationResult;
}
@Override @Override
public Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException { public Device getDevice(DeviceIdentifier deviceId, boolean requireDeviceInfo) throws DeviceManagementException {
if (deviceId == null) { if (deviceId == null) {

@ -19,25 +19,29 @@
package org.wso2.carbon.device.mgt.core.traccar.api.service; package org.wso2.carbon.device.mgt.core.traccar.api.service;
import org.json.JSONObject; import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo;
import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException; import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarGroups; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarGroups;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarPosition;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser;
import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
public interface TraccarClient { public interface TraccarClient {
String fetchAllDevices() throws TraccarConfigurationException, ExecutionException, InterruptedException; //String fetchDevicesByUniqueId(String uniqueId) throws ExecutionException, InterruptedException;
void addDevice(TraccarDevice deviceInfo, int tenantId) throws void addDevice(TraccarDevice deviceInfo, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException;
void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException; TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException;
void disEnrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException; void disEnrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException;
@ -49,9 +53,15 @@ public interface TraccarClient {
void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException; void deleteGroup(int traccarGroupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException;
void setPermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException; void setPermission(int userId, int deviceId) throws TrackerManagementDAOException, ExecutionException, InterruptedException;
void removePermission(int userId, int deviceId, int removeType) throws ExecutionException, InterruptedException;
List<TrackerPermissionInfo> getUserIdofPermissionByUserIdNIdList(int userId, List<Integer> NotInDeviceIdList) throws TrackerManagementDAOException;
boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TraccarConfigurationException, SQLException, TrackerManagementDAOException;
void removePermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException; TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TraccarConfigurationException, SQLException, TrackerManagementDAOException;
String fetchAllUsers() throws TraccarConfigurationException, ExecutionException, InterruptedException; String fetchAllUsers() throws TraccarConfigurationException, ExecutionException, InterruptedException;
@ -61,5 +71,5 @@ public interface TraccarClient {
String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException; String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException;
String returnUser(String userName) throws TraccarConfigurationException; String returnUser(String userName) throws TraccarConfigurationException, TrackerManagementDAOException;
} }

@ -55,6 +55,7 @@ import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Random; import java.util.Random;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@ -114,8 +115,14 @@ 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)){
log.info("publisherUrlWithContext - " + publisherUrlWithContext);
if(publisherUrlWithContext.indexOf("permission") !=-1){
requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8"));
builder = builder.delete(requestBody);
}else{
builder = builder.delete(); builder = builder.delete();
} }
}
request = builder.url(endpoint+publisherUrlWithContext).addHeader(authorization, authorizationKey).build(); request = builder.url(endpoint+publisherUrlWithContext).addHeader(authorization, authorizationKey).build();
response = client.newCall(request).execute(); response = client.newCall(request).execute();
@ -150,7 +157,7 @@ public class TraccarClientImpl implements TraccarClient {
return TraccarHandlerConstants.Types.USER_NOT_FOUND; return TraccarHandlerConstants.Types.USER_NOT_FOUND;
} }
public String returnUser(String userName) throws TraccarConfigurationException{ public String returnUser(String userName) throws TrackerManagementDAOException{
try{ try{
String result = DeviceAPIClientServiceImpl.fetchUserInfo(userName); String result = DeviceAPIClientServiceImpl.fetchUserInfo(userName);
Date today = new Date(); Date today = new Date();
@ -227,7 +234,7 @@ public class TraccarClientImpl implements TraccarClient {
return result; return result;
} }
public void setPermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException { public void setPermission(int userId, int deviceId) throws ExecutionException, InterruptedException, TrackerManagementDAOException {
JSONObject payload = new JSONObject(); JSONObject payload = new JSONObject();
payload.put("userId", userId); payload.put("userId", userId);
payload.put("deviceId", deviceId); payload.put("deviceId", deviceId);
@ -247,12 +254,12 @@ public class TraccarClientImpl implements TraccarClient {
TrackerManagementDAOFactory.rollbackTransaction(); 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);
throw new TraccarConfigurationException(msg, e); throw new TrackerManagementDAOException(msg, e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction(); TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection ."; String msg = "Error occurred establishing the DB connection .";
log.error(msg, e); log.error(msg, e);
throw new TraccarConfigurationException(msg, e); throw new TrackerManagementDAOException(msg, e);
} finally { } finally {
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
@ -261,7 +268,7 @@ public class TraccarClientImpl implements TraccarClient {
} }
} }
public void removePermission(int userId, int deviceId) throws TraccarConfigurationException, ExecutionException, InterruptedException { public void removePermission(int userId, int deviceId, int removeType) throws ExecutionException, InterruptedException {
JSONObject payload = new JSONObject(); JSONObject payload = new JSONObject();
payload.put("userId", userId); payload.put("userId", userId);
payload.put("deviceId", deviceId); payload.put("deviceId", deviceId);
@ -276,32 +283,76 @@ public class TraccarClientImpl implements TraccarClient {
if(result!=null){ if(result!=null){
try { try {
TrackerManagementDAOFactory.beginTransaction(); TrackerManagementDAOFactory.beginTransaction();
trackerDAO.removeTrackerUserDevicePermission(deviceId); trackerDAO.removeTrackerUserDevicePermission(deviceId, userId, removeType);
TrackerManagementDAOFactory.commitTransaction(); TrackerManagementDAOFactory.commitTransaction();
} catch (TrackerManagementDAOException e) { } catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction(); 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);
throw new TraccarConfigurationException(msg, e); //throw new TraccarConfigurationException(msg, e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction(); TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection ."; String msg = "Error occurred establishing the DB connection .";
log.error(msg, e); log.error(msg, e);
throw new TraccarConfigurationException(msg, e); //throw new TraccarConfigurationException(msg, e);
} finally { } finally {
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
} }
} }
public String fetchAllDevices() throws ExecutionException, InterruptedException { public List<TrackerPermissionInfo> getUserIdofPermissionByUserIdNIdList(int userId, List<Integer> NotInDeviceIdList) throws TrackerManagementDAOException {
String method = TraccarHandlerConstants.Methods.GET; try {
String url = defaultPort+"/api/devices"; 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);
} catch (SQLException e) {
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
}
Future<String> result = executor.submit(new OkHttpClientThreadPool(url, null, method)); public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException {
String res = result.get(); try {
//executor.shutdown(); TrackerManagementDAOFactory.openConnection();
return res; return trackerDAO.getTrackerDevice(deviceId, tenantId);
} catch (SQLException e) {
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} catch (TrackerManagementDAOException e) {
String msg="Could not add new device location";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally{
TrackerManagementDAOFactory.closeConnection();
}
}
public boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException {
Boolean result = false;
try {
TrackerManagementDAOFactory.openConnection();
result = trackerDAO.getUserIdofPermissionByDeviceIdNUserId(deviceId, userId);
} catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
return result;
} }
/** /**
@ -311,7 +362,7 @@ public class TraccarClientImpl implements TraccarClient {
* @throws TraccarConfigurationException Failed while add Traccar Device the operation * @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/ */
public void addDevice(TraccarDevice traccarDevice, int tenantId) throws public void addDevice(TraccarDevice traccarDevice, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException {
TrackerDeviceInfo trackerDeviceInfo = null; TrackerDeviceInfo trackerDeviceInfo = null;
try { try {
TrackerManagementDAOFactory.openConnection(); TrackerManagementDAOFactory.openConnection();
@ -324,11 +375,11 @@ public class TraccarClientImpl implements TraccarClient {
} 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);
throw new TraccarConfigurationException(msg, e); throw new TrackerManagementDAOException(msg, e);
} 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 TraccarConfigurationException(msg, e); throw new TrackerManagementDAOException(msg, e);
} finally { } finally {
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
@ -341,11 +392,14 @@ 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));
String result = res.get(); String result = res.get();
log.info("---------res--------" + result);
if(result.charAt(0)=='{'){ if(result.charAt(0)=='{'){
JSONObject obj = new JSONObject(result); JSONObject obj = new JSONObject(result);
if (obj.has("id")){ if (obj.has("id")){
int traccarDeviceId = obj.getInt("id"); int traccarDeviceId = obj.getInt("id");
int deviceId = traccarDevice.getId(); int deviceId = traccarDevice.getId();
log.info("TraccarDeviceId - " + traccarDeviceId);
log.info("DeviceId - " + deviceId);
try { try {
TrackerManagementDAOFactory.beginTransaction(); TrackerManagementDAOFactory.beginTransaction();
trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId); trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId);
@ -358,12 +412,12 @@ public class TraccarClientImpl implements TraccarClient {
TrackerManagementDAOFactory.rollbackTransaction(); 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);
throw new TraccarConfigurationException(msg, e); throw new TrackerManagementDAOException(msg, e);
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction(); TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection ."; String msg = "Error occurred establishing the DB connection .";
log.error(msg, e); log.error(msg, e);
throw new TraccarConfigurationException(msg, e); throw new TrackerManagementDAOException(msg, e);
} finally { } finally {
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
@ -380,7 +434,7 @@ public class TraccarClientImpl implements TraccarClient {
* Add Device GPS Location operation. * Add Device GPS Location operation.
* @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition * @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition
*/ */
public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException { public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException {
TrackerDeviceInfo trackerDeviceInfo = null; TrackerDeviceInfo trackerDeviceInfo = null;
try { try {
TrackerManagementDAOFactory.openConnection(); TrackerManagementDAOFactory.openConnection();
@ -388,11 +442,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 TraccarConfigurationException(msg, e); throw new TrackerManagementDAOException(msg, e);
} catch (TrackerManagementDAOException e) { } catch (TrackerManagementDAOException e) {
String msg="Could not add new device location"; String msg="Could not add new device location";
log.error(msg, e); log.error(msg, e);
throw new TraccarConfigurationException(msg, e); throw new TrackerManagementDAOException(msg, e);
} finally{ } finally{
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
@ -421,21 +475,25 @@ public class TraccarClientImpl implements TraccarClient {
*/ */
public void disEnrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException { public void disEnrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException {
TrackerDeviceInfo trackerDeviceInfo = null; TrackerDeviceInfo trackerDeviceInfo = null;
TrackerPermissionInfo trackerPermissionInfo = null; List<TrackerPermissionInfo> trackerPermissionInfo = null;
JSONObject trackerDevice = null; //JSONObject trackerDevice = null;
try { try {
TrackerManagementDAOFactory.beginTransaction(); TrackerManagementDAOFactory.beginTransaction();
trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId); trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId);
log.info("------deviceId-----" + deviceId);
log.info(trackerDeviceInfo);
log.info(new Gson().toJson(trackerDeviceInfo));
log.info(trackerDeviceInfo.getDeviceId());
log.info(trackerDeviceInfo.getTraccarDeviceId());
if(trackerDeviceInfo!=null){ if(trackerDeviceInfo!=null){
trackerDevice = new JSONObject(trackerDeviceInfo); //trackerDevice = new JSONObject(trackerDeviceInfo);
trackerDAO.removeTrackerDevice(deviceId, tenantId); int status = trackerDAO.removeTrackerDevice(deviceId, tenantId);
log.info("Status" + status);
TrackerManagementDAOFactory.commitTransaction(); TrackerManagementDAOFactory.commitTransaction();
log.error(trackerDevice.getInt("traccarDeviceId")); trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDeviceInfo.getTraccarDeviceId());
trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDevice.getInt("traccarDeviceId"));
log.error(trackerPermissionInfo);
log.error(new Gson().toJson(trackerPermissionInfo));
} }
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction(); TrackerManagementDAOFactory.rollbackTransaction();
@ -451,17 +509,26 @@ public class TraccarClientImpl implements TraccarClient {
TrackerManagementDAOFactory.closeConnection(); TrackerManagementDAOFactory.closeConnection();
} }
log.info("__________________");
log.info(new Gson().toJson(trackerPermissionInfo));
log.info(trackerPermissionInfo.get(0));
log.info(new Gson().toJson(trackerPermissionInfo.get(0)));
log.info("__________________");
//Delete from traccar //Delete from traccar
if(trackerDevice!=null){ if(trackerDeviceInfo!=null){
String method = TraccarHandlerConstants.Methods.DELETE; String method = TraccarHandlerConstants.Methods.DELETE;
String url = defaultPort+"/api/devices/"+trackerDevice.getInt("traccarDeviceId"); String url = defaultPort+"/api/devices/"+trackerPermissionInfo.get(0).getTraccarDeviceId();
//executor.submit(new OkHttpClientThreadPool(url, null, method));
executor.submit(new OkHttpClientThreadPool(url, null, method)); executor.submit(new OkHttpClientThreadPool(url, null, method));
//executor.shutdown(); //executor.shutdown();
//remove permissions
if(trackerPermissionInfo!=null){ //remove permissions
try { try {
removePermission(trackerPermissionInfo.getTraccarUserId(),trackerDevice.getInt("traccarDeviceId")); removePermission(
trackerPermissionInfo.get(0).getTraccarUserId(),
trackerPermissionInfo.get(0).getTraccarDeviceId(),
TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE);
} catch (ExecutionException e) { } catch (ExecutionException e) {
log.error("ExecutionException : " + e); log.error("ExecutionException : " + e);
//throw new RuntimeException(e); //throw new RuntimeException(e);
@ -471,7 +538,6 @@ public class TraccarClientImpl implements TraccarClient {
} }
} }
} }
}
/** /**
* Add Traccar Device operation. * Add Traccar Device operation.

@ -23,9 +23,12 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException; import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService; import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TraccarClientImpl; import org.wso2.carbon.device.mgt.core.traccar.api.service.addons.TraccarClientImpl;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice; import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice;
@ -35,6 +38,7 @@ import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser;
import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException; import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
public class DeviceAPIClientServiceImpl implements DeviceAPIClientService { public class DeviceAPIClientServiceImpl implements DeviceAPIClientService {
@ -49,7 +53,7 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService {
"", ""); "", "");
try { try {
client.addDevice(traccarDevice, tenantId); client.addDevice(traccarDevice, tenantId);
} catch (TraccarConfigurationException 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);
} catch (TrackerAlreadyExistException e) { } catch (TrackerAlreadyExistException e) {
@ -71,7 +75,7 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService {
"", ""); "", "");
try { try {
client.updateLocation(traccarDevice, traccarPosition, tenantId); client.updateLocation(traccarDevice, traccarPosition, tenantId);
} catch (TraccarConfigurationException 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);
}catch (TrackerAlreadyExistException e) { }catch (TrackerAlreadyExistException e) {
@ -109,20 +113,31 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService {
client.deleteGroup(groupId, tenantId); client.deleteGroup(groupId, tenantId);
} }
public static String fetchUserInfo(String userName) throws public static String fetchUserInfo(String userName) throws ExecutionException, InterruptedException {
TraccarConfigurationException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl(); TraccarClientImpl client = new TraccarClientImpl();
return client.fetchUserInfo(userName); return client.fetchUserInfo(userName);
} }
public static TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws
TrackerManagementDAOException {
TraccarClientImpl client = new TraccarClientImpl();
return client.getTrackerDevice(deviceId, tenantId);
}
public static boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws
TrackerManagementDAOException {
TraccarClientImpl client = new TraccarClientImpl();
return client.getUserIdofPermissionByDeviceIdNUserId(deviceId, userId);
}
public static String createUser(TraccarUser traccarUser) throws public static String createUser(TraccarUser traccarUser) throws
TraccarConfigurationException, ExecutionException, InterruptedException { TrackerManagementDAOException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl(); TraccarClientImpl client = new TraccarClientImpl();
return client.createUser(traccarUser); return client.createUser(traccarUser);
} }
public static String updateUser(TraccarUser traccarUser, int userId) throws public static String updateUser(TraccarUser traccarUser, int userId) throws
TraccarConfigurationException, ExecutionException, InterruptedException { TrackerManagementDAOException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl(); TraccarClientImpl client = new TraccarClientImpl();
return client.updateUser(traccarUser, userId); return client.updateUser(traccarUser, userId);
} }
@ -131,7 +146,7 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService {
TraccarClientImpl client = new TraccarClientImpl(); TraccarClientImpl client = new TraccarClientImpl();
try { try {
return client.returnUser(userName); return client.returnUser(userName);
} catch (TraccarConfigurationException e) { } catch (TrackerManagementDAOException e) {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
String msg = "Error occurred while creating a user: "+ e; String msg = "Error occurred while creating a user: "+ e;
obj.put("error", msg); obj.put("error", msg);
@ -139,6 +154,22 @@ public class DeviceAPIClientServiceImpl implements DeviceAPIClientService {
} }
} }
public static void addTrackerUserDevicePermission(int userId, int deviceId) throws
TrackerManagementDAOException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
client.setPermission(userId, deviceId);
}
public static void removeTrackerUserDevicePermission(int userId, int deviceId, int removeType) throws TrackerManagementDAOException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
client.removePermission(userId, deviceId, removeType);
}
public static List<TrackerPermissionInfo> getUserIdofPermissionByUserIdNIdList(int userId, List<Integer> NotInDeviceIdList) throws TrackerManagementDAOException {
TraccarClientImpl client = new TraccarClientImpl();
return client.getUserIdofPermissionByUserIdNIdList(userId, NotInDeviceIdList);
}
public static String generateRandomString(int len) { public static String generateRandomString(int len) {
TraccarClientImpl client = new TraccarClientImpl(); TraccarClientImpl client = new TraccarClientImpl();
return client.generateRandomString(len); return client.generateRandomString(len);

@ -44,18 +44,12 @@ public class TraccarHandlerConstants {
public static final String USER = "USER"; public static final String USER = "USER";
public static final String PERMISSION = "PERMISSION"; public static final String PERMISSION = "PERMISSION";
public static final String USER_CREATE = "USER_CREATE";
public static final String USER_CREATE_WITH_INSERT_DEVICE = "USER_CREATE_WITH_INSERT_DEVICE";
public static final String USER_UPDATE = "USER_UPDATE";
public static final String USER_UPDATE_WITH_INSERT_DEVICE = "USER_UPDATE_WITH_INSERT_DEVICE";
public static final String USER_SEARCH = "USER_SEARCH";
public static final String FETCH_ALL_USERS = "FETCH_ALL_USERS";
public static final String FETCH_ALL_DEVICES = "FETCH_ALL_DEVICES";
public static final String USER_NOT_FOUND = "USER_NOT_FOUND"; public static final String USER_NOT_FOUND = "USER_NOT_FOUND";
public static final int DEFAULT_RANDOM = 10; public static final int DEFAULT_RANDOM = 10;
public static final int TRACCAR_TOKEN = 32; public static final int TRACCAR_TOKEN = 32;
public static final int REMOVE_TYPE_MULTIPLE = -1;
public static final int REMOVE_TYPE_SINGLE = 1;
} }
} }

@ -16,6 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.core.traccar.common.beans; package org.wso2.carbon.device.mgt.core.traccar.common.beans;
import java.io.Serializable; import java.io.Serializable;

@ -1,12 +1,13 @@
/* /*
* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. * Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
* *
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License, * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
* Version 2.0 (the "License"); you may not use this file except *
* in compliance with the License. * Licensed under the Entgra Commercial License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * https://entgra.io/licenses/entgra-commercial/1.0
* *
* Unless required by applicable law or agreed to in writing, * Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an * software distributed under the License is distributed on an

@ -1,3 +1,22 @@
/*
* Copyright (C) 2018 - 2022 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
*
* Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
*
* Licensed under the Entgra Commercial License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://entgra.io/licenses/entgra-commercial/1.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.traccar.common.util; package org.wso2.carbon.device.mgt.core.traccar.common.util;
import org.json.JSONObject; import org.json.JSONObject;

Loading…
Cancel
Save