Merge branch 'traccar' into 'feature/traccar-sync'

Sync traccar changes to latest

See merge request entgra/carbon-device-mgt!912
feature/traccar-sync
Shamalka Navod 2 years ago
commit 4e489a642e

@ -583,6 +583,59 @@ public interface DeviceManagementService {
@QueryParam("limit") @QueryParam("limit")
int limit); int limit);
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of Registered Devices Owned by an Authenticated User",
notes = "Provides details of devices enrolled by authenticated users.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
})
}
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.",
response = DeviceList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of " +
"the requested resource.\n"),
@ApiResponse(
code = 400,
message = "The incoming request has more than one selection criteria defined via the query parameters.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "The search criteria did not match any device registered with the server.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
response = ErrorResponse.class)
})
@Path("/traccar-user-token")
Response getTraccarUserToken();
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/{groupId}/location-history") @Path("/{groupId}/location-history")

@ -42,6 +42,8 @@ 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.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.application.mgt.common.ApplicationInstallResponse; import io.entgra.application.mgt.common.ApplicationInstallResponse;
@ -60,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;
@ -87,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;
@ -97,7 +102,10 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException; 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.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.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance;
@ -124,12 +132,25 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.*; import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.sql.Timestamp; 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 {
@ -463,6 +484,109 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} }
} }
@GET
@Override
@Path("/traccar-user-token")
public Response getTraccarUserToken() {
if (HttpReportingUtil.isTrackerEnabled()) {
String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
JSONObject obj = new JSONObject(DeviceAPIClientServiceImpl.returnUser(currentUser));
if (obj.has("error")) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build();
} 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);
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 (DeviceManagementException e) {
String msg = "Error occurred while fetching all enrolled devices";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceAccessAuthorizationException e) {
String msg = "Error occurred while checking device access authorization";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ExecutionException e) {
String msg = "ExecutionException occured ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (InterruptedException e) {
String msg = "InterruptedException occured ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
/*Get Device Id List*/
return Response.status(Response.Status.OK).entity(obj.getString("token")).build();
}
} else {
return Response.status(Response.Status.BAD_REQUEST).entity("Traccar is not enabled").build();
}
}
/** /**
* Validate group Id and group Id greater than 0 and exist. * Validate group Id and group Id greater than 0 and exist.
* *

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

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

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

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

@ -0,0 +1,46 @@
/*
* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(value = "User", description = "This class carries all information related to a managed Traccar User.")
public class TrackerUserInfo implements Serializable {
private static final long serialVersionUID = 1998101712L;
@ApiModelProperty(name = "userName", value = "The user's name that can be set on the device by the device user.",
required = true)
private String userName;
public TrackerUserInfo() {
}
public String getUserName() {
return userName;
}
public void setUserName(String UserName) {
this.userName = UserName;
}
}

@ -0,0 +1,60 @@
/*
* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common.exceptions;
/**
* This class represents a custom exception specified for group management
*/
public class TrackerAlreadyExistException extends Exception {
private static final long serialVersionUID = -312678379574816874L;
private String errorMessage;
public TrackerAlreadyExistException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public TrackerAlreadyExistException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public TrackerAlreadyExistException(String msg) {
super(msg);
setErrorMessage(msg);
}
public TrackerAlreadyExistException() {
super();
}
public TrackerAlreadyExistException(Throwable cause) {
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -342,6 +342,11 @@
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

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

@ -27,12 +27,11 @@ import org.wso2.carbon.device.mgt.common.exceptions.UnsupportedDatabaseEngineExc
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.dao.impl.*; import org.wso2.carbon.device.mgt.core.dao.impl.*;
import org.wso2.carbon.device.mgt.core.dao.impl.event.GenericEventConfigDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.device.GenericDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.GenericDeviceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.device.OracleDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.OracleDeviceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.device.PostgreSQLDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.PostgreSQLDeviceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.device.SQLServerDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.device.SQLServerDeviceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.impl.event.H2EventConfigDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.tracker.TrackerDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO;
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.impl.DeviceDetailsDAOImpl; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.impl.DeviceDetailsDAOImpl;
@ -130,6 +129,23 @@ public class DeviceManagementDAOFactory {
return new BillingDAOImpl(); return new BillingDAOImpl();
} }
public static TrackerDAO getTrackerDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL:
return new TrackerDAOImpl();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
}
throw new IllegalStateException("Database engine has not initialized properly.");
}
public static DeviceStatusDAO getDeviceStatusDAO() { public static DeviceStatusDAO getDeviceStatusDAO() {
return new DeviceStatusDAOImpl(); return new DeviceStatusDAOImpl();
} }

@ -0,0 +1,148 @@
/*
* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.dao;
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 java.util.List;
public interface TrackerDAO {
/**
* Add new Device.
* @param traccarDeviceId to be added.
* @param deviceId of the device.
* @param tenantId of the group.
* @return boolean value.
* @throws TrackerManagementDAOException
*/
Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId) throws TrackerManagementDAOException;
/**
* get trackerDevice info.
* @param deviceId of the device.
* @param tenantId of the group.
* @return Tracker Device Info.
* @throws TrackerManagementDAOException
*/
TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException;
/**
* update trackerDevice status and traccarDeviceId.
* @param traccarDeviceId of the Device.
* @param deviceId of the device.
* @param tenantId of the group.
* @param status of the device.
* @return boolean value.
* @throws TrackerManagementDAOException
*/
Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status) throws TrackerManagementDAOException;
/**
* Remove a Device.
* @param deviceId of the device.
* @param tenantId of the group.
* @return sql execution result.
* @throws TrackerManagementDAOException
*/
int removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException;
/**
* Add new Group.
* @param traccarGroupId to be added.
* @param groupId of the group.
* @param tenantId of the group.
* @return boolean value.
* @throws TrackerManagementDAOException
*/
Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId) throws TrackerManagementDAOException;
/**
* Update status and traccarGroupId of a Group.
* @param traccarGroupId to be added.
* @param groupId of the group.
* @param tenantId of the group.
* @param status of the group.
* @return boolean value.
* @throws TrackerManagementDAOException
*/
Boolean updateTrackerGroupIdANDStatus(int traccarGroupId, int groupId, int tenantId, int status) throws TrackerManagementDAOException;
/**
* Remove a Group.
* @param id of groups.
* @return boolean value.
* @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.
* @param traccarUserId mapping table.
* @param deviceId mapping table.
* @return boolean value.
* @throws TrackerManagementDAOException
*/
Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId) throws TrackerManagementDAOException;
/**
* Remove a permission on viewing a device.
* @param deviceId of permissions.
* @return boolean value.
* @throws TrackerManagementDAOException
*/
Boolean removeTrackerUserDevicePermission(int deviceId, int userId, int removeType) 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 list of userDevicePermissions by.
* @param deviceId of permissions.
* @param userId of permissions.
* @return Tracker Permission Info.
* @throws TrackerManagementDAOException
*/
Boolean getUserIdofPermissionByDeviceIdNUserId(int deviceId, int userId) throws TrackerManagementDAOException;
}

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

@ -0,0 +1,241 @@
/*
* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.exceptions.IllegalTransactionStateException;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.UnsupportedDatabaseEngineException;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.dao.impl.tracker.TrackerDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.List;
/**
* This class intends to act as the primary entity that hides all DAO instantiation related complexities and logic so
* that the business objection handling layer doesn't need to be aware of the same providing seamless plug-ability of
* different data sources, connection acquisition mechanisms as well as different forms of DAO implementations to the
* high-level implementations that require device management related metadata persistence.
* <p/>
* In addition, this also provides means to handle transactions across multiple device management related DAO objects.
* Any high-level business logic that requires transaction handling to be done via utility methods provided in
* TrackerManagementDAOFactory should adhere the following guidelines to avoid any unexpected behaviour that can cause
* as a result of improper use of the aforementioned utility method.
* <p/>
* Any transaction that commits data into the underlying data persistence mechanism MUST follow the sequence of
* operations mentioned below.
* <p/>
* <pre>
* {@code
* try {
* TrackerManagementDAOFactory.beginTransaction();
* .....
* TrackerManagementDAOFactory.commitTransaction();
* return success;
* } catch (Exception e) {
* TrackerManagementDAOFactory.rollbackTransaction();
* throw new DeviceManagementException("Error occurred while ...", e);
* } finally {
* TrackerManagementDAOFactory.closeConnection();
* }
* }
* </pre>
* <p/>
* Any transaction that retrieves data from the underlying data persistence mechanism MUST follow the sequence of
* operations mentioned below.
* <p/>
* <pre>
* {@code
* try {
* TrackerManagementDAOFactory.openConnection();
* .....
* } catch (Exception e) {
* throw new DeviceManagementException("Error occurred while ..., e);
* } finally {
* TrackerManagementDAOFactory.closeConnection();
* }
* }
* </pre>
*/
public class TrackerManagementDAOFactory {
private static DataSource dataSource;
private static String databaseEngine;
private static final Log log = LogFactory.getLog(TrackerManagementDAOFactory.class);
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public static TrackerDAO getTrackerDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2:
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL:
return new TrackerDAOImpl();
default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
}
throw new IllegalStateException("Database engine has not initialized properly.");
}
public static void init(DataSourceConfig config) {
dataSource = resolveDataSource(config);
try {
databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName();
} catch (SQLException e) {
log.error("Error occurred while retrieving config.datasource connection", e);
}
}
public static void init(DataSource dtSource) {
dataSource = dtSource;
try {
databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName();
} catch (SQLException e) {
log.error("Error occurred while retrieving config.datasource connection", e);
}
}
public static void beginTransaction() throws TransactionManagementException {
Connection conn = currentConnection.get();
if (conn != null) {
throw new IllegalTransactionStateException("A transaction is already active within the context of " +
"this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
"transaction is already active is a sign of improper transaction handling");
}
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e);
}
}
public static void openConnection() throws SQLException {
Connection conn = currentConnection.get();
if (conn != null) {
throw new IllegalTransactionStateException("A transaction is already active within the context of " +
"this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
"transaction is already active is a sign of improper transaction handling");
}
conn = dataSource.getConnection();
currentConnection.set(conn);
}
public static Connection getConnection() throws SQLException {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
}
return conn;
}
public static void commitTransaction() {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
}
try {
conn.commit();
} catch (SQLException e) {
log.error("Error occurred while committing the transaction", e);
}
}
public static void rollbackTransaction() {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
}
try {
conn.rollback();
} catch (SQLException e) {
log.warn("Error occurred while roll-backing the transaction", e);
}
}
public static void closeConnection() {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
}
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while close the connection");
}
currentConnection.remove();
}
/**
* Resolve data source from the data source definition
*
* @param config data source configuration
* @return data source resolved from the data source definition
*/
private static DataSource resolveDataSource(DataSourceConfig config) {
DataSource dataSource = null;
if (config == null) {
throw new RuntimeException(
"Device Management Repository data source configuration " + "is null and " +
"thus, is not initialized");
}
JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition();
if (jndiConfig != null) {
if (log.isDebugEnabled()) {
log.debug("Initializing Device Management Repository data source using the JNDI " +
"Lookup Definition");
}
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}
dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties);
} else {
dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null);
}
}
return dataSource;
}
}

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

@ -0,0 +1,380 @@
/*
* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.dao.impl.tracker;
import org.apache.commons.logging.Log;
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.TrackerManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.TrackerDAO;
import org.wso2.carbon.device.mgt.core.dao.util.TrackerManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class TrackerDAOImpl implements TrackerDAO {
private static final Log log = LogFactory.getLog(TrackerDAOImpl.class);
@Override
public Boolean addTrackerDevice(int traccarDeviceId, int deviceId, int tenantId)
throws TrackerManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_EXT_DEVICE_MAPPING(TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID) VALUES(?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, traccarDeviceId);
stmt.setInt(2, deviceId);
stmt.setInt(3, tenantId);
stmt.execute();
return true;
} catch (SQLException e) {
String msg = "Error occurred while adding on trackerDevice mapping table";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public Boolean updateTrackerDeviceIdANDStatus(int traccarDeviceId, int deviceId, int tenantId, int status)
throws TrackerManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "UPDATE DM_EXT_DEVICE_MAPPING SET STATUS=?, TRACCAR_DEVICE_ID=? WHERE DEVICE_ID=? AND TENANT_ID=?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, status);
stmt.setInt(2, traccarDeviceId);
stmt.setInt(3, deviceId);
stmt.setInt(4, tenantId);
stmt.execute();
return true;
} catch (SQLException e) {
String msg = "Error occurred while updating status on trackerDevice mapping table";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public int removeTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
int status = -1;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_EXT_DEVICE_MAPPING WHERE DEVICE_ID = ? AND TENANT_ID = ? ";
stmt = conn.prepareStatement(sql, new String[]{"id"});
stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
status = 1;
}
return status;
} catch (SQLException e) {
String msg = "Error occurred while removing on trackerDevice table";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
TrackerDeviceInfo trackerDeviceInfo = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "SELECT ID, TRACCAR_DEVICE_ID, DEVICE_ID, TENANT_ID, STATUS FROM DM_EXT_DEVICE_MAPPING WHERE " +
"DEVICE_ID = ? AND TENANT_ID = ? ORDER BY ID DESC LIMIT 1";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
trackerDeviceInfo = TrackerManagementDAOUtil.loadTrackerDevice(rs);
}
return trackerDeviceInfo;
} catch (SQLException e) {
String msg = "Error occurred while retrieving data from the trackerDevice table ";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public Boolean addTrackerGroup(int traccarGroupId, int groupId, int tenantId)
throws TrackerManagementDAOException {
PreparedStatement stmt = null;
int status = 1;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_EXT_GROUP_MAPPING(TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID, STATUS) VALUES(?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, traccarGroupId);
stmt.setInt(2, groupId);
stmt.setInt(3, tenantId);
stmt.setInt(4, status);
stmt.execute();
return true;
} catch (SQLException e) {
String msg = "Error occurred while adding on traccarGroup mapping table";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public Boolean updateTrackerGroupIdANDStatus(int traccarGroupId, int groupId, int tenantId, int status)
throws TrackerManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "UPDATE DM_EXT_GROUP_MAPPING SET STATUS=?, TRACCAR_GROUP_ID=? WHERE GROUP_ID=? AND TENANT_ID=?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, status);
stmt.setInt(2, traccarGroupId);
stmt.setInt(3, groupId);
stmt.setInt(4, tenantId);
stmt.execute();
return true;
} catch (SQLException e) {
String msg = "Error occurred while updating status on traccarGroup mapping table";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public int removeTrackerGroup(int id) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
int status = -1;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "DELETE FROM DM_EXT_GROUP_MAPPING WHERE ID = ? ";
stmt = conn.prepareStatement(sql, new String[]{"id"});
stmt.setInt(1, id);
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
status = 1;
}
return status;
} catch (SQLException e) {
String msg = "Error occurred while removing from traccarGroup mapping table";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public TrackerGroupInfo getTrackerGroup(int groupId, int tenantId) throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
TrackerGroupInfo trackerGroupInfo = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "SELECT ID, TRACCAR_GROUP_ID, GROUP_ID, TENANT_ID, STATUS FROM DM_EXT_GROUP_MAPPING WHERE " +
"GROUP_ID = ? AND TENANT_ID = ? ORDER BY ID DESC LIMIT 1";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
trackerGroupInfo = TrackerManagementDAOUtil.loadTrackerGroup(rs);
}
return trackerGroupInfo;
} catch (SQLException e) {
String msg = "Error occurred while retrieving data from the traccarGroup mapping table ";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public Boolean addTrackerUserDevicePermission(int traccarUserId, int deviceId)
throws TrackerManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
String sql = "INSERT INTO DM_EXT_PERMISSION_MAPPING(TRACCAR_USER_ID, TRACCAR_DEVICE_ID) VALUES(?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, traccarUserId);
stmt.setInt(2, deviceId);
stmt.execute();
return true;
} catch (SQLException e) {
String msg = "Error occurred while adding permission on permissions mapping table";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public Boolean removeTrackerUserDevicePermission(int deviceId, int userId, int removeType)
throws TrackerManagementDAOException {
PreparedStatement stmt = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
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.setInt(1, deviceId);
if (removeType != TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE) {
stmt.setInt(2, userId);
}
stmt.execute();
return true;
} catch (SQLException e) {
String msg = "Error occurred while removing permission from permissions mapping table";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
public List<TrackerPermissionInfo> getUserIdofPermissionByDeviceId(int deviceId)
throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<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 = ? ORDER BY TRACCAR_DEVICE_ID ASC";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
rs = stmt.executeQuery();
trackerPermissionInfo = new ArrayList<>();
while (rs.next()) {
TrackerPermissionInfo loadPermission = TrackerManagementDAOUtil.loadPermission(rs);
trackerPermissionInfo.add(loadPermission);
}
return trackerPermissionInfo;
} catch (SQLException e) {
String msg = "Error occurred while retrieving permissions data from permissions mapping table ";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOUtil.cleanupResources(stmt, rs);
}
}
@Override
public List<TrackerPermissionInfo> getUserIdofPermissionByUserIdNIdList(int userId, List<Integer> NotInDeviceIdList)
throws TrackerManagementDAOException {
PreparedStatement stmt = null;
ResultSet rs = null;
List<TrackerPermissionInfo> trackerPermissionInfo = null;
try {
Connection conn = TrackerManagementDAOFactory.getConnection();
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";
stmt = conn.prepareStatement(sql);
int paramIdx = 1;
stmt.setInt(paramIdx++, userId);
if (NotInDeviceIdList != null && (!NotInDeviceIdList.isEmpty())) {
for (int id : NotInDeviceIdList) {
stmt.setInt(paramIdx++, id);
}
}
rs = stmt.executeQuery();
trackerPermissionInfo = new ArrayList<>();
while (rs.next()) {
TrackerPermissionInfo loadPermission = TrackerManagementDAOUtil.loadPermission(rs);
trackerPermissionInfo.add(loadPermission);
}
return trackerPermissionInfo;
} catch (SQLException e) {
String msg = "Error occurred while retrieving data from the permissions mapping table ";
log.error(msg, e);
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;
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) {
String msg = "Error occurred while retrieving permissions data from permissions mapping table ";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, 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"));

@ -0,0 +1,141 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/* Copyright (c) 2022, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.dao.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import 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.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.List;
import java.util.StringJoiner;
/**
* This class represents utilities required to work with group management data
*/
public final class TrackerManagementDAOUtil {
private static final Log log = LogFactory.getLog(TrackerManagementDAOUtil.class);
/**
* Cleanup resources used to transaction
*
* @param stmt Prepared statement used
* @param rs Obtained results set
*/
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
}
/**
* Lookup datasource using name and jndi properties
*
* @param dataSourceName Name of datasource to lookup
* @param jndiProperties Hash table of JNDI Properties
* @return datasource looked
*/
public static DataSource lookupDataSource(String dataSourceName, final Hashtable<Object, Object> jndiProperties) {
try {
if (jndiProperties == null || jndiProperties.isEmpty()) {
return (DataSource) InitialContext.doLookup(dataSourceName);
}
final InitialContext context = new InitialContext(jndiProperties);
return (DataSource) context.lookup(dataSourceName);
} catch (Exception e) {
String msg = "Error in looking up data source: " + e.getMessage();
log.error(msg, e);
throw new RuntimeException(msg, 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";
log.error(msg);
throw new TrackerManagementDAOException(msg);
}
StringJoiner joiner = new StringJoiner(",", " AND TRACCAR_DEVICE_ID NOT IN(", ")");
DeviceIdList.stream().map(status -> "?").forEach(joiner::add);
return joiner.toString();
}
}

@ -53,6 +53,7 @@ import java.util.Calendar;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutionException;
public class DeviceInformationManagerImpl implements DeviceInformationManager { public class DeviceInformationManagerImpl implements DeviceInformationManager {
@ -385,6 +386,24 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
// LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload // LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload
// ); // );
} }
//Tracker update GPS Location
if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) {
try {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId());
} catch (ExecutionException e) {
log.error("ExecutionException : " + e);
//throw new RuntimeException(e);
} catch (InterruptedException e) {
log.error("InterruptedException : " + e);
//throw new RuntimeException(e);
}
} else {
log.info("location publishing is disabled and traccan disabled");
}
//Tracker update GPS Location
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
throw new DeviceDetailsMgtException("Transactional error occurred while adding the device location " + throw new DeviceDetailsMgtException("Transactional error occurred while adding the device location " +

@ -41,6 +41,7 @@ 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.status.task.DeviceStatusTaskManagerService; import org.wso2.carbon.device.mgt.core.status.task.DeviceStatusTaskManagerService;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService;
import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ntask.core.service.TaskService; import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
@ -83,6 +84,7 @@ public class DeviceManagementDataHolder {
private GeoFenceEventOperationManager geoFenceEventOperationManager; private GeoFenceEventOperationManager geoFenceEventOperationManager;
private ExecutorService eventConfigExecutors; private ExecutorService eventConfigExecutors;
private OperationTimeoutTaskManagerService operationTimeoutTaskManagerService; private OperationTimeoutTaskManagerService operationTimeoutTaskManagerService;
private DeviceAPIClientService deviceAPIClientService;
private final Map<DeviceType, DeviceStatusTaskPluginConfig> deviceStatusTaskPluginConfigs = Collections.synchronizedMap( private final Map<DeviceType, DeviceStatusTaskPluginConfig> deviceStatusTaskPluginConfigs = Collections.synchronizedMap(
new HashMap<>()); new HashMap<>());
@ -349,4 +351,12 @@ public class DeviceManagementDataHolder {
OperationTimeoutTaskManagerService operationTimeoutTaskManagerService) { OperationTimeoutTaskManagerService operationTimeoutTaskManagerService) {
this.operationTimeoutTaskManagerService = operationTimeoutTaskManagerService; this.operationTimeoutTaskManagerService = operationTimeoutTaskManagerService;
} }
public DeviceAPIClientService getDeviceAPIClientService() {
return deviceAPIClientService;
}
public void setDeviceAPIClientService(DeviceAPIClientService deviceAPIClientService) {
this.deviceAPIClientService = deviceAPIClientService;
}
} }

@ -53,6 +53,7 @@ import org.wso2.carbon.device.mgt.core.config.ui.UIConfigurationManager;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.EventManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.EventManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl; import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformationManagerImpl;
import org.wso2.carbon.device.mgt.core.event.config.EventConfigurationProviderServiceImpl; import org.wso2.carbon.device.mgt.core.event.config.EventConfigurationProviderServiceImpl;
@ -78,6 +79,8 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceIm
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.service.GroupManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService; import org.wso2.carbon.device.mgt.core.task.DeviceTaskManagerService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl;
import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer; import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer;
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.DeviceMgtTenantMgtListener; import org.wso2.carbon.device.mgt.core.util.DeviceMgtTenantMgtListener;
@ -190,6 +193,7 @@ public class DeviceManagementServiceComponent {
DeviceManagementDAOFactory.init(dsConfig); DeviceManagementDAOFactory.init(dsConfig);
GroupManagementDAOFactory.init(dsConfig); GroupManagementDAOFactory.init(dsConfig);
TrackerManagementDAOFactory.init(dsConfig);
NotificationManagementDAOFactory.init(dsConfig); NotificationManagementDAOFactory.init(dsConfig);
OperationManagementDAOFactory.init(dsConfig); OperationManagementDAOFactory.init(dsConfig);
MetadataManagementDAOFactory.init(dsConfig); MetadataManagementDAOFactory.init(dsConfig);
@ -302,6 +306,11 @@ public class DeviceManagementServiceComponent {
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider); DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider);
bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null); bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null);
/* Registering Device API Client Service */
DeviceAPIClientService deviceAPIClientService = new DeviceAPIClientServiceImpl();
DeviceManagementDataHolder.getInstance().setDeviceAPIClientService(deviceAPIClientService);
bundleContext.registerService(DeviceAPIClientService.class.getName(), deviceAPIClientService, null);
/* Registering Group Management Service */ /* Registering Group Management Service */
GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl(); GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl();
String defaultGroups = String defaultGroups =

@ -66,7 +66,6 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; 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 org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
@ -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;
@ -50,7 +51,24 @@ import org.apache.http.protocol.HTTP;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.ActivityPaginationRequest;
import org.wso2.carbon.device.mgt.common.Billing;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceEnrollmentInfoNotification;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.DeviceNotification;
import org.wso2.carbon.device.mgt.common.DevicePropertyNotification;
import org.wso2.carbon.device.mgt.common.DeviceTransferRequest;
import org.wso2.carbon.device.mgt.common.DynamicTaskContext;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.StartupOperationConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException; import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException;
@ -104,7 +122,14 @@ import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey;
import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl; import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.*; import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.mgt.core.dao.BillingDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.DeviceStatusDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dao.EnrollmentDAO;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
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;
@ -112,7 +137,6 @@ import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier; import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier;
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 org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener; import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
@ -120,6 +144,7 @@ import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory; import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.email.sender.core.ContentProviderInfo; import org.wso2.carbon.email.sender.core.ContentProviderInfo;
import org.wso2.carbon.email.sender.core.EmailContext; import org.wso2.carbon.email.sender.core.EmailContext;
import org.wso2.carbon.email.sender.core.EmailSendingFailedException; import org.wso2.carbon.email.sender.core.EmailSendingFailedException;
@ -141,12 +166,21 @@ import java.sql.SQLException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.text.Format; import java.text.Format;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors; import java.util.stream.Collectors;
//import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService, public class DeviceManagementProviderServiceImpl implements DeviceManagementProviderService,
PluginInitializationListener { PluginInitializationListener {
@ -394,6 +428,22 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
status = true; status = true;
} }
//enroll Traccar device
if (HttpReportingUtil.isTrackerEnabled()) {
try {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId);
} catch (ExecutionException e) {
log.error("ExecutionException : " + e);
//throw new RuntimeException(e);
//Exception was not thrown due to being conflicted with non-traccar features
} catch (InterruptedException e) {
log.error("InterruptedException : " + e);
//throw new RuntimeException(e);
//Exception was not thrown due to being conflicted with non-traccar features
}
}
//enroll Traccar device
if (status) { if (status) {
addDeviceToGroups(deviceIdentifier, device.getEnrolmentInfo().getOwnership()); addDeviceToGroups(deviceIdentifier, device.getEnrolmentInfo().getOwnership());
if (enrollmentConfiguration != null) { if (enrollmentConfiguration != null) {
@ -455,6 +505,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
} }
deviceDAO.updateDevice(device, tenantId); deviceDAO.updateDevice(device, tenantId);
enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), tenantId); enrollmentDAO.updateEnrollment(device.getEnrolmentInfo(), tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
this.removeDeviceFromCache(deviceIdentifier); this.removeDeviceFromCache(deviceIdentifier);
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
@ -554,6 +605,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceDAO.updateDevice(device, tenantId); deviceDAO.updateDevice(device, tenantId);
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
this.removeDeviceFromCache(deviceId); this.removeDeviceFromCache(deviceId);
//procees to dis-enroll a device from traccar starts
if (HttpReportingUtil.isTrackerEnabled()) {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.disEnrollDevice(device.getId(), tenantId);
}
//procees to dis-enroll a device from traccar ends
} catch (DeviceManagementDAOException e) { } catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while dis-enrolling '" + deviceId.getType() + String msg = "Error occurred while dis-enrolling '" + deviceId.getType() +
@ -1176,6 +1235,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) {
@ -1236,6 +1300,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) {
@ -3872,9 +3978,10 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceLocation.setSpeed(Float.parseFloat(speed)); deviceLocation.setSpeed(Float.parseFloat(speed));
deviceLocation.setBearing(Float.parseFloat(bearing)); deviceLocation.setBearing(Float.parseFloat(bearing));
deviceInformationManager.addDeviceLocation(device, deviceLocation); deviceInformationManager.addDeviceLocation(device, deviceLocation);
} catch (Exception e) { } catch (DeviceDetailsMgtException e) {
//We are not failing the execution since this is not critical for the functionality. But logging as //We are not failing the execution since this is not critical for the functionality. But logging as
// a warning for reference. // a warning for reference.
//Exception was not thrown due to being conflicted with non-traccar features
log.warn("Error occurred while trying to add '" + device.getType() + "' device '" + log.warn("Error occurred while trying to add '" + device.getType() + "' device '" +
device.getDeviceIdentifier() + "' (id:'" + device.getId() + "') location (lat:" + latitude + device.getDeviceIdentifier() + "' (id:'" + device.getId() + "') location (lat:" + latitude +
", lon:" + longitude + ", altitude: " + altitude + ", lon:" + longitude + ", altitude: " + altitude +

@ -65,6 +65,7 @@ import org.wso2.carbon.device.mgt.core.geo.task.GeoFenceEventOperationManager;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants; import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.api.UserStoreManager;
@ -131,8 +132,24 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
this.groupDAO.addGroupProperties(deviceGroup, updatedGroupID, tenantId); this.groupDAO.addGroupProperties(deviceGroup, updatedGroupID, tenantId);
} }
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
//add new group in traccar
if (HttpReportingUtil.isTrackerEnabled()) {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.addGroup(deviceGroup, updatedGroupID, tenantId);
}
//add new group in traccar
} else { } else {
throw new GroupAlreadyExistException("Group already exists with name '" + deviceGroup.getName() + "'."); // add a group if not exist in traccar starts
if (HttpReportingUtil.isTrackerEnabled()){
existingGroup = this.groupDAO.getGroup(deviceGroup.getName(), tenantId);
int groupId = existingGroup.getGroupId();
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.addGroup(deviceGroup, groupId, tenantId);
}
// add a group if not exist in traccar starts
throw new GroupAlreadyExistException("Group exist with name " + deviceGroup.getName());
} }
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();
@ -213,6 +230,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
if (deviceGroup.getGroupProperties() != null && deviceGroup.getGroupProperties().size() > 0) { if (deviceGroup.getGroupProperties() != null && deviceGroup.getGroupProperties().size() > 0) {
this.groupDAO.updateGroupProperties(deviceGroup, groupId, tenantId); this.groupDAO.updateGroupProperties(deviceGroup, groupId, tenantId);
} }
//procees to update a group in traccar starts
if (HttpReportingUtil.isTrackerEnabled()) {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.updateGroup(deviceGroup, groupId, tenantId);
}
//procees to update a group in traccar starts
GroupManagementDAOFactory.commitTransaction(); GroupManagementDAOFactory.commitTransaction();
} else { } else {
throw new GroupNotExistException("Group with ID - '" + groupId + "' doesn't exists!"); throw new GroupNotExistException("Group with ID - '" + groupId + "' doesn't exists!");
@ -271,6 +296,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
} }
} }
} }
//procees to delete a group from traccar starts
if (HttpReportingUtil.isTrackerEnabled()) {
DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
.deleteGroup(groupId, tenantId);
}
//procees to delete a group from traccar ends
if (isDeleteChildren) { if (isDeleteChildren) {
groupIdsToDelete.add(groupId); groupIdsToDelete.add(groupId);
groupDAO.deleteGroupsMapping(groupIdsToDelete, tenantId); groupDAO.deleteGroupsMapping(groupIdsToDelete, tenantId);
@ -287,6 +320,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DeviceGroup " + deviceGroup.getName() + " removed."); log.debug("DeviceGroup " + deviceGroup.getName() + " removed.");
} }
return true; return true;
} catch (GroupManagementDAOException e) { } catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction(); GroupManagementDAOFactory.rollbackTransaction();

@ -0,0 +1,81 @@
/*
* 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.api.service;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException;
import java.util.concurrent.ExecutionException;
public interface DeviceAPIClientService {
/**
* Add GPS location of a device Traccar configuration records
*
* @param device to be added to update location of the device
* @param deviceLocation to be added to update location of the device
* @throws TraccarConfigurationException errors thrown while inserting location of a device traccar configuration
*/
void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId) throws ExecutionException, InterruptedException;
/**
* Create device Traccar configuration records
*
* @param device to be added
* @throws TraccarConfigurationException errors thrown while creating a device traccar configuration
*/
void addDevice(Device device, int tenantId) throws ExecutionException, InterruptedException;
/**
* Delete a device Traccar configuration records
*
* @param deviceId to be delete a device
* @throws TraccarConfigurationException errors thrown while deleting a device traccar configuration
*/
void disEnrollDevice(int deviceId, int tenantId);
/**
* Delete a device Traccar configuration records
*
* @param group to be add a group
* @throws TraccarConfigurationException errors thrown while adding a group traccar configuration
*/
void addGroup(DeviceGroup group, int groupID, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException;
/**
* Delete a device Traccar configuration records
*
* @param group to be update the group
* @throws TraccarConfigurationException errors thrown while adding a group traccar configuration
*/
void updateGroup(DeviceGroup group, int groupID, int tenantId) throws ExecutionException, InterruptedException, TraccarConfigurationException, TrackerAlreadyExistException;
/**
* Delete a device Traccar configuration records
*
* @param groupId to delete a group
* @param tenantId to delete a group
* @throws TraccarConfigurationException errors thrown while adding a group traccar configuration
*/
void deleteGroup(int groupId, int tenantId) throws ExecutionException, InterruptedException, TraccarConfigurationException;
}

@ -0,0 +1,75 @@
/*
* 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.api.service;
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.core.dao.TrackerManagementDAOException;
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.TraccarPosition;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser;
import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutionException;
public interface TraccarClient {
//String fetchDevicesByUniqueId(String uniqueId) throws ExecutionException, InterruptedException;
void addDevice(TraccarDevice deviceInfo, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException;
void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException;
void disEnrollDevice(int traccarDeviceId, int tenantId) throws TraccarConfigurationException;
void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException;
void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId)
throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException;
void deleteGroup(int traccarGroupId, int tenantId) 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;
TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TraccarConfigurationException, SQLException, TrackerManagementDAOException;
String fetchAllUsers() throws TraccarConfigurationException, ExecutionException, InterruptedException;
String fetchUserInfo(String userName) throws TraccarConfigurationException, ExecutionException, InterruptedException;
String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException;
String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException;
String returnUser(String userName) throws TraccarConfigurationException, TrackerManagementDAOException;
}

@ -0,0 +1,773 @@
/*
* 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.api.service.addons;
import com.google.gson.Gson;
import okhttp3.ConnectionPool;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.wso2.carbon.context.PrivilegedCarbonContext;
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.common.exceptions.TransactionManagementException;
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.dao.TrackerDAO;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.traccar.api.service.TraccarClient;
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.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.TraccarPosition;
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.TraccarGateway;
import org.wso2.carbon.device.mgt.core.traccar.common.util.TraccarUtil;
import org.wso2.carbon.device.mgt.core.traccar.core.config.TraccarConfigurationManager;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class TraccarClientImpl implements TraccarClient {
private static final Log log = LogFactory.getLog(TraccarClientImpl.class);
private static final int THREAD_POOL_SIZE = 50;
private final OkHttpClient client;
private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
final TraccarGateway traccarGateway = getTraccarGateway();
final String endpoint = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.ENDPOINT).getValue();
final String authorization = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.AUTHORIZATION).getValue();
final String authorizationKey = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.AUTHORIZATION_KEY).getValue();
final String defaultPort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.DEFAULT_PORT).getValue();
final String locationUpdatePort = traccarGateway.getPropertyByName(TraccarHandlerConstants.TraccarConfig.LOCATION_UPDATE_PORT).getValue();
final String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
private final TrackerDAO trackerDAO;
public TraccarClientImpl() {
client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(45, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(100,50,TimeUnit.SECONDS))
.build();
this.trackerDAO = TrackerManagementDAOFactory.getTrackerDAO();
}
private class OkHttpClientThreadPool implements Callable {
final String publisherUrlWithContext;
final JSONObject payload;
private final String method;
private String authorizeKey;
private String serverUri;
private OkHttpClientThreadPool(String publisherUrlWithContext, JSONObject payload, String method, String authorizeKey) {
this.publisherUrlWithContext = publisherUrlWithContext;
this.payload = payload;
this.method = method;
this.authorizeKey = authorizeKey;
}
private OkHttpClientThreadPool(String publisherUrlWithContext, JSONObject payload, String method,
String authorizeKey, String serverUri) {
this.publisherUrlWithContext = publisherUrlWithContext;
this.payload = payload;
this.method = method;
this.authorizeKey = authorizeKey;
this.serverUri = serverUri;
}
@Override
public String call() throws Exception {
RequestBody requestBody;
Request.Builder builder = new Request.Builder();
Request request;
Response response;
if(Objects.equals(method, TraccarHandlerConstants.Methods.POST)){
requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8"));
builder = builder.post(requestBody);
}else if(Objects.equals(method, TraccarHandlerConstants.Methods.PUT)){
requestBody = RequestBody.create(payload.toString(), MediaType.parse("application/json; charset=utf-8"));
builder = builder.put(requestBody);
}else if(Objects.equals(method, TraccarHandlerConstants.Methods.DELETE)){
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();
}
}
request = builder.url(serverUri+publisherUrlWithContext).addHeader(authorization, authorizeKey).build();
response = client.newCall(request).execute();
return response.body().string();
}
}
public String fetchAllUsers() throws ExecutionException, InterruptedException {
String method = TraccarHandlerConstants.Methods.GET;
String url = defaultPort+"/api/users";
Future<String> result = executor.submit(new OkHttpClientThreadPool(url, null, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String res = result.get();
//executor.shutdown();
return res;
}
public String fetchUserInfo(String userName) throws ExecutionException, InterruptedException {
String allUsers = fetchAllUsers(); //get all users
JSONArray fetchAllUsers = new JSONArray(allUsers); //loop users
for(int i=0; i<fetchAllUsers.length();i++){
// if login is null then check the name or if login is not null then check the login
if(fetchAllUsers.getJSONObject(i).isNull("login")){
if(Objects.equals(fetchAllUsers.getJSONObject(i).getString("name"), userName)){
return fetchAllUsers.getJSONObject(i).toString();
}
}else{
if(Objects.equals(fetchAllUsers.getJSONObject(i).getString("login"), userName) ||
Objects.equals(fetchAllUsers.getJSONObject(i).getString("name"), userName)){
return fetchAllUsers.getJSONObject(i).toString();
}
}
}
return TraccarHandlerConstants.Types.USER_NOT_FOUND;
}
public String returnUser(String userName) throws TrackerManagementDAOException{
try{
String result = DeviceAPIClientServiceImpl.fetchUserInfo(userName);
Date today = new Date();
LocalDateTime tomorrow = LocalDateTime.from(today.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);
String token = DeviceAPIClientServiceImpl.generateRandomString(TraccarHandlerConstants.Types.TRACCAR_TOKEN);
TraccarUser traccarUser = new TraccarUser();
traccarUser.setToken(token);
if(Objects.equals(result, TraccarHandlerConstants.Types.USER_NOT_FOUND)){
//create user
log.info("Creating a user");
traccarUser.setName(userName);
traccarUser.setLogin(userName);
traccarUser.setEmail(userName);
traccarUser.setPassword(DeviceAPIClientServiceImpl.generateRandomString(TraccarHandlerConstants.Types.DEFAULT_RANDOM));
traccarUser.setDeviceLimit(-1);
//traccarUser.setUserLimit(-1);
traccarUser.setExpirationTime(tomorrow.toString());
DeviceAPIClientServiceImpl.createUser(traccarUser);
}else{
//update user
log.info("Updating the user");
JSONObject obj = new JSONObject(result);
traccarUser.setId(obj.getInt("id"));
traccarUser.setName(obj.getString("name"));
if(!obj.isNull("login")){
traccarUser.setLogin(obj.getString("login"));
}
traccarUser.setEmail(obj.getString("email"));
traccarUser.setDeviceLimit(obj.getInt("deviceLimit"));
traccarUser.setUserLimit(obj.getInt("userLimit"));
traccarUser.setAdministrator(obj.getBoolean("administrator"));
traccarUser.setDisabled(obj.getBoolean("disabled"));
traccarUser.setReadonly(obj.getBoolean("readonly"));
if(!obj.getBoolean("administrator")){
traccarUser.setExpirationTime(tomorrow.toString());
}else if(!obj.isNull("expirationTime")){
traccarUser.setExpirationTime(obj.getString("expirationTime"));
}
DeviceAPIClientServiceImpl.updateUser(traccarUser, obj.getInt("id"));
}
result = DeviceAPIClientServiceImpl.fetchUserInfo(userName);
return result;
} catch (InterruptedException | ExecutionException e) {
JSONObject obj=new JSONObject();
String msg = "Error occurred while executing enrollment status of the device.";
obj.put("error",msg);
obj.put("e",e);
log.error(msg, e);
return obj.toString();
}
}
public String createUser(TraccarUser traccarUser) throws ExecutionException, InterruptedException {
String method = TraccarHandlerConstants.Methods.POST;
String url = defaultPort+"/api/users";
JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser);
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
//executor.shutdown();
return result;
}
public String updateUser(TraccarUser traccarUser, int userId) throws ExecutionException, InterruptedException {
String method = TraccarHandlerConstants.Methods.PUT;
String url = defaultPort+"/api/users/"+userId;
JSONObject payload = TraccarUtil.TraccarUserPayload(traccarUser);
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
//executor.shutdown();
return result;
}
public void setPermission(int userId, int deviceId) throws ExecutionException, InterruptedException, TrackerManagementDAOException {
JSONObject payload = new JSONObject();
payload.put("userId", userId);
payload.put("deviceId", deviceId);
String method = TraccarHandlerConstants.Methods.POST;
String url = defaultPort+"/api/permissions";
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
//executor.shutdown();
if(result==""){
try {
TrackerManagementDAOFactory.beginTransaction();
trackerDAO.addTrackerUserDevicePermission(userId, deviceId);
TrackerManagementDAOFactory.commitTransaction();
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
}else{
log.error("Couldnt add the permission record: "+ result);
}
}
public void removePermission(int userId, int deviceId, int removeType) throws ExecutionException, InterruptedException {
JSONObject payload = new JSONObject();
payload.put("userId", userId);
payload.put("deviceId", deviceId);
String method = TraccarHandlerConstants.Methods.DELETE;
String url = defaultPort+"/api/permissions";
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
//executor.shutdown();
if(result!=null){
try {
TrackerManagementDAOFactory.beginTransaction();
trackerDAO.removeTrackerUserDevicePermission(deviceId, userId, removeType);
TrackerManagementDAOFactory.commitTransaction();
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
//throw new TraccarConfigurationException(msg, e);
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
//throw new TraccarConfigurationException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
}
}
public List<TrackerPermissionInfo> getUserIdofPermissionByUserIdNIdList(int userId, List<Integer> NotInDeviceIdList) throws TrackerManagementDAOException {
try {
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();
}
}
public TrackerDeviceInfo getTrackerDevice(int deviceId, int tenantId) throws TrackerManagementDAOException {
try {
TrackerManagementDAOFactory.openConnection();
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;
}
/**
* Add Traccar Device operation.
* @param traccarDevice with DeviceName UniqueId, Status, Disabled LastUpdate, PositionId, GroupId
* Model, Contact, Category, fenceIds
* @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/
public void addDevice(TraccarDevice traccarDevice, int tenantId) throws
TrackerAlreadyExistException, ExecutionException, InterruptedException, TrackerManagementDAOException {
TrackerDeviceInfo trackerDeviceInfo = null;
try {
TrackerManagementDAOFactory.openConnection();
trackerDeviceInfo = trackerDAO.getTrackerDevice(traccarDevice.getId(), tenantId);
if(trackerDeviceInfo!=null){
String msg = "The device already exist";
log.error(msg);
//throw new TrackerAlreadyExistException(msg);
}
} catch (TrackerManagementDAOException e) {
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();
}
if(trackerDeviceInfo==null){
//add the device
String method = TraccarHandlerConstants.Methods.POST;
String url = defaultPort+"/api/devices";
JSONObject payload = TraccarUtil.TraccarDevicePayload(traccarDevice);
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
log.info("---------result--------");
if(result.charAt(0)=='{'){
JSONObject obj = new JSONObject(result);
if (obj.has("id")){
int traccarDeviceId = obj.getInt("id");
int deviceId = traccarDevice.getId();
log.info("TraccarDeviceId - " + traccarDeviceId);
try {
TrackerManagementDAOFactory.beginTransaction();
trackerDAO.addTrackerDevice(traccarDeviceId, deviceId, tenantId);
trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId);
if(trackerDeviceInfo.getStatus()==0){
trackerDAO.updateTrackerDeviceIdANDStatus(trackerDeviceInfo.getTraccarDeviceId(), deviceId, tenantId, 1);
}
TrackerManagementDAOFactory.commitTransaction();
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
throw new TrackerManagementDAOException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
JSONObject returnUserInfo = new JSONObject(returnUser(username));
setPermission(returnUserInfo.getInt("id"), traccarDeviceId);
}
}
}
//executor.shutdown();
}
/**
* Add Device GPS Location operation.
* @param deviceInfo with DeviceIdentifier, Timestamp, Lat, Lon, Bearing, Speed, ignition
*/
public void updateLocation(TraccarDevice device, TraccarPosition deviceInfo, int tenantId) throws TrackerManagementDAOException, TrackerAlreadyExistException, ExecutionException, InterruptedException {
TrackerDeviceInfo trackerDeviceInfo = null;
try {
TrackerManagementDAOFactory.openConnection();
trackerDeviceInfo = trackerDAO.getTrackerDevice(device.getId(), 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();
}
//check if the device is already exist before updating the location
if (trackerDeviceInfo == null){
//add device if not exist
addDevice(device, tenantId);
}else{
//Update Location
log.info("Updating Location");
String method = TraccarHandlerConstants.Methods.GET;
String url = locationUpdatePort+"/?id="+deviceInfo.getDeviceIdentifier()+
"&timestamp="+deviceInfo.getTimestamp()+"&lat="+deviceInfo.getLat()+
"&lon="+deviceInfo.getLon()+"&bearing="+deviceInfo.getBearing()+
"&speed="+deviceInfo.getSpeed()+"&ignition=true";
executor.submit(new OkHttpClientThreadPool(url, null, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
"http://localhost:"));
//executor.shutdown();
}
}
/**
* Dis-enroll a Device operation.
* @param deviceId identified via deviceIdentifier
* @throws TraccarConfigurationException Failed while dis-enroll a Traccar Device operation
*/
public void disEnrollDevice(int deviceId, int tenantId) throws TraccarConfigurationException {
TrackerDeviceInfo trackerDeviceInfo = null;
List<TrackerPermissionInfo> trackerPermissionInfo = null;
//JSONObject trackerDevice = null;
try {
TrackerManagementDAOFactory.beginTransaction();
trackerDeviceInfo = trackerDAO.getTrackerDevice(deviceId, tenantId);
log.info("------deviceId-----" + deviceId);
log.info(trackerDeviceInfo);
if(trackerDeviceInfo!=null){
//trackerDevice = new JSONObject(trackerDeviceInfo);
int status = trackerDAO.removeTrackerDevice(deviceId, tenantId);
log.info("Status" + status);
TrackerManagementDAOFactory.commitTransaction();
trackerPermissionInfo = trackerDAO.getUserIdofPermissionByDeviceId(trackerDeviceInfo.getTraccarDeviceId());
}
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with deviceId";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
log.info("--------Disenrolling Device--------");
//Delete from traccar
if(trackerDeviceInfo!=null){
String method = TraccarHandlerConstants.Methods.DELETE;
String url = defaultPort+"/api/devices/"+trackerPermissionInfo.get(0).getTraccarDeviceId();
executor.submit(new OkHttpClientThreadPool(url, null, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
//executor.shutdown();
//remove permissions
try {
removePermission(
trackerPermissionInfo.get(0).getTraccarUserId(),
trackerPermissionInfo.get(0).getTraccarDeviceId(),
TraccarHandlerConstants.Types.REMOVE_TYPE_MULTIPLE);
} catch (ExecutionException e) {
log.error("ExecutionException : " + e);
//throw new RuntimeException(e);
} catch (InterruptedException e) {
log.error("InterruptedException : " + e);
//throw new RuntimeException(e);
}
}
}
/**
* Add Traccar Device operation.
* @param groupInfo with groupName
* @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/
public void addGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException {
TrackerGroupInfo trackerGroupInfo = null;
try {
TrackerManagementDAOFactory.openConnection();
trackerGroupInfo = trackerDAO.getTrackerGroup(groupId, tenantId);
if (trackerGroupInfo!=null){
String msg = "The group already exit";
log.error(msg);
throw new TrackerAlreadyExistException(msg);
}
} catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with groupId.";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
} catch (SQLException e) {
String msg = "Error occurred establishing the DB connection.";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
JSONObject payload = new JSONObject();
payload.put("name", groupInfo.getName());
payload.put("attributes", new JSONObject());
String method = TraccarHandlerConstants.Methods.POST;
String url = defaultPort+"/api/groups";
Future<String> res = executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
String result = res.get();
if(result.charAt(0)=='{'){
JSONObject obj = new JSONObject(result);
if (obj.has("id")){
int traccarGroupId = obj.getInt("id");
try {
TrackerManagementDAOFactory.beginTransaction();
trackerDAO.addTrackerGroup(traccarGroupId, groupId, tenantId);
trackerGroupInfo = trackerDAO.getTrackerGroup(groupId, tenantId);
if(trackerGroupInfo.getStatus()==0){
trackerDAO.updateTrackerGroupIdANDStatus(trackerGroupInfo.getTraccarGroupId(), groupId, tenantId, 1);
}
} catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
TrackerManagementDAOFactory.rollbackTransaction();
throw new TraccarConfigurationException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
TrackerManagementDAOFactory.rollbackTransaction();
throw new TraccarConfigurationException(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
}else{
log.error("Something went wrong_1: " + result);
}
}else{
log.error("Something went wrong_2: " + result);
}
//executor.shutdown();
}
/**
* update Traccar Group operation.
* @param groupInfo with groupName
* @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/
public void updateGroup(TraccarGroups groupInfo, int groupId, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException {
TrackerGroupInfo res = null;
try {
TrackerManagementDAOFactory.openConnection();
res = trackerDAO.getTrackerGroup(groupId, tenantId);
} catch (SQLException e) {
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
} catch (TrackerManagementDAOException e) {
String msg="Could not find traccar group details";
log.error(msg, e);
} finally{
TrackerManagementDAOFactory.closeConnection();
}
if ((res==null) || (res.getTraccarGroupId()==0)){
//add a new traccar group
addGroup(groupInfo, groupId, tenantId);
}else if (res!=null && (res.getTraccarGroupId()!=0 && res.getStatus()==0)){
//update the traccargroupId and status
try {
TrackerManagementDAOFactory.beginTransaction();
trackerDAO.updateTrackerGroupIdANDStatus(res.getTraccarGroupId(), groupId, tenantId, 1);
TrackerManagementDAOFactory.commitTransaction();
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg="Could not update the traccar group";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection .";
log.error(msg, e);
throw new TraccarConfigurationException(msg, e);
} finally{
TrackerManagementDAOFactory.closeConnection();
}
}else{
JSONObject obj = new JSONObject(res);
JSONObject payload = new JSONObject();
payload.put("id", obj.getInt("traccarGroupId"));
payload.put("name", groupInfo.getName());
payload.put("attributes", new JSONObject());
String method = TraccarHandlerConstants.Methods.PUT;
String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId");
executor.submit(new OkHttpClientThreadPool(url, payload, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
//executor.shutdown();
}
}
/**
* Add Traccar Device operation.
* @param groupId
* @throws TraccarConfigurationException Failed while add Traccar Device the operation
*/
public void deleteGroup(int groupId, int tenantId) throws TraccarConfigurationException, ExecutionException, InterruptedException {
TrackerGroupInfo res = null;
JSONObject obj = null;
try {
TrackerManagementDAOFactory.beginTransaction();
res = trackerDAO.getTrackerGroup(groupId, tenantId);
if(res!=null){
obj = new JSONObject(res);
if(obj!=null){
trackerDAO.removeTrackerGroup(obj.getInt("id"));
TrackerManagementDAOFactory.commitTransaction();
String method = TraccarHandlerConstants.Methods.DELETE;
String url = defaultPort+"/api/groups/"+obj.getInt("traccarGroupId");
executor.submit(new OkHttpClientThreadPool(url, null, method,
authorizedKey(HttpReportingUtil.trackerUser(), HttpReportingUtil.trackerPassword()),
serverUrl(HttpReportingUtil.trackerServer())));
//executor.shutdown();
}
}
} catch (TransactionManagementException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred establishing the DB connection";
log.error(msg, e);
} catch (TrackerManagementDAOException e) {
TrackerManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while mapping with groupId";
log.error(msg, e);
} finally {
TrackerManagementDAOFactory.closeConnection();
}
}
public String generateRandomString(int len) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(chars.charAt(rnd.nextInt(chars.length())));
return sb.toString();
}
private TraccarGateway getTraccarGateway(){
return TraccarConfigurationManager.getInstance().getTraccarConfig().getTraccarGateway(
TraccarHandlerConstants.TraccarConfig.GATEWAY_NAME);
}
public String authorizedKey(String trackerUser, String trackerPassword) {
String newAuthorizationKey = authorizationKey;
if(trackerUser!=null && trackerPassword!=null){
newAuthorizationKey= trackerUser+':'+trackerPassword;
byte[] result = newAuthorizationKey.getBytes();
byte[] res = Base64.encodeBase64(result);
newAuthorizationKey = "Basic " + new String(res);
}
return newAuthorizationKey;
}
public String serverUrl(String serverUrl) {
String newServerUri = endpoint;
if(serverUrl!=null){
newServerUri= serverUrl;
}
return newServerUri;
}
}

@ -0,0 +1,179 @@
/*
* 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.api.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;
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.exceptions.DeviceManagementException;
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.core.dao.TrackerManagementDAOException;
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.common.beans.TraccarDevice;
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.TraccarUser;
import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfigurationException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class DeviceAPIClientServiceImpl implements DeviceAPIClientService {
private static final Log log = LogFactory.getLog(DeviceAPIClientServiceImpl.class);
public void addDevice(Device device, int tenantId) throws ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
String lastUpdatedTime = String.valueOf((new Date().getTime()));
TraccarDevice traccarDevice = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(),
"online", "false", lastUpdatedTime, "", "", "", "",
"", "");
try {
client.addDevice(traccarDevice, tenantId);
} catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with deviceId";
log.error(msg, e);
} catch (TrackerAlreadyExistException e) {
String msg = "The device already exist";
log.error(msg, e);
}
}
public void updateLocation(Device device, DeviceLocation deviceLocation, int tenantId) throws ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
TraccarPosition traccarPosition = new TraccarPosition(device.getDeviceIdentifier(),
deviceLocation.getUpdatedTime().getTime(),
deviceLocation.getLatitude(), deviceLocation.getLongitude(),
deviceLocation.getBearing(), deviceLocation.getSpeed());
String lastUpdatedTime = String.valueOf((new Date().getTime()));
TraccarDevice traccarDevice = new TraccarDevice(device.getId(), device.getName(), device.getDeviceIdentifier(),
"online", "false", lastUpdatedTime, "", "", "", "",
"", "");
try {
client.updateLocation(traccarDevice, traccarPosition, tenantId);
} catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with deviceId";
log.error(msg, e);
}catch (TrackerAlreadyExistException e) {
String msg = "The device already exist";
log.error(msg, e);
}
}
public void disEnrollDevice(int deviceId, int tenantId) {
TraccarClientImpl client = new TraccarClientImpl();
try {
client.disEnrollDevice(deviceId, tenantId);
} catch (TraccarConfigurationException e) {
String msg = "Error occurred while dis-enrolling the device";
log.error(msg, e);
}
}
public void addGroup(DeviceGroup group, int groupId, int tenantId) throws
TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
TraccarGroups traccarGroups = new TraccarGroups(group.getName());
client.addGroup(traccarGroups, groupId, tenantId);
}
public void updateGroup(DeviceGroup group, int groupId, int tenantId) throws TraccarConfigurationException, TrackerAlreadyExistException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
TraccarGroups traccarGroups = new TraccarGroups(group.getName());
client.updateGroup(traccarGroups, groupId, tenantId);
}
public void deleteGroup(int groupId, int tenantId) throws
TraccarConfigurationException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
client.deleteGroup(groupId, tenantId);
}
public static String fetchUserInfo(String userName) throws ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
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
TrackerManagementDAOException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
return client.createUser(traccarUser);
}
public static String updateUser(TraccarUser traccarUser, int userId) throws
TrackerManagementDAOException, ExecutionException, InterruptedException {
TraccarClientImpl client = new TraccarClientImpl();
return client.updateUser(traccarUser, userId);
}
public static String returnUser(String userName) {
TraccarClientImpl client = new TraccarClientImpl();
try {
return client.returnUser(userName);
} catch (TrackerManagementDAOException e) {
JSONObject obj = new JSONObject();
String msg = "Error occurred while creating a user: "+ e;
obj.put("error", msg);
return obj.toString();
}
}
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) {
TraccarClientImpl client = new TraccarClientImpl();
return client.generateRandomString(len);
}
}

@ -0,0 +1,55 @@
/*
* 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;
public class TraccarHandlerConstants {
public static class TraccarConfig {
public static final String TRACCAR_CONFIG_XML_NAME = "traccar-config.xml";
public static final String GATEWAY_NAME = "sample";
public static final String ENDPOINT = "api-endpoint";
public static final String AUTHORIZATION = "authorization";
public static final String AUTHORIZATION_KEY = "authorization-key";
public static final String DEFAULT_PORT = "default-port";
public static final String LOCATION_UPDATE_PORT = "location-update-port";
}
public static class Methods {
public static final String POST = "POST";
public static final String GET = "GET";
public static final String PUT = "PUT";
public static final String DELETE = "DELETE";
}
public static class Types {
public static final String DEVICE = "DEVICE";
public static final String GROUP = "GROUP";
public static final String USER = "USER";
public static final String PERMISSION = "PERMISSION";
public static final String USER_NOT_FOUND = "USER_NOT_FOUND";
public static final int DEFAULT_RANDOM = 10;
public static final int TRACCAR_TOKEN = 32;
public static final int REMOVE_TYPE_MULTIPLE = -1;
public static final int REMOVE_TYPE_SINGLE = 1;
}
}

@ -0,0 +1,112 @@
/*
* 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.beans;
public class TraccarDevice {
private int id;
private String deviceIdentifier;
private String deviceName;
private String uniqueId;
private String status;
private String disabled;
private String lastUpdate;
private String positionId;
private String groupId;
private String phone;
private String model;
private String contact;
private String category;
public TraccarDevice(String deviceIdentifier){
this.deviceIdentifier =deviceIdentifier;
}
public TraccarDevice(int id, String deviceName, String uniqueId, String status, String disabled, String lastUpdate,
String positionId, String groupId, String phone, String model, String contact,
String category){
this.id =id;
this.deviceName =deviceName;
this.uniqueId=uniqueId;
this.status=status;
this.disabled =disabled;
this.lastUpdate =lastUpdate;
this.positionId =positionId;
this.groupId =groupId;
this.phone =phone;
this.model =model;
this.contact =contact;
this.category =category;
}
public TraccarDevice(){ }
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getDeviceIdentifier() {return deviceIdentifier;}
public void setDeviceIdentifier(String deviceIdentifier) {this.deviceIdentifier = deviceIdentifier;}
public String getDeviceName() {return deviceName;}
public void setDeviceName(String deviceName) {this.deviceName = deviceName;}
public String getUniqueId() {return uniqueId;}
public void setUniqueId(String uniqueId) {this.uniqueId = uniqueId;}
public String getStatus() {return status;}
public void setStatus(String status) {this.status = status;}
public String getDisabled() {return disabled;}
public void setDisabled(String disabled) {this.disabled = disabled;}
public String getLastUpdate() {return lastUpdate;}
public void setLastUpdate(String lastUpdate) {this.lastUpdate = lastUpdate;}
public String getPhone() {return phone;}
public void setPhone(String phone) {this.phone = phone;}
public String getModel() {return model;}
public void setModel(String model) {this.model = model;}
public String getContact() {return contact;}
public void setContact(String contact) {this.contact = contact;}
public String getCategory() {return category;}
public void setCategory(String category) {this.category = category;}
public String getPositionId() {return positionId;}
public void setPositionId(String positionId) {this.positionId = positionId;}
public String getGroupId() {return groupId;}
public void setGroupId(String groupId) {this.groupId = groupId;}
}

@ -0,0 +1,50 @@
/*
* 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.beans;
public class TraccarGroups {
private String name;
private int groupId;
public TraccarGroups(String name){
this.name =name;
}
public TraccarGroups(String name, int groupId){
this.name =name;
this.groupId =groupId;
}
public TraccarGroups(){ }
public String getName() { return name; }
public void setName(String name) {
this.name = name;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
}

@ -0,0 +1,109 @@
/*
* 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.beans;
public class TraccarPosition {
private int id;
private String deviceIdentifier;
private Long timestamp;
private Double lat;
private Double lon;
private Float bearing;
private Float speed;
public TraccarPosition(int id, String deviceIdentifier, long timestamp, Double lat, Double lon,
float bearing, float speed){
this.id =id;
this.deviceIdentifier =deviceIdentifier;
this.timestamp=timestamp;
this.lat=lat;
this.lon =lon;
this.bearing =bearing;
this.speed =speed;
}
public TraccarPosition(String deviceIdentifier, long timestamp, Double lat, Double lon,
float bearing, float speed){
this.deviceIdentifier =deviceIdentifier;
this.timestamp=timestamp;
this.lat=lat;
this.lon =lon;
this.bearing =bearing;
this.speed =speed;
}
public TraccarPosition(){ }
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDeviceIdentifier() {
return deviceIdentifier;
}
public void setDeviceIdentifier(String deviceIdentifier) {
this.deviceIdentifier = deviceIdentifier;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Float getBearing() {
return bearing;
}
public void setBearing(Float bearing) {
this.bearing = bearing;
}
public Float getSpeed() {
return speed;
}
public void setSpeed(Float speed) {
this.speed = speed;
}
}

@ -0,0 +1,176 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.core.traccar.common.beans;
import java.io.Serializable;
public class TraccarUser implements Serializable {
private static final long serialVersionUID = 1998101712L;
private int id;
private String name;
private String login;
private String email;
private String phone;
private Boolean readonly;
private Boolean administrator;
private Boolean disabled;
private String expirationTime;
private int deviceLimit;
private int userLimit;
private Boolean deviceReadonly;
private String token;
private String password;
public TraccarUser() {
}
public TraccarUser(String name, String login, String email, String phone, Boolean readonly, Boolean administrator,
Boolean disabled, String expirationTime, int deviceLimit, int userLimit,
Boolean deviceReadonly, String token, String password) {
this.name = name;
this.login = login;
this.email = email;
this.phone = phone;
this.readonly = readonly;
this.administrator = administrator;
this.disabled = disabled;
this.expirationTime = expirationTime;
this.deviceLimit = deviceLimit;
this.userLimit = userLimit;
this.deviceReadonly = deviceReadonly;
this.token = token;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Boolean getReadonly() {
return readonly;
}
public void setReadonly(Boolean readonly) {
this.readonly = readonly;
}
public Boolean getAdministrator() {
return administrator;
}
public void setAdministrator(Boolean administrator) {
this.administrator = administrator;
}
public Boolean getDisabled() {
return disabled;
}
public void setDisabled(Boolean disabled) {
this.disabled = disabled;
}
public String getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(String expirationTime) {
this.expirationTime = expirationTime;
}
public int getDeviceLimit() {
return deviceLimit;
}
public void setDeviceLimit(int deviceLimit) {
this.deviceLimit = deviceLimit;
}
public int getUserLimit() {
return userLimit;
}
public void setUserLimit(int userLimit) {
this.userLimit = userLimit;
}
public Boolean getDeviceReadonly() {
return deviceReadonly;
}
public void setDeviceReadonly(Boolean deviceReadonly) {
this.deviceReadonly = deviceReadonly;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

@ -0,0 +1,49 @@
/*
* 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.config;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
@XmlRootElement(name = "Property")
public class Property {
private String name;
private String value;
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

@ -0,0 +1,68 @@
/*
* 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.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "TraccarConfiguration")
public class TraccarConfiguration {
private List<TraccarGateway> traccarGateways;
@XmlElementWrapper(name = "Gateways")
@XmlElement(name = "Gateway")
public List<TraccarGateway> getTraccarGateways() {
return traccarGateways;
}
public void setTraccarGateways(List<TraccarGateway> traccarGateways) {
this.traccarGateways = traccarGateways;
}
/**
* Retrieve the default Traccar Gateway as defined in the Traccar configuration.
* @return default {@link TraccarGateway}
*/
public TraccarGateway getDefaultTraccarGateway() {
for (TraccarGateway traccarGateway : traccarGateways) {
if (traccarGateway.isDefault()) {
return traccarGateway;
}
}
return null;
}
/**
* Retrieve Traccar Gateway by the provided Gateway Name
* @param gatewayName has the name of the Gateway to be retrieved
* @return retrieved {@link TraccarGateway}
*/
public TraccarGateway getTraccarGateway(String gatewayName) {
for (TraccarGateway traccarGateway : traccarGateways) {
if (gatewayName.equals(traccarGateway.getName())) {
return traccarGateway;
}
}
return null;
}
}

@ -0,0 +1,38 @@
/*
* 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.config;
public class TraccarConfigurationException extends Exception {
public TraccarConfigurationException() {
super();
}
public TraccarConfigurationException(String message) {
super(message);
}
public TraccarConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public TraccarConfigurationException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,87 @@
/*
* 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.config;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement(name = "Gateway")
public class TraccarGateway {
private String name;
private String extensionClass;
private boolean isDefault;
private List<Property> properties;
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlAttribute(name = "extensionClass")
public String getExtensionClass() {
return extensionClass;
}
public void setExtensionClass(String extensionClass) {
this.extensionClass = extensionClass;
}
@XmlAttribute(name = "isDefault")
public boolean isDefault() {
return isDefault;
}
public void setDefault(boolean aDefault) {
isDefault = aDefault;
}
@XmlElementWrapper(name = "Properties")
@XmlElement(name = "Property")
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
/**
* Retrives the Property based on the provided property name
* @param propertyName has the name of the Property to be retrieved
* @return retrieved {@link Property}
*/
public Property getPropertyByName(String propertyName) {
for (Property property : properties) {
if (propertyName.equals(property.getName())) {
return property;
}
}
return null;
}
}

@ -0,0 +1,69 @@
/*
* 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;
import org.json.JSONObject;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarDevice;
import org.wso2.carbon.device.mgt.core.traccar.common.beans.TraccarUser;
import java.util.ArrayList;
import java.util.List;
public class TraccarUtil {
public static JSONObject TraccarUserPayload(TraccarUser traccarUser){
JSONObject payload = new JSONObject();
JSONObject attribute = new JSONObject();
attribute.put("speedUnit", "kmh");
payload.put("id", traccarUser.getId());
payload.put("name", traccarUser.getName());
payload.put("login", traccarUser.getLogin());
payload.put("email", traccarUser.getEmail());
payload.put("password", traccarUser.getPassword());
payload.put("token", traccarUser.getToken());
payload.put("administrator", traccarUser.getAdministrator());
payload.put("deviceLimit", traccarUser.getDeviceLimit());
payload.put("userLimit", traccarUser.getUserLimit());
payload.put("disabled", traccarUser.getDisabled());
payload.put("deviceReadonly", traccarUser.getDeviceReadonly());
payload.put("readonly", traccarUser.getReadonly());
payload.put("expirationTime", traccarUser.getExpirationTime());
payload.put("attributes", attribute);
return payload;
}
public static JSONObject TraccarDevicePayload(TraccarDevice deviceInfo){
JSONObject payload = new JSONObject();
payload.put("name", deviceInfo.getDeviceName());
payload.put("uniqueId", deviceInfo.getUniqueId());
payload.put("status", deviceInfo.getStatus());
payload.put("disabled", deviceInfo.getDisabled());
payload.put("lastUpdate", deviceInfo.getLastUpdate());
payload.put("positionId", deviceInfo.getPositionId());
payload.put("groupId", deviceInfo.getGroupId());
payload.put("phone", deviceInfo.getPhone());
payload.put("model", deviceInfo.getModel());
payload.put("contact", deviceInfo.getContact());
payload.put("category", deviceInfo.getCategory());
List<String> geoFenceIds = new ArrayList<>();
payload.put("geofenceIds", geoFenceIds);
payload.put("attributes", new JSONObject());
return payload;
}
}

@ -0,0 +1,102 @@
/*
* 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.core.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import org.wso2.carbon.device.mgt.core.traccar.common.config.TraccarConfiguration;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class TraccarConfigurationManager {
private static final Log log = LogFactory.getLog(TraccarConfigurationManager.class);
private static TraccarConfigurationManager traccarConfigurationManager;
private TraccarConfiguration traccarConfiguration;
private static final String CarbonUtilsFile = CarbonUtils.getCarbonConfigDirPath() + File.separator;
private static final String TRACCAR_CONFIG_PATH = CarbonUtilsFile + TraccarHandlerConstants.TraccarConfig.TRACCAR_CONFIG_XML_NAME;
/**
* Retrieve an instance of {@link TraccarConfigurationManager}
* @return an instance of {@link TraccarConfigurationManager}
*/
public static TraccarConfigurationManager getInstance() {
if (traccarConfigurationManager == null) {
synchronized (TraccarConfigurationManager.class) {
if (traccarConfigurationManager == null) {
traccarConfigurationManager = new TraccarConfigurationManager();
}
}
}
return traccarConfigurationManager;
}
/**
* Initialize the Traccar Configuration through the provided configuration location
* @param configLocation has the path of the Traccar configuration file
* @throws DeviceManagementException throws when there are any errors during the initialization of
* Traccar configuration
*/
public synchronized void initConfig(String configLocation) throws DeviceManagementException {
try {
File traccarConfig = new File(configLocation);
Document doc = DeviceManagerUtil.convertToDocument(traccarConfig);
//Un-marshaling Traccar configuration
JAXBContext traccarContext = JAXBContext.newInstance(TraccarConfiguration.class);
Unmarshaller unmarshaller = traccarContext.createUnmarshaller();
this.traccarConfiguration = (TraccarConfiguration) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
String msg = "Error occurred while initializing Traccar config '" + configLocation + "'";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
}
/**
* Initialize the Traccar Configuration through the traccar-config.xml file in the TRACCAR_CONFIG_PATH
* @throws DeviceManagementException throws when there are any errors during the initialization of
* Traccar configuration
*/
public void initConfig() throws DeviceManagementException {
this.initConfig(TRACCAR_CONFIG_PATH);
}
/**
* Retrieves the initialized {@link TraccarConfiguration}
* @return the initialized {@link TraccarConfiguration}
*/
public TraccarConfiguration getTraccarConfig() {
try{
initConfig();
}catch (Exception e){
log.error("TraccarConfiguration:", e);
}
return traccarConfiguration;
}
}

@ -34,6 +34,11 @@ public class HttpReportingUtil {
private static final Log log = LogFactory.getLog(HttpReportingUtil.class); private static final Log log = LogFactory.getLog(HttpReportingUtil.class);
private static final String IS_EVENT_PUBLISHING_ENABLED = "isEventPublishingEnabled"; private static final String IS_EVENT_PUBLISHING_ENABLED = "isEventPublishingEnabled";
private static final String IS_TRACKER_ENABLED = "isTrackerEnabled";
private static final String IS_LOCATION_PUBLISHING_ENABLED = "isLocationPublishingEnabled";
private static final String TRACKER_SERVER_URI = "trackerServer";
private static final String TRACKER_PASSWORD = "trackerPassword";
private static final String TRACKER_USER = "trackerUsername";
public static String getReportingHost() { public static String getReportingHost() {
return System.getProperty(DeviceManagementConstants.Report.REPORTING_EVENT_HOST); return System.getProperty(DeviceManagementConstants.Report.REPORTING_EVENT_HOST);
@ -62,4 +67,44 @@ public class HttpReportingUtil {
} }
return false; return false;
} }
public static boolean isLocationPublishing() {
Object configuration = DeviceManagerUtil.getConfiguration(IS_LOCATION_PUBLISHING_ENABLED);
if (configuration != null) {
return Boolean.valueOf(configuration.toString());
}
return false;
}
public static boolean isTrackerEnabled() {
Object configuration = DeviceManagerUtil.getConfiguration(IS_TRACKER_ENABLED);
if (configuration != null) {
return Boolean.valueOf(configuration.toString());
}
return false;
}
public static String trackerServer() {
Object configuration = DeviceManagerUtil.getConfiguration(TRACKER_SERVER_URI);
if (configuration != null) {
return configuration.toString();
}
return null;
}
public static String trackerPassword() {
Object configuration = DeviceManagerUtil.getConfiguration(TRACKER_PASSWORD);
if (configuration != null) {
return configuration.toString();
}
return null;
}
public static String trackerUser() {
Object configuration = DeviceManagerUtil.getConfiguration(TRACKER_USER);
if (configuration != null) {
return configuration.toString();
}
return null;
}
} }

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<TraccarConfiguration>
<Gateways>
<!-- multiple gateways can be listed and the gateway having the isDefault=true is picked up or gateway
extensionClass can be passed and relevant impl can be used-->
<Gateway name="sample" extensionClass="org.wso2.carbon.device.mgt.core.traccar" isDefault="true">
<!-- properties can be listed and can be picked up in the relevant implementation class as required-->
<Properties>
<Property name="sample-property">sample</Property>
<Property name="api-endpoint">http://localhost:</Property>
<Property name="default-port"></Property>
<Property name="location-update-port">5055</Property>
<Property name="authorization">Authorization</Property>
<Property name="authorization-key">Basic YWRtaW46YWRtaW4=</Property>
</Properties>
</Gateway>
</Gateways>
</TraccarConfiguration>

@ -574,3 +574,31 @@ CREATE TABLE IF NOT EXISTS DM_BILLING (
CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
); );
-- DM_EXT_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
TRACCAR_GROUP_ID INT DEFAULT 0,
GROUP_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
STATUS INT DEFAULT 0,
PRIMARY KEY (ID)
);
-- END OF DM_EXT_GROUP_MAPPING TABLE--
-- END OF DM_EXT_DEVICE_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
TRACCAR_DEVICE_ID INT DEFAULT 0,
DEVICE_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
STATUS INT DEFAULT 0,
PRIMARY KEY (ID)
);
-- END OF DM_EXT_DEVICE_MAPPING TABLE--
-- END OF DM_EXT_PERMISSION_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING (
TRACCAR_DEVICE_ID INT DEFAULT 0,
TRACCAR_USER_ID INT DEFAULT 0
);
-- END OF DM_EXT_PERMISSION_MAPPING TABLE--

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2022, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<TraccarConfiguration>
<Gateways>
<!-- multiple gateways can be listed and the gateway having the isDefault=true is picked up or gateway
extensionClass can be passed and relevant impl can be used-->
<Gateway name="sample" extensionClass="org.wso2.carbon.device.mgt.core.traccar" isDefault="true">
<!-- properties can be listed and can be picked up in the relevant implementation class as required-->
<Properties>
<Property name="sample-property">sample</Property>
<Property name="api-endpoint">http://localhost:</Property>
<Property name="default-port"></Property>
<Property name="location-update-port">5055</Property>
<Property name="authorization">Authorization</Property>
<Property name="authorization-key">Basic YWRtaW46YWRtaW4=</Property>
</Properties>
</Gateway>
</Gateways>
</TraccarConfiguration>

@ -748,3 +748,32 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING (
); );
-- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- -- END OF DM_GEOFENCE_GROUP_MAPPING TABLE--
-- DM_EXT_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
TRACCAR_GROUP_ID INT DEFAULT 0,
GROUP_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
STATUS INT DEFAULT 0,
PRIMARY KEY (ID)
);
-- END OF DM_EXT_GROUP_MAPPING TABLE--
-- END OF DM_EXT_DEVICE_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
TRACCAR_DEVICE_ID INT DEFAULT 0,
DEVICE_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
STATUS INT DEFAULT 0,
PRIMARY KEY (ID)
);
-- END OF DM_EXT_DEVICE_MAPPING TABLE--
-- END OF DM_EXT_PERMISSION_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING (
TRACCAR_DEVICE_ID INT DEFAULT 0,
TRACCAR_USER_ID INT DEFAULT 0
);
-- END OF DM_EXT_PERMISSION_MAPPING TABLE--

@ -812,3 +812,32 @@ CREATE TABLE IF NOT EXISTS DM_GEOFENCE_EVENT_MAPPING (
) ENGINE=InnoDB; ) ENGINE=InnoDB;
-- END OF DM_GEOFENCE_GROUP_MAPPING TABLE-- -- END OF DM_GEOFENCE_GROUP_MAPPING TABLE--
-- DM_EXT_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
TRACCAR_GROUP_ID INT DEFAULT 0,
GROUP_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
STATUS INT DEFAULT 0,
PRIMARY KEY (ID)
);
-- END OF DM_EXT_GROUP_MAPPING TABLE--
-- END OF DM_EXT_DEVICE_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_DEVICE_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
TRACCAR_DEVICE_ID INT DEFAULT 0,
DEVICE_ID INT NOT NULL,
TENANT_ID INT NOT NULL,
STATUS INT DEFAULT 0,
PRIMARY KEY (ID)
);
-- END OF DM_EXT_DEVICE_MAPPING TABLE--
-- END OF DM_EXT_PERMISSION_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_PERMISSION_MAPPING (
TRACCAR_DEVICE_ID INT DEFAULT 0,
TRACCAR_USER_ID INT DEFAULT 0
);
-- END OF DM_EXT_PERMISSION_MAPPING TABLE--

@ -11,3 +11,4 @@ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../featur
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/resources/email-templates);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/resources/email-templates);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/email/templates,target:${installFolder}/../../../repository/resources/email-templates,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf_templates/,target:${installFolder}/../../resources/conf/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.basics_${feature.version}/conf/traccar-config.xml,target:${installFolder}/../../conf/traccar-config.xml,overwrite:true);\

Loading…
Cancel
Save